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 50KB

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