選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

accounts.go 56KB

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