You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

accounts.go 59KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "unicode"
  15. "github.com/oragono/oragono/irc/connection_limits"
  16. "github.com/oragono/oragono/irc/email"
  17. "github.com/oragono/oragono/irc/modes"
  18. "github.com/oragono/oragono/irc/passwd"
  19. "github.com/oragono/oragono/irc/utils"
  20. "github.com/tidwall/buntdb"
  21. )
  22. const (
  23. keyAccountExists = "account.exists %s"
  24. keyAccountVerified = "account.verified %s"
  25. keyAccountUnregistered = "account.unregistered %s"
  26. keyAccountCallback = "account.callback %s"
  27. keyAccountVerificationCode = "account.verificationcode %s"
  28. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  29. keyAccountRegTime = "account.registered.time %s"
  30. keyAccountCredentials = "account.credentials %s"
  31. keyAccountAdditionalNicks = "account.additionalnicks %s"
  32. keyAccountSettings = "account.settings %s"
  33. keyAccountVHost = "account.vhost %s"
  34. keyCertToAccount = "account.creds.certfp %s"
  35. keyAccountChannels = "account.channels %s" // channels registered to the account
  36. keyAccountJoinedChannels = "account.joinedto %s" // channels a persistent client has joined
  37. keyAccountLastSeen = "account.lastseen %s"
  38. keyAccountModes = "account.modes %s" // user modes for the always-on client as a string
  39. keyAccountRealname = "account.realname %s" // client realname stored as string
  40. keyVHostQueueAcctToId = "vhostQueue %s"
  41. vhostRequestIdx = "vhostQueue"
  42. maxCertfpsPerAccount = 5
  43. )
  44. // everything about accounts is persistent; therefore, the database is the authoritative
  45. // source of truth for all account information. anything on the heap is just a cache
  46. type AccountManager struct {
  47. // XXX these are up here so they can be aligned to a 64-bit boundary, please forgive me
  48. // autoincrementing ID for vhost requests:
  49. vhostRequestID uint64
  50. vhostRequestPendingCount uint64
  51. sync.RWMutex // tier 2
  52. serialCacheUpdateMutex sync.Mutex // tier 3
  53. vHostUpdateMutex sync.Mutex // tier 3
  54. server *Server
  55. // track clients logged in to accounts
  56. accountToClients map[string][]*Client
  57. nickToAccount map[string]string
  58. skeletonToAccount map[string]string
  59. accountToMethod map[string]NickEnforcementMethod
  60. registerThrottle connection_limits.GenericThrottle
  61. }
  62. func (am *AccountManager) Initialize(server *Server) {
  63. am.accountToClients = make(map[string][]*Client)
  64. am.nickToAccount = make(map[string]string)
  65. am.skeletonToAccount = make(map[string]string)
  66. am.accountToMethod = make(map[string]NickEnforcementMethod)
  67. am.server = server
  68. config := server.Config()
  69. am.buildNickToAccountIndex(config)
  70. am.initVHostRequestQueue(config)
  71. am.createAlwaysOnClients(config)
  72. am.resetRegisterThrottle(config)
  73. }
  74. func (am *AccountManager) resetRegisterThrottle(config *Config) {
  75. am.Lock()
  76. defer am.Unlock()
  77. am.registerThrottle = connection_limits.GenericThrottle{
  78. Duration: config.Accounts.Registration.Throttling.Duration,
  79. Limit: config.Accounts.Registration.Throttling.MaxAttempts,
  80. }
  81. }
  82. func (am *AccountManager) touchRegisterThrottle() (throttled bool) {
  83. am.Lock()
  84. defer am.Unlock()
  85. throttled, _ = am.registerThrottle.Touch()
  86. return
  87. }
  88. func (am *AccountManager) createAlwaysOnClients(config *Config) {
  89. if config.Accounts.Multiclient.AlwaysOn == PersistentDisabled {
  90. return
  91. }
  92. verifiedPrefix := fmt.Sprintf(keyAccountVerified, "")
  93. am.serialCacheUpdateMutex.Lock()
  94. defer am.serialCacheUpdateMutex.Unlock()
  95. var accounts []string
  96. am.server.store.View(func(tx *buntdb.Tx) error {
  97. err := tx.AscendGreaterOrEqual("", verifiedPrefix, func(key, value string) bool {
  98. if !strings.HasPrefix(key, verifiedPrefix) {
  99. return false
  100. }
  101. account := strings.TrimPrefix(key, verifiedPrefix)
  102. accounts = append(accounts, account)
  103. return true
  104. })
  105. return err
  106. })
  107. for _, accountName := range accounts {
  108. account, err := am.LoadAccount(accountName)
  109. if err == nil && account.Verified &&
  110. persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, account.Settings.AlwaysOn) {
  111. am.server.AddAlwaysOnClient(
  112. account,
  113. am.loadChannels(accountName),
  114. am.loadLastSeen(accountName),
  115. am.loadModes(accountName),
  116. am.loadRealname(accountName),
  117. )
  118. }
  119. }
  120. }
  121. func (am *AccountManager) buildNickToAccountIndex(config *Config) {
  122. if !config.Accounts.NickReservation.Enabled {
  123. return
  124. }
  125. nickToAccount := make(map[string]string)
  126. skeletonToAccount := make(map[string]string)
  127. accountToMethod := make(map[string]NickEnforcementMethod)
  128. existsPrefix := fmt.Sprintf(keyAccountExists, "")
  129. am.serialCacheUpdateMutex.Lock()
  130. defer am.serialCacheUpdateMutex.Unlock()
  131. err := am.server.store.View(func(tx *buntdb.Tx) error {
  132. err := tx.AscendGreaterOrEqual("", existsPrefix, func(key, value string) bool {
  133. if !strings.HasPrefix(key, existsPrefix) {
  134. return false
  135. }
  136. account := strings.TrimPrefix(key, existsPrefix)
  137. if _, err := tx.Get(fmt.Sprintf(keyAccountVerified, account)); err == nil {
  138. nickToAccount[account] = account
  139. accountName, err := tx.Get(fmt.Sprintf(keyAccountName, account))
  140. if err != nil {
  141. am.server.logger.Error("internal", "missing account name for", account)
  142. } else {
  143. skeleton, _ := Skeleton(accountName)
  144. skeletonToAccount[skeleton] = account
  145. }
  146. }
  147. if rawNicks, err := tx.Get(fmt.Sprintf(keyAccountAdditionalNicks, account)); err == nil {
  148. additionalNicks := unmarshalReservedNicks(rawNicks)
  149. for _, nick := range additionalNicks {
  150. cfnick, _ := CasefoldName(nick)
  151. nickToAccount[cfnick] = account
  152. skeleton, _ := Skeleton(nick)
  153. skeletonToAccount[skeleton] = account
  154. }
  155. }
  156. if rawPrefs, err := tx.Get(fmt.Sprintf(keyAccountSettings, account)); err == nil {
  157. var prefs AccountSettings
  158. err := json.Unmarshal([]byte(rawPrefs), &prefs)
  159. if err == nil && prefs.NickEnforcement != NickEnforcementOptional {
  160. accountToMethod[account] = prefs.NickEnforcement
  161. } else if err != nil {
  162. am.server.logger.Error("internal", "corrupt account creds", account)
  163. }
  164. }
  165. return true
  166. })
  167. return err
  168. })
  169. if config.Accounts.NickReservation.Method == NickEnforcementStrict {
  170. unregisteredPrefix := fmt.Sprintf(keyAccountUnregistered, "")
  171. am.server.store.View(func(tx *buntdb.Tx) error {
  172. tx.AscendGreaterOrEqual("", unregisteredPrefix, func(key, value string) bool {
  173. if !strings.HasPrefix(key, unregisteredPrefix) {
  174. return false
  175. }
  176. account := strings.TrimPrefix(key, unregisteredPrefix)
  177. accountName := value
  178. nickToAccount[account] = account
  179. skeleton, _ := Skeleton(accountName)
  180. skeletonToAccount[skeleton] = account
  181. return true
  182. })
  183. return nil
  184. })
  185. }
  186. if err != nil {
  187. am.server.logger.Error("internal", "couldn't read reserved nicks", err.Error())
  188. } else {
  189. am.Lock()
  190. am.nickToAccount = nickToAccount
  191. am.skeletonToAccount = skeletonToAccount
  192. am.accountToMethod = accountToMethod
  193. am.Unlock()
  194. }
  195. }
  196. func (am *AccountManager) initVHostRequestQueue(config *Config) {
  197. if !config.Accounts.VHosts.Enabled {
  198. return
  199. }
  200. am.vHostUpdateMutex.Lock()
  201. defer am.vHostUpdateMutex.Unlock()
  202. // the db maps the account name to the autoincrementing integer ID of its request
  203. // create an numerically ordered index on ID, so we can list the oldest requests
  204. // finally, collect the integer id of the newest request and the total request count
  205. var total uint64
  206. var lastIDStr string
  207. err := am.server.store.Update(func(tx *buntdb.Tx) error {
  208. err := tx.CreateIndex(vhostRequestIdx, fmt.Sprintf(keyVHostQueueAcctToId, "*"), buntdb.IndexInt)
  209. if err != nil {
  210. return err
  211. }
  212. return tx.Descend(vhostRequestIdx, func(key, value string) bool {
  213. if lastIDStr == "" {
  214. lastIDStr = value
  215. }
  216. total++
  217. return true
  218. })
  219. })
  220. if err != nil {
  221. am.server.logger.Error("internal", "could not create vhost queue index", err.Error())
  222. }
  223. lastID, _ := strconv.ParseUint(lastIDStr, 10, 64)
  224. am.server.logger.Debug("services", fmt.Sprintf("vhost queue length is %d, autoincrementing id is %d", total, lastID))
  225. atomic.StoreUint64(&am.vhostRequestID, lastID)
  226. atomic.StoreUint64(&am.vhostRequestPendingCount, total)
  227. }
  228. func (am *AccountManager) NickToAccount(nick string) string {
  229. cfnick, err := CasefoldName(nick)
  230. if err != nil {
  231. return ""
  232. }
  233. am.RLock()
  234. defer am.RUnlock()
  235. return am.nickToAccount[cfnick]
  236. }
  237. // given an account, combine stored enforcement method with the config settings
  238. // to compute the actual enforcement method
  239. func configuredEnforcementMethod(config *Config, storedMethod NickEnforcementMethod) (result NickEnforcementMethod) {
  240. if !config.Accounts.NickReservation.Enabled {
  241. return NickEnforcementNone
  242. }
  243. result = storedMethod
  244. // if they don't have a custom setting, or customization is disabled, use the default
  245. if result == NickEnforcementOptional || !config.Accounts.NickReservation.AllowCustomEnforcement {
  246. result = config.Accounts.NickReservation.Method
  247. }
  248. if result == NickEnforcementOptional {
  249. // enforcement was explicitly enabled neither in the config or by the user
  250. result = NickEnforcementNone
  251. }
  252. return
  253. }
  254. // Given a nick, looks up the account that owns it and the method (none/timeout/strict)
  255. // used to enforce ownership.
  256. func (am *AccountManager) EnforcementStatus(cfnick, skeleton string) (account string, method NickEnforcementMethod) {
  257. config := am.server.Config()
  258. if !config.Accounts.NickReservation.Enabled {
  259. return "", NickEnforcementNone
  260. }
  261. am.RLock()
  262. defer am.RUnlock()
  263. finalEnforcementMethod := func(account_ string) (result NickEnforcementMethod) {
  264. storedMethod := am.accountToMethod[account_]
  265. return configuredEnforcementMethod(config, storedMethod)
  266. }
  267. nickAccount := am.nickToAccount[cfnick]
  268. skelAccount := am.skeletonToAccount[skeleton]
  269. if nickAccount == "" && skelAccount == "" {
  270. return "", NickEnforcementNone
  271. } else if nickAccount != "" && (skelAccount == nickAccount || skelAccount == "") {
  272. return nickAccount, finalEnforcementMethod(nickAccount)
  273. } else if skelAccount != "" && nickAccount == "" {
  274. return skelAccount, finalEnforcementMethod(skelAccount)
  275. } else {
  276. // nickAccount != skelAccount and both are nonempty:
  277. // two people have competing claims on (this casefolding of) this nick!
  278. nickMethod := finalEnforcementMethod(nickAccount)
  279. skelMethod := finalEnforcementMethod(skelAccount)
  280. switch {
  281. case skelMethod == NickEnforcementNone:
  282. return nickAccount, nickMethod
  283. case nickMethod == NickEnforcementNone:
  284. return skelAccount, skelMethod
  285. default:
  286. // nobody can use this nick
  287. return "!", NickEnforcementStrict
  288. }
  289. }
  290. }
  291. // Sets a custom enforcement method for an account and stores it in the database.
  292. func (am *AccountManager) SetEnforcementStatus(account string, method NickEnforcementMethod) (finalSettings AccountSettings, err error) {
  293. config := am.server.Config()
  294. if !(config.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.AllowCustomEnforcement) {
  295. err = errFeatureDisabled
  296. return
  297. }
  298. setter := func(in AccountSettings) (out AccountSettings, err error) {
  299. out = in
  300. out.NickEnforcement = method
  301. return out, nil
  302. }
  303. _, err = am.ModifyAccountSettings(account, setter)
  304. if err != nil {
  305. return
  306. }
  307. // this update of the data plane is racey, but it's probably fine
  308. am.Lock()
  309. defer am.Unlock()
  310. if method == NickEnforcementOptional {
  311. delete(am.accountToMethod, account)
  312. } else {
  313. am.accountToMethod[account] = method
  314. }
  315. return
  316. }
  317. func (am *AccountManager) AccountToClients(account string) (result []*Client) {
  318. cfaccount, err := CasefoldName(account)
  319. if err != nil {
  320. return
  321. }
  322. am.RLock()
  323. defer am.RUnlock()
  324. return am.accountToClients[cfaccount]
  325. }
  326. func (am *AccountManager) Register(client *Client, account string, callbackNamespace string, callbackValue string, passphrase string, certfp string) error {
  327. casefoldedAccount, err := CasefoldName(account)
  328. skeleton, skerr := Skeleton(account)
  329. if err != nil || skerr != nil || account == "" || account == "*" {
  330. return errAccountCreation
  331. }
  332. if restrictedCasefoldedNicks[casefoldedAccount] || restrictedSkeletons[skeleton] {
  333. return errAccountAlreadyRegistered
  334. }
  335. config := am.server.Config()
  336. // final "is registration allowed" check:
  337. if !(config.Accounts.Registration.Enabled || callbackNamespace == "admin") || am.server.Defcon() <= 4 {
  338. return errFeatureDisabled
  339. }
  340. if client != nil && client.Account() != "" {
  341. return errAccountAlreadyLoggedIn
  342. }
  343. if client != nil && am.touchRegisterThrottle() {
  344. am.server.logger.Warning("accounts", "global registration throttle exceeded by client", client.Nick())
  345. return errLimitExceeded
  346. }
  347. // if nick reservation is enabled, you can only register your current nickname
  348. // as an account; this prevents "land-grab" situations where someone else
  349. // registers your nick out from under you and then NS GHOSTs you
  350. // n.b. client is nil during a SAREGISTER
  351. // n.b. if ForceGuestFormat, then there's no concern, because you can't
  352. // register a guest nickname anyway, and the actual registration system
  353. // will prevent any double-register
  354. if client != nil && config.Accounts.NickReservation.Enabled &&
  355. !config.Accounts.NickReservation.ForceGuestFormat &&
  356. client.NickCasefolded() != casefoldedAccount {
  357. return errAccountMustHoldNick
  358. }
  359. // can't register a guest nickname
  360. if config.Accounts.NickReservation.guestRegexpFolded.MatchString(casefoldedAccount) {
  361. return errAccountAlreadyRegistered
  362. }
  363. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  364. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  365. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  366. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  367. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  368. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  369. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  370. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  371. var creds AccountCredentials
  372. creds.Version = 1
  373. err = creds.SetPassphrase(passphrase, am.server.Config().Accounts.Registration.BcryptCost)
  374. if err != nil {
  375. return err
  376. }
  377. creds.AddCertfp(certfp)
  378. credStr, err := creds.Serialize()
  379. if err != nil {
  380. return err
  381. }
  382. registeredTimeStr := strconv.FormatInt(time.Now().UnixNano(), 10)
  383. callbackSpec := fmt.Sprintf("%s:%s", callbackNamespace, callbackValue)
  384. var setOptions *buntdb.SetOptions
  385. ttl := time.Duration(config.Accounts.Registration.VerifyTimeout)
  386. if ttl != 0 {
  387. setOptions = &buntdb.SetOptions{Expires: true, TTL: ttl}
  388. }
  389. err = func() error {
  390. am.serialCacheUpdateMutex.Lock()
  391. defer am.serialCacheUpdateMutex.Unlock()
  392. // can't register an account with the same name as a registered nick
  393. if am.NickToAccount(casefoldedAccount) != "" {
  394. return errAccountAlreadyRegistered
  395. }
  396. return am.server.store.Update(func(tx *buntdb.Tx) error {
  397. if _, err := tx.Get(unregisteredKey); err == nil {
  398. return errAccountAlreadyUnregistered
  399. }
  400. _, err = am.loadRawAccount(tx, casefoldedAccount)
  401. if err != errAccountDoesNotExist {
  402. return errAccountAlreadyRegistered
  403. }
  404. if certfp != "" {
  405. // make sure certfp doesn't already exist because that'd be silly
  406. _, err := tx.Get(certFPKey)
  407. if err != buntdb.ErrNotFound {
  408. return errCertfpAlreadyExists
  409. }
  410. }
  411. tx.Set(accountKey, "1", setOptions)
  412. tx.Set(accountNameKey, account, setOptions)
  413. tx.Set(registeredTimeKey, registeredTimeStr, setOptions)
  414. tx.Set(credentialsKey, credStr, setOptions)
  415. tx.Set(callbackKey, callbackSpec, setOptions)
  416. if certfp != "" {
  417. tx.Set(certFPKey, casefoldedAccount, setOptions)
  418. }
  419. return nil
  420. })
  421. }()
  422. if err != nil {
  423. return err
  424. }
  425. code, err := am.dispatchCallback(client, account, callbackNamespace, callbackValue)
  426. if err != nil {
  427. am.Unregister(casefoldedAccount, true)
  428. return errCallbackFailed
  429. } else {
  430. return am.server.store.Update(func(tx *buntdb.Tx) error {
  431. _, _, err = tx.Set(verificationCodeKey, code, setOptions)
  432. return err
  433. })
  434. }
  435. }
  436. // validatePassphrase checks whether a passphrase is allowed by our rules
  437. func validatePassphrase(passphrase string) error {
  438. // sanity check the length
  439. if len(passphrase) == 0 || len(passphrase) > 300 {
  440. return errAccountBadPassphrase
  441. }
  442. // we use * as a placeholder in some places, if it's gotten this far then fail
  443. if passphrase == "*" {
  444. return errAccountBadPassphrase
  445. }
  446. // for now, just enforce that spaces are not allowed
  447. for _, r := range passphrase {
  448. if unicode.IsSpace(r) {
  449. return errAccountBadPassphrase
  450. }
  451. }
  452. return nil
  453. }
  454. // changes the password for an account
  455. func (am *AccountManager) setPassword(account string, password string, hasPrivs bool) (err error) {
  456. cfAccount, err := CasefoldName(account)
  457. if err != nil {
  458. return errAccountDoesNotExist
  459. }
  460. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  461. var credStr string
  462. am.server.store.View(func(tx *buntdb.Tx) error {
  463. // no need to check verification status here or below;
  464. // you either need to be auth'ed to the account or be an oper to do this
  465. credStr, err = tx.Get(credKey)
  466. return nil
  467. })
  468. if err != nil {
  469. return errAccountDoesNotExist
  470. }
  471. var creds AccountCredentials
  472. err = json.Unmarshal([]byte(credStr), &creds)
  473. if err != nil {
  474. return err
  475. }
  476. if !hasPrivs && creds.Empty() {
  477. return errCredsExternallyManaged
  478. }
  479. err = creds.SetPassphrase(password, am.server.Config().Accounts.Registration.BcryptCost)
  480. if err != nil {
  481. return err
  482. }
  483. if creds.Empty() && !hasPrivs {
  484. return errEmptyCredentials
  485. }
  486. newCredStr, err := creds.Serialize()
  487. if err != nil {
  488. return err
  489. }
  490. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  491. curCredStr, err := tx.Get(credKey)
  492. if credStr != curCredStr {
  493. return errCASFailed
  494. }
  495. _, _, err = tx.Set(credKey, newCredStr, nil)
  496. return err
  497. })
  498. return err
  499. }
  500. func (am *AccountManager) saveChannels(account string, channels []string) {
  501. channelsStr := strings.Join(channels, ",")
  502. key := fmt.Sprintf(keyAccountJoinedChannels, account)
  503. am.server.store.Update(func(tx *buntdb.Tx) error {
  504. tx.Set(key, channelsStr, nil)
  505. return nil
  506. })
  507. }
  508. func (am *AccountManager) loadChannels(account string) (channels []string) {
  509. key := fmt.Sprintf(keyAccountJoinedChannels, account)
  510. var channelsStr string
  511. am.server.store.View(func(tx *buntdb.Tx) error {
  512. channelsStr, _ = tx.Get(key)
  513. return nil
  514. })
  515. if channelsStr != "" {
  516. return strings.Split(channelsStr, ",")
  517. }
  518. return
  519. }
  520. func (am *AccountManager) saveModes(account string, uModes modes.Modes) {
  521. modeStr := uModes.String()
  522. key := fmt.Sprintf(keyAccountModes, account)
  523. am.server.store.Update(func(tx *buntdb.Tx) error {
  524. tx.Set(key, modeStr, nil)
  525. return nil
  526. })
  527. }
  528. func (am *AccountManager) loadModes(account string) (uModes modes.Modes) {
  529. key := fmt.Sprintf(keyAccountModes, account)
  530. var modeStr string
  531. am.server.store.View(func(tx *buntdb.Tx) error {
  532. modeStr, _ = tx.Get(key)
  533. return nil
  534. })
  535. for _, m := range modeStr {
  536. uModes = append(uModes, modes.Mode(m))
  537. }
  538. return
  539. }
  540. func (am *AccountManager) saveLastSeen(account string, lastSeen map[string]time.Time) {
  541. key := fmt.Sprintf(keyAccountLastSeen, account)
  542. var val string
  543. if len(lastSeen) != 0 {
  544. text, _ := json.Marshal(lastSeen)
  545. val = string(text)
  546. }
  547. am.server.store.Update(func(tx *buntdb.Tx) error {
  548. if val != "" {
  549. tx.Set(key, val, nil)
  550. } else {
  551. tx.Delete(key)
  552. }
  553. return nil
  554. })
  555. }
  556. func (am *AccountManager) loadLastSeen(account string) (lastSeen map[string]time.Time) {
  557. key := fmt.Sprintf(keyAccountLastSeen, account)
  558. var lsText string
  559. am.server.store.Update(func(tx *buntdb.Tx) error {
  560. lsText, _ = tx.Get(key)
  561. return nil
  562. })
  563. if lsText == "" {
  564. return nil
  565. }
  566. err := json.Unmarshal([]byte(lsText), &lastSeen)
  567. if err != nil {
  568. return nil
  569. }
  570. return
  571. }
  572. func (am *AccountManager) saveRealname(account string, realname string) {
  573. key := fmt.Sprintf(keyAccountRealname, account)
  574. am.server.store.Update(func(tx *buntdb.Tx) error {
  575. if realname != "" {
  576. tx.Set(key, realname, nil)
  577. } else {
  578. tx.Delete(key)
  579. }
  580. return nil
  581. })
  582. }
  583. func (am *AccountManager) loadRealname(account string) (realname string) {
  584. key := fmt.Sprintf(keyAccountRealname, account)
  585. am.server.store.Update(func(tx *buntdb.Tx) error {
  586. realname, _ = tx.Get(key)
  587. return nil
  588. })
  589. return
  590. }
  591. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  592. certfp, err = utils.NormalizeCertfp(certfp)
  593. if err != nil {
  594. return err
  595. }
  596. cfAccount, err := CasefoldName(account)
  597. if err != nil {
  598. return errAccountDoesNotExist
  599. }
  600. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  601. var credStr string
  602. am.server.store.View(func(tx *buntdb.Tx) error {
  603. credStr, err = tx.Get(credKey)
  604. return nil
  605. })
  606. if err != nil {
  607. return errAccountDoesNotExist
  608. }
  609. var creds AccountCredentials
  610. err = json.Unmarshal([]byte(credStr), &creds)
  611. if err != nil {
  612. return err
  613. }
  614. if !hasPrivs && creds.Empty() {
  615. return errCredsExternallyManaged
  616. }
  617. if add {
  618. err = creds.AddCertfp(certfp)
  619. } else {
  620. err = creds.RemoveCertfp(certfp)
  621. }
  622. if err != nil {
  623. return err
  624. }
  625. if creds.Empty() && !hasPrivs {
  626. return errEmptyCredentials
  627. }
  628. newCredStr, err := creds.Serialize()
  629. if err != nil {
  630. return err
  631. }
  632. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  633. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  634. curCredStr, err := tx.Get(credKey)
  635. if credStr != curCredStr {
  636. return errCASFailed
  637. }
  638. if add {
  639. _, err = tx.Get(certfpKey)
  640. if err != buntdb.ErrNotFound {
  641. return errCertfpAlreadyExists
  642. }
  643. tx.Set(certfpKey, cfAccount, nil)
  644. } else {
  645. tx.Delete(certfpKey)
  646. }
  647. _, _, err = tx.Set(credKey, newCredStr, nil)
  648. return err
  649. })
  650. return err
  651. }
  652. func (am *AccountManager) dispatchCallback(client *Client, account string, callbackNamespace string, callbackValue string) (string, error) {
  653. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  654. return "", nil
  655. } else if callbackNamespace == "mailto" {
  656. return am.dispatchMailtoCallback(client, account, callbackValue)
  657. } else {
  658. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  659. }
  660. }
  661. func (am *AccountManager) dispatchMailtoCallback(client *Client, account string, callbackValue string) (code string, err error) {
  662. config := am.server.Config().Accounts.Registration.Callbacks.Mailto
  663. code = utils.GenerateSecretToken()
  664. subject := config.VerifyMessageSubject
  665. if subject == "" {
  666. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  667. }
  668. var message bytes.Buffer
  669. fmt.Fprintf(&message, "From: %s\r\n", config.Sender)
  670. fmt.Fprintf(&message, "To: %s\r\n", callbackValue)
  671. if config.DKIM.Domain != "" {
  672. fmt.Fprintf(&message, "Message-ID: <%s@%s>\r\n", utils.GenerateSecretKey(), config.DKIM.Domain)
  673. }
  674. fmt.Fprintf(&message, "Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
  675. fmt.Fprintf(&message, "Subject: %s\r\n", subject)
  676. message.WriteString("\r\n") // blank line: end headers, begin message body
  677. fmt.Fprintf(&message, client.t("Account: %s"), account)
  678. message.WriteString("\r\n")
  679. fmt.Fprintf(&message, client.t("Verification code: %s"), code)
  680. message.WriteString("\r\n")
  681. message.WriteString("\r\n")
  682. message.WriteString(client.t("To verify your account, issue the following command:"))
  683. message.WriteString("\r\n")
  684. fmt.Fprintf(&message, "/MSG NickServ VERIFY %s %s\r\n", account, code)
  685. err = email.SendMail(config, callbackValue, message.Bytes())
  686. if err != nil {
  687. am.server.logger.Error("internal", "Failed to dispatch e-mail to", callbackValue, err.Error())
  688. }
  689. return
  690. }
  691. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  692. casefoldedAccount, err := CasefoldName(account)
  693. var skeleton string
  694. if err != nil || account == "" || account == "*" {
  695. return errAccountVerificationFailed
  696. }
  697. if client != nil && client.Account() != "" {
  698. return errAccountAlreadyLoggedIn
  699. }
  700. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  701. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  702. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  703. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  704. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  705. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  706. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  707. var raw rawClientAccount
  708. func() {
  709. am.serialCacheUpdateMutex.Lock()
  710. defer am.serialCacheUpdateMutex.Unlock()
  711. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  712. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  713. if err == errAccountDoesNotExist {
  714. return errAccountDoesNotExist
  715. } else if err != nil {
  716. return errAccountVerificationFailed
  717. } else if raw.Verified {
  718. return errAccountAlreadyVerified
  719. }
  720. // actually verify the code
  721. // a stored code of "" means a none callback / no code required
  722. success := false
  723. storedCode, err := tx.Get(verificationCodeKey)
  724. if err == nil {
  725. // this is probably unnecessary
  726. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  727. success = true
  728. }
  729. }
  730. if !success {
  731. return errAccountVerificationInvalidCode
  732. }
  733. // verify the account
  734. tx.Set(verifiedKey, "1", nil)
  735. // don't need the code anymore
  736. tx.Delete(verificationCodeKey)
  737. // re-set all other keys, removing the TTL
  738. tx.Set(accountKey, "1", nil)
  739. tx.Set(accountNameKey, raw.Name, nil)
  740. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  741. tx.Set(callbackKey, raw.Callback, nil)
  742. tx.Set(credentialsKey, raw.Credentials, nil)
  743. var creds AccountCredentials
  744. // XXX we shouldn't do (de)serialization inside the txn,
  745. // but this is like 2 usec on my system
  746. json.Unmarshal([]byte(raw.Credentials), &creds)
  747. for _, cert := range creds.Certfps {
  748. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  749. tx.Set(certFPKey, casefoldedAccount, nil)
  750. }
  751. return nil
  752. })
  753. if err == nil {
  754. skeleton, _ = Skeleton(raw.Name)
  755. am.Lock()
  756. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  757. am.skeletonToAccount[skeleton] = casefoldedAccount
  758. am.Unlock()
  759. }
  760. }()
  761. if err != nil {
  762. return err
  763. }
  764. nick := "[server admin]"
  765. if client != nil {
  766. nick = client.Nick()
  767. }
  768. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  769. raw.Verified = true
  770. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  771. if err != nil {
  772. return err
  773. }
  774. if client != nil {
  775. am.Login(client, clientAccount)
  776. }
  777. _, method := am.EnforcementStatus(casefoldedAccount, skeleton)
  778. if method != NickEnforcementNone {
  779. currentClient := am.server.clients.Get(casefoldedAccount)
  780. if currentClient == nil || currentClient == client || currentClient.Account() == casefoldedAccount {
  781. return nil
  782. }
  783. if method == NickEnforcementStrict {
  784. am.server.RandomlyRename(currentClient)
  785. }
  786. }
  787. if client.AlwaysOn() {
  788. client.markDirty(IncludeRealname)
  789. }
  790. return nil
  791. }
  792. // register and verify an account, for internal use
  793. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  794. err = am.Register(nil, account, "admin", "", passphrase, "")
  795. if err == nil {
  796. err = am.Verify(nil, account, "")
  797. }
  798. return
  799. }
  800. func marshalReservedNicks(nicks []string) string {
  801. return strings.Join(nicks, ",")
  802. }
  803. func unmarshalReservedNicks(nicks string) (result []string) {
  804. if nicks == "" {
  805. return
  806. }
  807. return strings.Split(nicks, ",")
  808. }
  809. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  810. cfnick, err := CasefoldName(nick)
  811. skeleton, skerr := Skeleton(nick)
  812. // garbage nick, or garbage options, or disabled
  813. nrconfig := am.server.Config().Accounts.NickReservation
  814. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  815. return errAccountNickReservationFailed
  816. }
  817. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  818. am.serialCacheUpdateMutex.Lock()
  819. defer am.serialCacheUpdateMutex.Unlock()
  820. // find the affected account, which is usually the client's:
  821. account := client.Account()
  822. if saUnreserve {
  823. // unless this is a sadrop:
  824. account = am.NickToAccount(cfnick)
  825. if account == "" {
  826. // nothing to do
  827. return nil
  828. }
  829. }
  830. if account == "" {
  831. return errAccountNotLoggedIn
  832. }
  833. am.Lock()
  834. accountForNick := am.nickToAccount[cfnick]
  835. var accountForSkeleton string
  836. if reserve {
  837. accountForSkeleton = am.skeletonToAccount[skeleton]
  838. }
  839. am.Unlock()
  840. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  841. return errNicknameReserved
  842. } else if !reserve && !saUnreserve && accountForNick != account {
  843. return errNicknameReserved
  844. } else if !reserve && cfnick == account {
  845. return errAccountCantDropPrimaryNick
  846. }
  847. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  848. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  849. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  850. if reserve {
  851. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  852. // however you shouldn't be able to reserve a nick out from under them
  853. _, err := tx.Get(unverifiedAccountKey)
  854. if err == nil {
  855. return errNicknameReserved
  856. }
  857. }
  858. rawNicks, err := tx.Get(nicksKey)
  859. if err != nil && err != buntdb.ErrNotFound {
  860. return err
  861. }
  862. nicks := unmarshalReservedNicks(rawNicks)
  863. if reserve {
  864. if len(nicks) >= nrconfig.AdditionalNickLimit {
  865. return errAccountTooManyNicks
  866. }
  867. nicks = append(nicks, nick)
  868. } else {
  869. // compute (original reserved nicks) minus cfnick
  870. var newNicks []string
  871. for _, reservedNick := range nicks {
  872. cfreservednick, _ := CasefoldName(reservedNick)
  873. if cfreservednick != cfnick {
  874. newNicks = append(newNicks, reservedNick)
  875. } else {
  876. // found the original, unfolded version of the nick we're dropping;
  877. // recompute the true skeleton from it
  878. skeleton, _ = Skeleton(reservedNick)
  879. }
  880. }
  881. nicks = newNicks
  882. }
  883. marshaledNicks := marshalReservedNicks(nicks)
  884. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  885. return err
  886. })
  887. if err == errAccountTooManyNicks || err == errNicknameReserved {
  888. return err
  889. } else if err != nil {
  890. return errAccountNickReservationFailed
  891. }
  892. // success
  893. am.Lock()
  894. defer am.Unlock()
  895. if reserve {
  896. am.nickToAccount[cfnick] = account
  897. am.skeletonToAccount[skeleton] = account
  898. } else {
  899. delete(am.nickToAccount, cfnick)
  900. delete(am.skeletonToAccount, skeleton)
  901. }
  902. return nil
  903. }
  904. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  905. account, err = am.LoadAccount(accountName)
  906. if err != nil {
  907. return
  908. }
  909. if !account.Verified {
  910. err = errAccountUnverified
  911. return
  912. }
  913. switch account.Credentials.Version {
  914. case 0:
  915. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  916. case 1:
  917. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  918. err = errAccountInvalidCredentials
  919. }
  920. default:
  921. err = errAccountInvalidCredentials
  922. }
  923. return
  924. }
  925. func (am *AccountManager) loadWithAutocreation(accountName string, autocreate bool) (account ClientAccount, err error) {
  926. account, err = am.LoadAccount(accountName)
  927. if err == errAccountDoesNotExist && autocreate {
  928. err = am.SARegister(accountName, "")
  929. if err != nil {
  930. return
  931. }
  932. account, err = am.LoadAccount(accountName)
  933. }
  934. return
  935. }
  936. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  937. // XXX check this now, so we don't allow a redundant login for an always-on client
  938. // even for a brief period. the other potential source of nick-account conflicts
  939. // is from force-nick-equals-account, but those will be caught later by
  940. // fixupNickEqualsAccount and if there is a conflict, they will be logged out.
  941. if client.registered {
  942. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  943. return errNickAccountMismatch
  944. }
  945. }
  946. if throttled, remainingTime := client.checkLoginThrottle(); throttled {
  947. return &ThrottleError{remainingTime}
  948. }
  949. var account ClientAccount
  950. defer func() {
  951. if err == nil {
  952. am.Login(client, account)
  953. }
  954. }()
  955. config := am.server.Config()
  956. if config.Accounts.AuthScript.Enabled {
  957. var output AuthScriptOutput
  958. output, err = CheckAuthScript(config.Accounts.AuthScript,
  959. AuthScriptInput{AccountName: accountName, Passphrase: passphrase, IP: client.IP().String()})
  960. if err != nil {
  961. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  962. } else if output.Success {
  963. if output.AccountName != "" {
  964. accountName = output.AccountName
  965. }
  966. account, err = am.loadWithAutocreation(accountName, config.Accounts.AuthScript.Autocreate)
  967. return
  968. }
  969. }
  970. account, err = am.checkPassphrase(accountName, passphrase)
  971. return err
  972. }
  973. // AllNicks returns the uncasefolded nicknames for all accounts, including additional (grouped) nicks.
  974. func (am *AccountManager) AllNicks() (result []string) {
  975. accountNamePrefix := fmt.Sprintf(keyAccountName, "")
  976. accountAdditionalNicksPrefix := fmt.Sprintf(keyAccountAdditionalNicks, "")
  977. am.server.store.View(func(tx *buntdb.Tx) error {
  978. // Account names
  979. err := tx.AscendGreaterOrEqual("", accountNamePrefix, func(key, value string) bool {
  980. if !strings.HasPrefix(key, accountNamePrefix) {
  981. return false
  982. }
  983. result = append(result, value)
  984. return true
  985. })
  986. if err != nil {
  987. return err
  988. }
  989. // Additional nicks
  990. return tx.AscendGreaterOrEqual("", accountAdditionalNicksPrefix, func(key, value string) bool {
  991. if !strings.HasPrefix(key, accountAdditionalNicksPrefix) {
  992. return false
  993. }
  994. additionalNicks := unmarshalReservedNicks(value)
  995. for _, additionalNick := range additionalNicks {
  996. result = append(result, additionalNick)
  997. }
  998. return true
  999. })
  1000. })
  1001. sort.Strings(result)
  1002. return
  1003. }
  1004. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  1005. casefoldedAccount, err := CasefoldName(accountName)
  1006. if err != nil {
  1007. err = errAccountDoesNotExist
  1008. return
  1009. }
  1010. var raw rawClientAccount
  1011. am.server.store.View(func(tx *buntdb.Tx) error {
  1012. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  1013. return nil
  1014. })
  1015. if err != nil {
  1016. return
  1017. }
  1018. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  1019. return
  1020. }
  1021. // look up the unfolded version of an account name, possibly after deletion
  1022. func (am *AccountManager) AccountToAccountName(account string) (result string) {
  1023. casefoldedAccount, err := CasefoldName(account)
  1024. if err != nil {
  1025. return
  1026. }
  1027. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1028. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1029. am.server.store.View(func(tx *buntdb.Tx) error {
  1030. if name, err := tx.Get(accountNameKey); err == nil {
  1031. result = name
  1032. return nil
  1033. }
  1034. if name, err := tx.Get(unregisteredKey); err == nil {
  1035. result = name
  1036. }
  1037. return nil
  1038. })
  1039. return
  1040. }
  1041. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  1042. result.Name = raw.Name
  1043. result.NameCasefolded = cfName
  1044. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  1045. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  1046. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  1047. if e != nil {
  1048. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  1049. err = errAccountDoesNotExist
  1050. return
  1051. }
  1052. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  1053. result.Verified = raw.Verified
  1054. if raw.VHost != "" {
  1055. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  1056. if e != nil {
  1057. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  1058. // pretend they have no vhost and move on
  1059. }
  1060. }
  1061. if raw.Settings != "" {
  1062. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  1063. if e != nil {
  1064. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  1065. }
  1066. }
  1067. return
  1068. }
  1069. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  1070. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1071. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1072. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1073. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1074. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1075. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1076. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1077. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1078. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1079. _, e := tx.Get(accountKey)
  1080. if e == buntdb.ErrNotFound {
  1081. err = errAccountDoesNotExist
  1082. return
  1083. }
  1084. result.Name, _ = tx.Get(accountNameKey)
  1085. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  1086. result.Credentials, _ = tx.Get(credentialsKey)
  1087. result.Callback, _ = tx.Get(callbackKey)
  1088. result.AdditionalNicks, _ = tx.Get(nicksKey)
  1089. result.VHost, _ = tx.Get(vhostKey)
  1090. result.Settings, _ = tx.Get(settingsKey)
  1091. if _, e = tx.Get(verifiedKey); e == nil {
  1092. result.Verified = true
  1093. }
  1094. return
  1095. }
  1096. func (am *AccountManager) Suspend(accountName string) (err error) {
  1097. account, err := CasefoldName(accountName)
  1098. if err != nil {
  1099. return errAccountDoesNotExist
  1100. }
  1101. existsKey := fmt.Sprintf(keyAccountExists, account)
  1102. verifiedKey := fmt.Sprintf(keyAccountVerified, account)
  1103. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1104. _, err := tx.Get(existsKey)
  1105. if err != nil {
  1106. return errAccountDoesNotExist
  1107. }
  1108. _, err = tx.Delete(verifiedKey)
  1109. return err
  1110. })
  1111. if err == errAccountDoesNotExist {
  1112. return err
  1113. } else if err != nil {
  1114. am.server.logger.Error("internal", "couldn't persist suspension", account, err.Error())
  1115. } // keep going
  1116. am.Lock()
  1117. clients := am.accountToClients[account]
  1118. delete(am.accountToClients, account)
  1119. am.Unlock()
  1120. am.killClients(clients)
  1121. return nil
  1122. }
  1123. func (am *AccountManager) killClients(clients []*Client) {
  1124. for _, client := range clients {
  1125. client.Logout()
  1126. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1127. client.destroy(nil)
  1128. }
  1129. }
  1130. func (am *AccountManager) Unsuspend(account string) (err error) {
  1131. cfaccount, err := CasefoldName(account)
  1132. if err != nil {
  1133. return errAccountDoesNotExist
  1134. }
  1135. existsKey := fmt.Sprintf(keyAccountExists, cfaccount)
  1136. verifiedKey := fmt.Sprintf(keyAccountVerified, cfaccount)
  1137. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1138. _, err := tx.Get(existsKey)
  1139. if err != nil {
  1140. return errAccountDoesNotExist
  1141. }
  1142. tx.Set(verifiedKey, "1", nil)
  1143. return nil
  1144. })
  1145. if err != nil {
  1146. return errAccountDoesNotExist
  1147. }
  1148. return nil
  1149. }
  1150. func (am *AccountManager) Unregister(account string, erase bool) error {
  1151. config := am.server.Config()
  1152. casefoldedAccount, err := CasefoldName(account)
  1153. if err != nil {
  1154. return errAccountDoesNotExist
  1155. }
  1156. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1157. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1158. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1159. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1160. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1161. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  1162. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1163. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1164. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1165. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1166. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  1167. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1168. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  1169. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1170. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1171. modesKey := fmt.Sprintf(keyAccountModes, casefoldedAccount)
  1172. var clients []*Client
  1173. defer func() {
  1174. am.killClients(clients)
  1175. }()
  1176. var registeredChannels []string
  1177. // on our way out, unregister all the account's channels and delete them from the db
  1178. defer func() {
  1179. for _, channelName := range registeredChannels {
  1180. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1181. if err != nil {
  1182. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1183. }
  1184. }
  1185. }()
  1186. var credText string
  1187. var rawNicks string
  1188. am.serialCacheUpdateMutex.Lock()
  1189. defer am.serialCacheUpdateMutex.Unlock()
  1190. var accountName string
  1191. var channelsStr string
  1192. keepProtections := false
  1193. am.server.store.Update(func(tx *buntdb.Tx) error {
  1194. // get the unfolded account name; for an active account, this is
  1195. // stored under accountNameKey, for an unregistered account under unregisteredKey
  1196. accountName, _ = tx.Get(accountNameKey)
  1197. if accountName == "" {
  1198. accountName, _ = tx.Get(unregisteredKey)
  1199. }
  1200. if erase {
  1201. tx.Delete(unregisteredKey)
  1202. } else {
  1203. if _, err := tx.Get(verifiedKey); err == nil {
  1204. tx.Set(unregisteredKey, accountName, nil)
  1205. keepProtections = true
  1206. }
  1207. }
  1208. tx.Delete(accountKey)
  1209. tx.Delete(accountNameKey)
  1210. tx.Delete(verifiedKey)
  1211. tx.Delete(registeredTimeKey)
  1212. tx.Delete(callbackKey)
  1213. tx.Delete(verificationCodeKey)
  1214. tx.Delete(settingsKey)
  1215. rawNicks, _ = tx.Get(nicksKey)
  1216. tx.Delete(nicksKey)
  1217. credText, err = tx.Get(credentialsKey)
  1218. tx.Delete(credentialsKey)
  1219. tx.Delete(vhostKey)
  1220. channelsStr, _ = tx.Get(channelsKey)
  1221. tx.Delete(channelsKey)
  1222. tx.Delete(joinedChannelsKey)
  1223. tx.Delete(lastSeenKey)
  1224. tx.Delete(modesKey)
  1225. _, err := tx.Delete(vhostQueueKey)
  1226. am.decrementVHostQueueCount(casefoldedAccount, err)
  1227. return nil
  1228. })
  1229. if err == nil {
  1230. var creds AccountCredentials
  1231. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1232. for _, cert := range creds.Certfps {
  1233. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1234. am.server.store.Update(func(tx *buntdb.Tx) error {
  1235. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1236. tx.Delete(certFPKey)
  1237. }
  1238. return nil
  1239. })
  1240. }
  1241. }
  1242. }
  1243. skeleton, _ := Skeleton(accountName)
  1244. additionalNicks := unmarshalReservedNicks(rawNicks)
  1245. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1246. am.Lock()
  1247. defer am.Unlock()
  1248. clients = am.accountToClients[casefoldedAccount]
  1249. delete(am.accountToClients, casefoldedAccount)
  1250. // protect the account name itself where applicable, but not any grouped nicks
  1251. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1252. delete(am.nickToAccount, casefoldedAccount)
  1253. delete(am.skeletonToAccount, skeleton)
  1254. }
  1255. for _, nick := range additionalNicks {
  1256. delete(am.nickToAccount, nick)
  1257. additionalSkel, _ := Skeleton(nick)
  1258. delete(am.skeletonToAccount, additionalSkel)
  1259. }
  1260. if err != nil && !erase {
  1261. return errAccountDoesNotExist
  1262. }
  1263. return nil
  1264. }
  1265. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1266. if channelsStr != "" {
  1267. result = strings.Split(channelsStr, ",")
  1268. }
  1269. return
  1270. }
  1271. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1272. cfaccount, err := CasefoldName(account)
  1273. if err != nil {
  1274. return
  1275. }
  1276. var channelStr string
  1277. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1278. am.server.store.View(func(tx *buntdb.Tx) error {
  1279. channelStr, _ = tx.Get(key)
  1280. return nil
  1281. })
  1282. return unmarshalRegisteredChannels(channelStr)
  1283. }
  1284. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) (err error) {
  1285. if certfp == "" {
  1286. return errAccountInvalidCredentials
  1287. }
  1288. var clientAccount ClientAccount
  1289. defer func() {
  1290. if err != nil {
  1291. return
  1292. } else if !clientAccount.Verified {
  1293. err = errAccountUnverified
  1294. return
  1295. }
  1296. // TODO(#1109) clean this check up?
  1297. if client.registered {
  1298. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1299. err = errNickAccountMismatch
  1300. return
  1301. }
  1302. }
  1303. am.Login(client, clientAccount)
  1304. return
  1305. }()
  1306. config := am.server.Config()
  1307. if config.Accounts.AuthScript.Enabled {
  1308. var output AuthScriptOutput
  1309. output, err = CheckAuthScript(config.Accounts.AuthScript,
  1310. AuthScriptInput{Certfp: certfp, IP: client.IP().String()})
  1311. if err != nil {
  1312. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  1313. } else if output.Success && output.AccountName != "" {
  1314. clientAccount, err = am.loadWithAutocreation(output.AccountName, config.Accounts.AuthScript.Autocreate)
  1315. return
  1316. }
  1317. }
  1318. var account string
  1319. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1320. err = am.server.store.View(func(tx *buntdb.Tx) error {
  1321. account, _ = tx.Get(certFPKey)
  1322. if account == "" {
  1323. return errAccountInvalidCredentials
  1324. }
  1325. return nil
  1326. })
  1327. if err != nil {
  1328. return err
  1329. }
  1330. if authzid != "" && authzid != account {
  1331. return errAuthzidAuthcidMismatch
  1332. }
  1333. // ok, we found an account corresponding to their certificate
  1334. clientAccount, err = am.LoadAccount(account)
  1335. return err
  1336. }
  1337. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1338. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1339. casefoldedAccount, err := CasefoldName(account)
  1340. if err != nil {
  1341. return newSettings, errAccountDoesNotExist
  1342. }
  1343. // TODO implement this in general via a compare-and-swap API
  1344. accountData, err := am.LoadAccount(casefoldedAccount)
  1345. if err != nil {
  1346. return
  1347. } else if !accountData.Verified {
  1348. return newSettings, errAccountUnverified
  1349. }
  1350. newSettings, err = munger(accountData.Settings)
  1351. if err != nil {
  1352. return
  1353. }
  1354. text, err := json.Marshal(newSettings)
  1355. if err != nil {
  1356. return
  1357. }
  1358. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1359. serializedValue := string(text)
  1360. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1361. _, _, err = tx.Set(key, serializedValue, nil)
  1362. return
  1363. })
  1364. if err != nil {
  1365. err = errAccountUpdateFailed
  1366. return
  1367. }
  1368. // success, push new settings into the client objects
  1369. am.Lock()
  1370. defer am.Unlock()
  1371. for _, client := range am.accountToClients[casefoldedAccount] {
  1372. client.SetAccountSettings(newSettings)
  1373. }
  1374. return
  1375. }
  1376. // represents someone's status in hostserv
  1377. type VHostInfo struct {
  1378. ApprovedVHost string
  1379. Enabled bool
  1380. Forbidden bool
  1381. RequestedVHost string
  1382. RejectedVHost string
  1383. RejectionReason string
  1384. LastRequestTime time.Time
  1385. }
  1386. // pair type, <VHostInfo, accountName>
  1387. type PendingVHostRequest struct {
  1388. VHostInfo
  1389. Account string
  1390. }
  1391. type vhostThrottleExceeded struct {
  1392. timeRemaining time.Duration
  1393. }
  1394. func (vhe *vhostThrottleExceeded) Error() string {
  1395. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1396. }
  1397. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1398. if cooldown == 0 {
  1399. return nil
  1400. }
  1401. now := time.Now().UTC()
  1402. elapsed := now.Sub(vh.LastRequestTime)
  1403. if elapsed > cooldown {
  1404. // success
  1405. vh.LastRequestTime = now
  1406. return nil
  1407. } else {
  1408. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1409. }
  1410. }
  1411. // callback type implementing the actual business logic of vhost operations
  1412. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1413. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1414. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1415. output = input
  1416. output.Enabled = true
  1417. output.ApprovedVHost = vhost
  1418. return
  1419. }
  1420. return am.performVHostChange(account, munger)
  1421. }
  1422. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1423. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1424. output = input
  1425. if input.Forbidden {
  1426. err = errVhostsForbidden
  1427. return
  1428. }
  1429. // you can update your existing request, but if you were approved or rejected,
  1430. // you can't spam a new request
  1431. if output.RequestedVHost == "" {
  1432. err = output.checkThrottle(cooldown)
  1433. }
  1434. if err != nil {
  1435. return
  1436. }
  1437. output.RequestedVHost = vhost
  1438. output.RejectedVHost = ""
  1439. output.RejectionReason = ""
  1440. output.LastRequestTime = time.Now().UTC()
  1441. return
  1442. }
  1443. return am.performVHostChange(account, munger)
  1444. }
  1445. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1446. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1447. output = input
  1448. if input.Forbidden {
  1449. err = errVhostsForbidden
  1450. return
  1451. }
  1452. // if you have a request pending, you can cancel it using take;
  1453. // otherwise, you're subject to the same throttling as if you were making a request
  1454. if output.RequestedVHost == "" {
  1455. err = output.checkThrottle(cooldown)
  1456. }
  1457. if err != nil {
  1458. return
  1459. }
  1460. output.ApprovedVHost = vhost
  1461. output.RequestedVHost = ""
  1462. output.RejectedVHost = ""
  1463. output.RejectionReason = ""
  1464. output.LastRequestTime = time.Now().UTC()
  1465. return
  1466. }
  1467. return am.performVHostChange(account, munger)
  1468. }
  1469. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1470. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1471. output = input
  1472. output.Enabled = true
  1473. output.ApprovedVHost = input.RequestedVHost
  1474. output.RequestedVHost = ""
  1475. output.RejectionReason = ""
  1476. return
  1477. }
  1478. return am.performVHostChange(account, munger)
  1479. }
  1480. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1481. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1482. output = input
  1483. output.RejectedVHost = output.RequestedVHost
  1484. output.RequestedVHost = ""
  1485. output.RejectionReason = reason
  1486. return
  1487. }
  1488. return am.performVHostChange(account, munger)
  1489. }
  1490. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1491. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1492. if input.ApprovedVHost == "" {
  1493. err = errNoVhost
  1494. return
  1495. }
  1496. output = input
  1497. output.Enabled = enabled
  1498. return
  1499. }
  1500. return am.performVHostChange(client.Account(), munger)
  1501. }
  1502. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1503. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1504. output = input
  1505. output.Forbidden = forbid
  1506. return
  1507. }
  1508. return am.performVHostChange(account, munger)
  1509. }
  1510. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1511. account, err = CasefoldName(account)
  1512. if err != nil || account == "" {
  1513. err = errAccountDoesNotExist
  1514. return
  1515. }
  1516. if am.server.Defcon() <= 3 {
  1517. err = errFeatureDisabled
  1518. return
  1519. }
  1520. am.vHostUpdateMutex.Lock()
  1521. defer am.vHostUpdateMutex.Unlock()
  1522. clientAccount, err := am.LoadAccount(account)
  1523. if err != nil {
  1524. err = errAccountDoesNotExist
  1525. return
  1526. } else if !clientAccount.Verified {
  1527. err = errAccountUnverified
  1528. return
  1529. }
  1530. result, err = munger(clientAccount.VHost)
  1531. if err != nil {
  1532. return
  1533. }
  1534. vhtext, err := json.Marshal(result)
  1535. if err != nil {
  1536. err = errAccountUpdateFailed
  1537. return
  1538. }
  1539. vhstr := string(vhtext)
  1540. key := fmt.Sprintf(keyAccountVHost, account)
  1541. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1542. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1543. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1544. return err
  1545. }
  1546. // update request queue
  1547. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1548. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1549. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1550. return err
  1551. }
  1552. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1553. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1554. _, err = tx.Delete(queueKey)
  1555. am.decrementVHostQueueCount(account, err)
  1556. }
  1557. return nil
  1558. })
  1559. if err != nil {
  1560. err = errAccountUpdateFailed
  1561. return
  1562. }
  1563. am.applyVhostToClients(account, result)
  1564. return result, nil
  1565. }
  1566. // XXX annoying helper method for keeping the queue count in sync with the DB
  1567. // `err` is the buntdb error returned from deleting the queue key
  1568. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1569. if err == nil {
  1570. // successfully deleted a queue entry, do a 2's complement decrement:
  1571. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1572. } else if err != buntdb.ErrNotFound {
  1573. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1574. }
  1575. }
  1576. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1577. am.vHostUpdateMutex.Lock()
  1578. defer am.vHostUpdateMutex.Unlock()
  1579. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1580. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1581. accounts := make([]string, 0, limit)
  1582. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1583. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1584. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1585. return len(accounts) < limit
  1586. })
  1587. })
  1588. if err != nil {
  1589. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1590. return
  1591. }
  1592. for _, account := range accounts {
  1593. accountInfo, err := am.LoadAccount(account)
  1594. if err == nil {
  1595. requests = append(requests, PendingVHostRequest{
  1596. Account: account,
  1597. VHostInfo: accountInfo.VHost,
  1598. })
  1599. } else {
  1600. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1601. }
  1602. }
  1603. return
  1604. }
  1605. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1606. // if hostserv is disabled in config, then don't grant vhosts
  1607. // that were previously approved while it was enabled
  1608. if !am.server.Config().Accounts.VHosts.Enabled {
  1609. return
  1610. }
  1611. vhost := ""
  1612. if info.Enabled && !info.Forbidden {
  1613. vhost = info.ApprovedVHost
  1614. }
  1615. oldNickmask := client.NickMaskString()
  1616. updated := client.SetVHost(vhost)
  1617. if updated && client.Registered() {
  1618. // TODO: doing I/O here is kind of a kludge
  1619. client.sendChghost(oldNickmask, client.Hostname())
  1620. }
  1621. }
  1622. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1623. am.RLock()
  1624. clients := am.accountToClients[account]
  1625. am.RUnlock()
  1626. for _, client := range clients {
  1627. am.applyVHostInfo(client, result)
  1628. }
  1629. }
  1630. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1631. client.Login(account)
  1632. am.applyVHostInfo(client, account.VHost)
  1633. casefoldedAccount := client.Account()
  1634. am.Lock()
  1635. defer am.Unlock()
  1636. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1637. }
  1638. func (am *AccountManager) Logout(client *Client) {
  1639. am.Lock()
  1640. defer am.Unlock()
  1641. casefoldedAccount := client.Account()
  1642. if casefoldedAccount == "" {
  1643. return
  1644. }
  1645. client.Logout()
  1646. clients := am.accountToClients[casefoldedAccount]
  1647. if len(clients) <= 1 {
  1648. delete(am.accountToClients, casefoldedAccount)
  1649. return
  1650. }
  1651. remainingClients := make([]*Client, len(clients)-1)
  1652. remainingPos := 0
  1653. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1654. if clients[currentPos] != client {
  1655. remainingClients[remainingPos] = clients[currentPos]
  1656. remainingPos++
  1657. }
  1658. }
  1659. am.accountToClients[casefoldedAccount] = remainingClients
  1660. }
  1661. var (
  1662. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1663. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1664. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1665. "PLAIN": authPlainHandler,
  1666. "EXTERNAL": authExternalHandler,
  1667. }
  1668. )
  1669. // AccountCredentials stores the various methods for verifying accounts.
  1670. type AccountCredentials struct {
  1671. Version uint
  1672. PassphraseSalt []byte // legacy field, not used by v1 and later
  1673. PassphraseHash []byte
  1674. Certfps []string
  1675. }
  1676. func (ac *AccountCredentials) Empty() bool {
  1677. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1678. }
  1679. // helper to assemble the serialized JSON for an account's credentials
  1680. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1681. ac.Version = 1
  1682. credText, err := json.Marshal(*ac)
  1683. if err != nil {
  1684. return "", err
  1685. }
  1686. return string(credText), nil
  1687. }
  1688. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1689. if passphrase == "" {
  1690. ac.PassphraseHash = nil
  1691. return nil
  1692. }
  1693. if validatePassphrase(passphrase) != nil {
  1694. return errAccountBadPassphrase
  1695. }
  1696. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1697. if err != nil {
  1698. return errAccountBadPassphrase
  1699. }
  1700. return nil
  1701. }
  1702. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1703. // XXX we require that certfp is already normalized (rather than normalize here
  1704. // and pass back the normalized version as an additional return parameter);
  1705. // this is just a final sanity check:
  1706. if len(certfp) != 64 {
  1707. return utils.ErrInvalidCertfp
  1708. }
  1709. for _, current := range ac.Certfps {
  1710. if certfp == current {
  1711. return errNoop
  1712. }
  1713. }
  1714. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1715. return errLimitExceeded
  1716. }
  1717. ac.Certfps = append(ac.Certfps, certfp)
  1718. return nil
  1719. }
  1720. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1721. found := false
  1722. newList := make([]string, 0, len(ac.Certfps))
  1723. for _, current := range ac.Certfps {
  1724. if current == certfp {
  1725. found = true
  1726. } else {
  1727. newList = append(newList, current)
  1728. }
  1729. }
  1730. if !found {
  1731. // this is important because it prevents you from deleting someone else's
  1732. // fingerprint record
  1733. return errNoop
  1734. }
  1735. ac.Certfps = newList
  1736. return nil
  1737. }
  1738. type MulticlientAllowedSetting int
  1739. const (
  1740. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1741. MulticlientDisallowedByUser
  1742. MulticlientAllowedByUser
  1743. )
  1744. // controls whether/when clients without event-playback support see fake
  1745. // PRIVMSGs for JOINs
  1746. type ReplayJoinsSetting uint
  1747. const (
  1748. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1749. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1750. ReplayJoinsNever // never replay
  1751. )
  1752. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1753. switch strings.ToLower(str) {
  1754. case "commands-only":
  1755. result = ReplayJoinsCommandsOnly
  1756. case "always":
  1757. result = ReplayJoinsAlways
  1758. case "never":
  1759. result = ReplayJoinsNever
  1760. default:
  1761. err = errInvalidParams
  1762. }
  1763. return
  1764. }
  1765. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1766. // persistent JSON blobs in the database
  1767. type AccountSettings struct {
  1768. AutoreplayLines *int
  1769. NickEnforcement NickEnforcementMethod
  1770. AllowBouncer MulticlientAllowedSetting
  1771. ReplayJoins ReplayJoinsSetting
  1772. AlwaysOn PersistentStatus
  1773. AutoreplayMissed bool
  1774. DMHistory HistoryStatus
  1775. AutoAway PersistentStatus
  1776. }
  1777. // ClientAccount represents a user account.
  1778. type ClientAccount struct {
  1779. // Name of the account.
  1780. Name string
  1781. NameCasefolded string
  1782. RegisteredAt time.Time
  1783. Credentials AccountCredentials
  1784. Verified bool
  1785. AdditionalNicks []string
  1786. VHost VHostInfo
  1787. Settings AccountSettings
  1788. }
  1789. // convenience for passing around raw serialized account data
  1790. type rawClientAccount struct {
  1791. Name string
  1792. RegisteredAt string
  1793. Credentials string
  1794. Callback string
  1795. Verified bool
  1796. AdditionalNicks string
  1797. VHost string
  1798. Settings string
  1799. }