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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. keyAccountLastSeen = "account.lastseen %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.loadLastSeen(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) saveLastSeen(account string, lastSeen time.Time) {
  462. key := fmt.Sprintf(keyAccountLastSeen, account)
  463. var val string
  464. if !lastSeen.IsZero() {
  465. val = strconv.FormatInt(lastSeen.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) loadLastSeen(account string) (lastSeen time.Time) {
  477. key := fmt.Sprintf(keyAccountLastSeen, account)
  478. var lsText string
  479. am.server.store.Update(func(tx *buntdb.Tx) error {
  480. lsText, _ = tx.Get(key)
  481. // XXX clear this on startup, because it's not clear when it's
  482. // going to be overwritten, and restarting the server twice in a row
  483. // could result in a large amount of duplicated history replay
  484. tx.Delete(key)
  485. return nil
  486. })
  487. lsNum, err := strconv.ParseInt(lsText, 10, 64)
  488. if err == nil {
  489. return time.Unix(0, lsNum).UTC()
  490. }
  491. return
  492. }
  493. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  494. certfp, err = utils.NormalizeCertfp(certfp)
  495. if err != nil {
  496. return err
  497. }
  498. cfAccount, err := CasefoldName(account)
  499. if err != nil {
  500. return errAccountDoesNotExist
  501. }
  502. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  503. var credStr string
  504. am.server.store.View(func(tx *buntdb.Tx) error {
  505. credStr, err = tx.Get(credKey)
  506. return nil
  507. })
  508. if err != nil {
  509. return errAccountDoesNotExist
  510. }
  511. var creds AccountCredentials
  512. err = json.Unmarshal([]byte(credStr), &creds)
  513. if err != nil {
  514. return err
  515. }
  516. if !hasPrivs && creds.Empty() {
  517. return errCredsExternallyManaged
  518. }
  519. if add {
  520. err = creds.AddCertfp(certfp)
  521. } else {
  522. err = creds.RemoveCertfp(certfp)
  523. }
  524. if err != nil {
  525. return err
  526. }
  527. if creds.Empty() && !hasPrivs {
  528. return errEmptyCredentials
  529. }
  530. newCredStr, err := creds.Serialize()
  531. if err != nil {
  532. return err
  533. }
  534. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  535. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  536. curCredStr, err := tx.Get(credKey)
  537. if credStr != curCredStr {
  538. return errCASFailed
  539. }
  540. if add {
  541. _, err = tx.Get(certfpKey)
  542. if err != buntdb.ErrNotFound {
  543. return errCertfpAlreadyExists
  544. }
  545. tx.Set(certfpKey, cfAccount, nil)
  546. } else {
  547. tx.Delete(certfpKey)
  548. }
  549. _, _, err = tx.Set(credKey, newCredStr, nil)
  550. return err
  551. })
  552. return err
  553. }
  554. func (am *AccountManager) dispatchCallback(client *Client, casefoldedAccount string, callbackNamespace string, callbackValue string) (string, error) {
  555. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  556. return "", nil
  557. } else if callbackNamespace == "mailto" {
  558. return am.dispatchMailtoCallback(client, casefoldedAccount, callbackValue)
  559. } else {
  560. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  561. }
  562. }
  563. func (am *AccountManager) dispatchMailtoCallback(client *Client, casefoldedAccount string, callbackValue string) (code string, err error) {
  564. config := am.server.AccountConfig().Registration.Callbacks.Mailto
  565. code = utils.GenerateSecretToken()
  566. subject := config.VerifyMessageSubject
  567. if subject == "" {
  568. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  569. }
  570. messageStrings := []string{
  571. fmt.Sprintf("From: %s\r\n", config.Sender),
  572. fmt.Sprintf("To: %s\r\n", callbackValue),
  573. fmt.Sprintf("Subject: %s\r\n", subject),
  574. "\r\n", // end headers, begin message body
  575. fmt.Sprintf(client.t("Account: %s"), casefoldedAccount) + "\r\n",
  576. fmt.Sprintf(client.t("Verification code: %s"), code) + "\r\n",
  577. "\r\n",
  578. client.t("To verify your account, issue the following command:") + "\r\n",
  579. fmt.Sprintf("/MSG NickServ VERIFY %s %s", casefoldedAccount, code) + "\r\n",
  580. }
  581. var message []byte
  582. for i := 0; i < len(messageStrings); i++ {
  583. message = append(message, []byte(messageStrings[i])...)
  584. }
  585. addr := fmt.Sprintf("%s:%d", config.Server, config.Port)
  586. var auth smtp.Auth
  587. if config.Username != "" && config.Password != "" {
  588. auth = smtp.PlainAuth("", config.Username, config.Password, config.Server)
  589. }
  590. // TODO: this will never send the password in plaintext over a nonlocal link,
  591. // but it might send the email in plaintext, regardless of the value of
  592. // config.TLS.InsecureSkipVerify
  593. err = smtp.SendMail(addr, auth, config.Sender, []string{callbackValue}, message)
  594. if err != nil {
  595. am.server.logger.Error("internal", "Failed to dispatch e-mail", err.Error())
  596. }
  597. return
  598. }
  599. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  600. casefoldedAccount, err := CasefoldName(account)
  601. if err != nil || account == "" || account == "*" {
  602. return errAccountVerificationFailed
  603. }
  604. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  605. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  606. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  607. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  608. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  609. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  610. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  611. var raw rawClientAccount
  612. func() {
  613. am.serialCacheUpdateMutex.Lock()
  614. defer am.serialCacheUpdateMutex.Unlock()
  615. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  616. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  617. if err == errAccountDoesNotExist {
  618. return errAccountDoesNotExist
  619. } else if err != nil {
  620. return errAccountVerificationFailed
  621. } else if raw.Verified {
  622. return errAccountAlreadyVerified
  623. }
  624. // actually verify the code
  625. // a stored code of "" means a none callback / no code required
  626. success := false
  627. storedCode, err := tx.Get(verificationCodeKey)
  628. if err == nil {
  629. // this is probably unnecessary
  630. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  631. success = true
  632. }
  633. }
  634. if !success {
  635. return errAccountVerificationInvalidCode
  636. }
  637. // verify the account
  638. tx.Set(verifiedKey, "1", nil)
  639. // don't need the code anymore
  640. tx.Delete(verificationCodeKey)
  641. // re-set all other keys, removing the TTL
  642. tx.Set(accountKey, "1", nil)
  643. tx.Set(accountNameKey, raw.Name, nil)
  644. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  645. tx.Set(callbackKey, raw.Callback, nil)
  646. tx.Set(credentialsKey, raw.Credentials, nil)
  647. var creds AccountCredentials
  648. // XXX we shouldn't do (de)serialization inside the txn,
  649. // but this is like 2 usec on my system
  650. json.Unmarshal([]byte(raw.Credentials), &creds)
  651. for _, cert := range creds.Certfps {
  652. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  653. tx.Set(certFPKey, casefoldedAccount, nil)
  654. }
  655. return nil
  656. })
  657. if err == nil {
  658. skeleton, _ := Skeleton(raw.Name)
  659. am.Lock()
  660. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  661. am.skeletonToAccount[skeleton] = casefoldedAccount
  662. am.Unlock()
  663. }
  664. }()
  665. if err != nil {
  666. return err
  667. }
  668. nick := "[server admin]"
  669. if client != nil {
  670. nick = client.Nick()
  671. }
  672. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  673. raw.Verified = true
  674. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  675. if err != nil {
  676. return err
  677. }
  678. if client != nil {
  679. am.Login(client, clientAccount)
  680. }
  681. return nil
  682. }
  683. // register and verify an account, for internal use
  684. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  685. err = am.Register(nil, account, "admin", "", passphrase, "")
  686. if err == nil {
  687. err = am.Verify(nil, account, "")
  688. }
  689. return
  690. }
  691. func marshalReservedNicks(nicks []string) string {
  692. return strings.Join(nicks, ",")
  693. }
  694. func unmarshalReservedNicks(nicks string) (result []string) {
  695. if nicks == "" {
  696. return
  697. }
  698. return strings.Split(nicks, ",")
  699. }
  700. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  701. cfnick, err := CasefoldName(nick)
  702. skeleton, skerr := Skeleton(nick)
  703. // garbage nick, or garbage options, or disabled
  704. nrconfig := am.server.AccountConfig().NickReservation
  705. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  706. return errAccountNickReservationFailed
  707. }
  708. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  709. am.serialCacheUpdateMutex.Lock()
  710. defer am.serialCacheUpdateMutex.Unlock()
  711. // find the affected account, which is usually the client's:
  712. account := client.Account()
  713. if saUnreserve {
  714. // unless this is a sadrop:
  715. account = am.NickToAccount(cfnick)
  716. if account == "" {
  717. // nothing to do
  718. return nil
  719. }
  720. }
  721. if account == "" {
  722. return errAccountNotLoggedIn
  723. }
  724. am.Lock()
  725. accountForNick := am.nickToAccount[cfnick]
  726. var accountForSkeleton string
  727. if reserve {
  728. accountForSkeleton = am.skeletonToAccount[skeleton]
  729. }
  730. am.Unlock()
  731. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  732. return errNicknameReserved
  733. } else if !reserve && !saUnreserve && accountForNick != account {
  734. return errNicknameReserved
  735. } else if !reserve && cfnick == account {
  736. return errAccountCantDropPrimaryNick
  737. }
  738. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  739. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  740. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  741. if reserve {
  742. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  743. // however you shouldn't be able to reserve a nick out from under them
  744. _, err := tx.Get(unverifiedAccountKey)
  745. if err == nil {
  746. return errNicknameReserved
  747. }
  748. }
  749. rawNicks, err := tx.Get(nicksKey)
  750. if err != nil && err != buntdb.ErrNotFound {
  751. return err
  752. }
  753. nicks := unmarshalReservedNicks(rawNicks)
  754. if reserve {
  755. if len(nicks) >= nrconfig.AdditionalNickLimit {
  756. return errAccountTooManyNicks
  757. }
  758. nicks = append(nicks, nick)
  759. } else {
  760. // compute (original reserved nicks) minus cfnick
  761. var newNicks []string
  762. for _, reservedNick := range nicks {
  763. cfreservednick, _ := CasefoldName(reservedNick)
  764. if cfreservednick != cfnick {
  765. newNicks = append(newNicks, reservedNick)
  766. } else {
  767. // found the original, unfolded version of the nick we're dropping;
  768. // recompute the true skeleton from it
  769. skeleton, _ = Skeleton(reservedNick)
  770. }
  771. }
  772. nicks = newNicks
  773. }
  774. marshaledNicks := marshalReservedNicks(nicks)
  775. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  776. return err
  777. })
  778. if err == errAccountTooManyNicks || err == errNicknameReserved {
  779. return err
  780. } else if err != nil {
  781. return errAccountNickReservationFailed
  782. }
  783. // success
  784. am.Lock()
  785. defer am.Unlock()
  786. if reserve {
  787. am.nickToAccount[cfnick] = account
  788. am.skeletonToAccount[skeleton] = account
  789. } else {
  790. delete(am.nickToAccount, cfnick)
  791. delete(am.skeletonToAccount, skeleton)
  792. }
  793. return nil
  794. }
  795. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  796. account, err = am.LoadAccount(accountName)
  797. if err != nil {
  798. return
  799. }
  800. if !account.Verified {
  801. err = errAccountUnverified
  802. return
  803. }
  804. switch account.Credentials.Version {
  805. case 0:
  806. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  807. case 1:
  808. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  809. err = errAccountInvalidCredentials
  810. }
  811. default:
  812. err = errAccountInvalidCredentials
  813. }
  814. return
  815. }
  816. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  817. if client.registered {
  818. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  819. return errNickAccountMismatch
  820. }
  821. }
  822. var account ClientAccount
  823. defer func() {
  824. if err == nil {
  825. am.Login(client, account)
  826. }
  827. }()
  828. ldapConf := am.server.Config().Accounts.LDAP
  829. if ldapConf.Enabled {
  830. err = ldap.CheckLDAPPassphrase(ldapConf, accountName, passphrase, am.server.logger)
  831. if err == nil {
  832. account, err = am.LoadAccount(accountName)
  833. // autocreate if necessary:
  834. if err == errAccountDoesNotExist && ldapConf.Autocreate {
  835. err = am.SARegister(accountName, "")
  836. if err != nil {
  837. return
  838. }
  839. account, err = am.LoadAccount(accountName)
  840. }
  841. return
  842. }
  843. }
  844. account, err = am.checkPassphrase(accountName, passphrase)
  845. return err
  846. }
  847. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  848. casefoldedAccount, err := CasefoldName(accountName)
  849. if err != nil {
  850. err = errAccountDoesNotExist
  851. return
  852. }
  853. var raw rawClientAccount
  854. am.server.store.View(func(tx *buntdb.Tx) error {
  855. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  856. return nil
  857. })
  858. if err != nil {
  859. return
  860. }
  861. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  862. return
  863. }
  864. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  865. result.Name = raw.Name
  866. result.NameCasefolded = cfName
  867. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  868. result.RegisteredAt = time.Unix(regTimeInt, 0).UTC()
  869. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  870. if e != nil {
  871. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  872. err = errAccountDoesNotExist
  873. return
  874. }
  875. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  876. result.Verified = raw.Verified
  877. if raw.VHost != "" {
  878. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  879. if e != nil {
  880. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  881. // pretend they have no vhost and move on
  882. }
  883. }
  884. if raw.Settings != "" {
  885. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  886. if e != nil {
  887. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  888. }
  889. }
  890. return
  891. }
  892. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  893. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  894. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  895. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  896. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  897. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  898. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  899. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  900. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  901. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  902. _, e := tx.Get(accountKey)
  903. if e == buntdb.ErrNotFound {
  904. err = errAccountDoesNotExist
  905. return
  906. }
  907. result.Name, _ = tx.Get(accountNameKey)
  908. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  909. result.Credentials, _ = tx.Get(credentialsKey)
  910. result.Callback, _ = tx.Get(callbackKey)
  911. result.AdditionalNicks, _ = tx.Get(nicksKey)
  912. result.VHost, _ = tx.Get(vhostKey)
  913. result.Settings, _ = tx.Get(settingsKey)
  914. if _, e = tx.Get(verifiedKey); e == nil {
  915. result.Verified = true
  916. }
  917. return
  918. }
  919. func (am *AccountManager) Unregister(account string) error {
  920. config := am.server.Config()
  921. casefoldedAccount, err := CasefoldName(account)
  922. if err != nil {
  923. return errAccountDoesNotExist
  924. }
  925. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  926. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  927. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  928. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  929. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  930. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  931. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  932. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  933. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  934. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  935. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  936. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  937. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  938. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  939. var clients []*Client
  940. var registeredChannels []string
  941. // on our way out, unregister all the account's channels and delete them from the db
  942. defer func() {
  943. for _, channelName := range registeredChannels {
  944. am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  945. }
  946. }()
  947. var credText string
  948. var rawNicks string
  949. am.serialCacheUpdateMutex.Lock()
  950. defer am.serialCacheUpdateMutex.Unlock()
  951. var accountName string
  952. var channelsStr string
  953. am.server.store.Update(func(tx *buntdb.Tx) error {
  954. tx.Delete(accountKey)
  955. accountName, _ = tx.Get(accountNameKey)
  956. tx.Delete(accountNameKey)
  957. tx.Delete(verifiedKey)
  958. tx.Delete(registeredTimeKey)
  959. tx.Delete(callbackKey)
  960. tx.Delete(verificationCodeKey)
  961. tx.Delete(settingsKey)
  962. rawNicks, _ = tx.Get(nicksKey)
  963. tx.Delete(nicksKey)
  964. credText, err = tx.Get(credentialsKey)
  965. tx.Delete(credentialsKey)
  966. tx.Delete(vhostKey)
  967. channelsStr, _ = tx.Get(channelsKey)
  968. tx.Delete(channelsKey)
  969. tx.Delete(joinedChannelsKey)
  970. tx.Delete(lastSeenKey)
  971. _, err := tx.Delete(vhostQueueKey)
  972. am.decrementVHostQueueCount(casefoldedAccount, err)
  973. return nil
  974. })
  975. if err == nil {
  976. var creds AccountCredentials
  977. if err = json.Unmarshal([]byte(credText), &creds); err == nil {
  978. for _, cert := range creds.Certfps {
  979. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  980. am.server.store.Update(func(tx *buntdb.Tx) error {
  981. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  982. tx.Delete(certFPKey)
  983. }
  984. return nil
  985. })
  986. }
  987. }
  988. }
  989. skeleton, _ := Skeleton(accountName)
  990. additionalNicks := unmarshalReservedNicks(rawNicks)
  991. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  992. am.Lock()
  993. defer am.Unlock()
  994. clients = am.accountToClients[casefoldedAccount]
  995. delete(am.accountToClients, casefoldedAccount)
  996. delete(am.nickToAccount, casefoldedAccount)
  997. delete(am.skeletonToAccount, skeleton)
  998. for _, nick := range additionalNicks {
  999. delete(am.nickToAccount, nick)
  1000. additionalSkel, _ := Skeleton(nick)
  1001. delete(am.skeletonToAccount, additionalSkel)
  1002. }
  1003. for _, client := range clients {
  1004. if config.Accounts.RequireSasl.Enabled {
  1005. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1006. // destroy acquires a semaphore so we can't call it while holding a lock
  1007. go client.destroy(nil)
  1008. } else {
  1009. am.logoutOfAccount(client)
  1010. }
  1011. }
  1012. if err != nil {
  1013. return errAccountDoesNotExist
  1014. }
  1015. return nil
  1016. }
  1017. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1018. if channelsStr != "" {
  1019. result = strings.Split(channelsStr, ",")
  1020. }
  1021. return
  1022. }
  1023. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1024. cfaccount, err := CasefoldName(account)
  1025. if err != nil {
  1026. return
  1027. }
  1028. var channelStr string
  1029. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1030. am.server.store.View(func(tx *buntdb.Tx) error {
  1031. channelStr, _ = tx.Get(key)
  1032. return nil
  1033. })
  1034. return unmarshalRegisteredChannels(channelStr)
  1035. }
  1036. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1037. if certfp == "" {
  1038. return errAccountInvalidCredentials
  1039. }
  1040. var account string
  1041. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1042. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1043. account, _ = tx.Get(certFPKey)
  1044. if account == "" {
  1045. return errAccountInvalidCredentials
  1046. }
  1047. return nil
  1048. })
  1049. if err != nil {
  1050. return err
  1051. }
  1052. if authzid != "" && authzid != account {
  1053. return errAuthzidAuthcidMismatch
  1054. }
  1055. // ok, we found an account corresponding to their certificate
  1056. clientAccount, err := am.LoadAccount(account)
  1057. if err != nil {
  1058. return err
  1059. } else if !clientAccount.Verified {
  1060. return errAccountUnverified
  1061. }
  1062. if client.registered {
  1063. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1064. return errNickAccountMismatch
  1065. }
  1066. }
  1067. am.Login(client, clientAccount)
  1068. return nil
  1069. }
  1070. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1071. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1072. casefoldedAccount, err := CasefoldName(account)
  1073. if err != nil {
  1074. return newSettings, errAccountDoesNotExist
  1075. }
  1076. // TODO implement this in general via a compare-and-swap API
  1077. accountData, err := am.LoadAccount(casefoldedAccount)
  1078. if err != nil {
  1079. return
  1080. } else if !accountData.Verified {
  1081. return newSettings, errAccountUnverified
  1082. }
  1083. newSettings, err = munger(accountData.Settings)
  1084. if err != nil {
  1085. return
  1086. }
  1087. text, err := json.Marshal(newSettings)
  1088. if err != nil {
  1089. return
  1090. }
  1091. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1092. serializedValue := string(text)
  1093. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1094. _, _, err = tx.Set(key, serializedValue, nil)
  1095. return
  1096. })
  1097. if err != nil {
  1098. err = errAccountUpdateFailed
  1099. return
  1100. }
  1101. // success, push new settings into the client objects
  1102. am.Lock()
  1103. defer am.Unlock()
  1104. for _, client := range am.accountToClients[casefoldedAccount] {
  1105. client.SetAccountSettings(newSettings)
  1106. }
  1107. return
  1108. }
  1109. // represents someone's status in hostserv
  1110. type VHostInfo struct {
  1111. ApprovedVHost string
  1112. Enabled bool
  1113. Forbidden bool
  1114. RequestedVHost string
  1115. RejectedVHost string
  1116. RejectionReason string
  1117. LastRequestTime time.Time
  1118. }
  1119. // pair type, <VHostInfo, accountName>
  1120. type PendingVHostRequest struct {
  1121. VHostInfo
  1122. Account string
  1123. }
  1124. type vhostThrottleExceeded struct {
  1125. timeRemaining time.Duration
  1126. }
  1127. func (vhe *vhostThrottleExceeded) Error() string {
  1128. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1129. }
  1130. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1131. if cooldown == 0 {
  1132. return nil
  1133. }
  1134. now := time.Now().UTC()
  1135. elapsed := now.Sub(vh.LastRequestTime)
  1136. if elapsed > cooldown {
  1137. // success
  1138. vh.LastRequestTime = now
  1139. return nil
  1140. } else {
  1141. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1142. }
  1143. }
  1144. // callback type implementing the actual business logic of vhost operations
  1145. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1146. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1147. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1148. output = input
  1149. output.Enabled = true
  1150. output.ApprovedVHost = vhost
  1151. return
  1152. }
  1153. return am.performVHostChange(account, munger)
  1154. }
  1155. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1156. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1157. output = input
  1158. if input.Forbidden {
  1159. err = errVhostsForbidden
  1160. return
  1161. }
  1162. // you can update your existing request, but if you were approved or rejected,
  1163. // you can't spam a new request
  1164. if output.RequestedVHost == "" {
  1165. err = output.checkThrottle(cooldown)
  1166. }
  1167. if err != nil {
  1168. return
  1169. }
  1170. output.RequestedVHost = vhost
  1171. output.RejectedVHost = ""
  1172. output.RejectionReason = ""
  1173. output.LastRequestTime = time.Now().UTC()
  1174. return
  1175. }
  1176. return am.performVHostChange(account, munger)
  1177. }
  1178. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1179. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1180. output = input
  1181. if input.Forbidden {
  1182. err = errVhostsForbidden
  1183. return
  1184. }
  1185. // if you have a request pending, you can cancel it using take;
  1186. // otherwise, you're subject to the same throttling as if you were making a request
  1187. if output.RequestedVHost == "" {
  1188. err = output.checkThrottle(cooldown)
  1189. }
  1190. if err != nil {
  1191. return
  1192. }
  1193. output.ApprovedVHost = vhost
  1194. output.RequestedVHost = ""
  1195. output.RejectedVHost = ""
  1196. output.RejectionReason = ""
  1197. output.LastRequestTime = time.Now().UTC()
  1198. return
  1199. }
  1200. return am.performVHostChange(account, munger)
  1201. }
  1202. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1203. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1204. output = input
  1205. output.Enabled = true
  1206. output.ApprovedVHost = input.RequestedVHost
  1207. output.RequestedVHost = ""
  1208. output.RejectionReason = ""
  1209. return
  1210. }
  1211. return am.performVHostChange(account, munger)
  1212. }
  1213. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1214. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1215. output = input
  1216. output.RejectedVHost = output.RequestedVHost
  1217. output.RequestedVHost = ""
  1218. output.RejectionReason = reason
  1219. return
  1220. }
  1221. return am.performVHostChange(account, munger)
  1222. }
  1223. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1224. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1225. if input.ApprovedVHost == "" {
  1226. err = errNoVhost
  1227. return
  1228. }
  1229. output = input
  1230. output.Enabled = enabled
  1231. return
  1232. }
  1233. return am.performVHostChange(client.Account(), munger)
  1234. }
  1235. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1236. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1237. output = input
  1238. output.Forbidden = forbid
  1239. return
  1240. }
  1241. return am.performVHostChange(account, munger)
  1242. }
  1243. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1244. account, err = CasefoldName(account)
  1245. if err != nil || account == "" {
  1246. err = errAccountDoesNotExist
  1247. return
  1248. }
  1249. am.vHostUpdateMutex.Lock()
  1250. defer am.vHostUpdateMutex.Unlock()
  1251. clientAccount, err := am.LoadAccount(account)
  1252. if err != nil {
  1253. err = errAccountDoesNotExist
  1254. return
  1255. } else if !clientAccount.Verified {
  1256. err = errAccountUnverified
  1257. return
  1258. }
  1259. result, err = munger(clientAccount.VHost)
  1260. if err != nil {
  1261. return
  1262. }
  1263. vhtext, err := json.Marshal(result)
  1264. if err != nil {
  1265. err = errAccountUpdateFailed
  1266. return
  1267. }
  1268. vhstr := string(vhtext)
  1269. key := fmt.Sprintf(keyAccountVHost, account)
  1270. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1271. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1272. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1273. return err
  1274. }
  1275. // update request queue
  1276. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1277. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1278. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1279. return err
  1280. }
  1281. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1282. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1283. _, err = tx.Delete(queueKey)
  1284. am.decrementVHostQueueCount(account, err)
  1285. }
  1286. return nil
  1287. })
  1288. if err != nil {
  1289. err = errAccountUpdateFailed
  1290. return
  1291. }
  1292. am.applyVhostToClients(account, result)
  1293. return result, nil
  1294. }
  1295. // XXX annoying helper method for keeping the queue count in sync with the DB
  1296. // `err` is the buntdb error returned from deleting the queue key
  1297. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1298. if err == nil {
  1299. // successfully deleted a queue entry, do a 2's complement decrement:
  1300. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1301. } else if err != buntdb.ErrNotFound {
  1302. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1303. }
  1304. }
  1305. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1306. am.vHostUpdateMutex.Lock()
  1307. defer am.vHostUpdateMutex.Unlock()
  1308. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1309. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1310. accounts := make([]string, 0, limit)
  1311. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1312. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1313. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1314. return len(accounts) < limit
  1315. })
  1316. })
  1317. if err != nil {
  1318. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1319. return
  1320. }
  1321. for _, account := range accounts {
  1322. accountInfo, err := am.LoadAccount(account)
  1323. if err == nil {
  1324. requests = append(requests, PendingVHostRequest{
  1325. Account: account,
  1326. VHostInfo: accountInfo.VHost,
  1327. })
  1328. } else {
  1329. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1330. }
  1331. }
  1332. return
  1333. }
  1334. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1335. // if hostserv is disabled in config, then don't grant vhosts
  1336. // that were previously approved while it was enabled
  1337. if !am.server.AccountConfig().VHosts.Enabled {
  1338. return
  1339. }
  1340. vhost := ""
  1341. if info.Enabled && !info.Forbidden {
  1342. vhost = info.ApprovedVHost
  1343. }
  1344. oldNickmask := client.NickMaskString()
  1345. updated := client.SetVHost(vhost)
  1346. if updated {
  1347. // TODO: doing I/O here is kind of a kludge
  1348. go client.sendChghost(oldNickmask, client.Hostname())
  1349. }
  1350. }
  1351. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1352. am.RLock()
  1353. clients := am.accountToClients[account]
  1354. am.RUnlock()
  1355. for _, client := range clients {
  1356. am.applyVHostInfo(client, result)
  1357. }
  1358. }
  1359. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1360. client.Login(account)
  1361. client.nickTimer.Touch(nil)
  1362. am.applyVHostInfo(client, account.VHost)
  1363. casefoldedAccount := client.Account()
  1364. am.Lock()
  1365. defer am.Unlock()
  1366. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1367. }
  1368. func (am *AccountManager) Logout(client *Client) {
  1369. am.Lock()
  1370. defer am.Unlock()
  1371. casefoldedAccount := client.Account()
  1372. if casefoldedAccount == "" {
  1373. return
  1374. }
  1375. am.logoutOfAccount(client)
  1376. clients := am.accountToClients[casefoldedAccount]
  1377. if len(clients) <= 1 {
  1378. delete(am.accountToClients, casefoldedAccount)
  1379. return
  1380. }
  1381. remainingClients := make([]*Client, len(clients)-1)
  1382. remainingPos := 0
  1383. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1384. if clients[currentPos] != client {
  1385. remainingClients[remainingPos] = clients[currentPos]
  1386. remainingPos++
  1387. }
  1388. }
  1389. am.accountToClients[casefoldedAccount] = remainingClients
  1390. }
  1391. var (
  1392. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1393. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1394. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1395. "PLAIN": authPlainHandler,
  1396. "EXTERNAL": authExternalHandler,
  1397. }
  1398. )
  1399. // AccountCredentials stores the various methods for verifying accounts.
  1400. type AccountCredentials struct {
  1401. Version uint
  1402. PassphraseSalt []byte // legacy field, not used by v1 and later
  1403. PassphraseHash []byte
  1404. Certfps []string
  1405. }
  1406. func (ac *AccountCredentials) Empty() bool {
  1407. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1408. }
  1409. // helper to assemble the serialized JSON for an account's credentials
  1410. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1411. ac.Version = 1
  1412. credText, err := json.Marshal(*ac)
  1413. if err != nil {
  1414. return "", err
  1415. }
  1416. return string(credText), nil
  1417. }
  1418. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1419. if passphrase == "" {
  1420. ac.PassphraseHash = nil
  1421. return nil
  1422. }
  1423. if validatePassphrase(passphrase) != nil {
  1424. return errAccountBadPassphrase
  1425. }
  1426. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1427. if err != nil {
  1428. return errAccountBadPassphrase
  1429. }
  1430. return nil
  1431. }
  1432. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1433. // XXX we require that certfp is already normalized (rather than normalize here
  1434. // and pass back the normalized version as an additional return parameter);
  1435. // this is just a final sanity check:
  1436. if len(certfp) != 64 {
  1437. return utils.ErrInvalidCertfp
  1438. }
  1439. for _, current := range ac.Certfps {
  1440. if certfp == current {
  1441. return errNoop
  1442. }
  1443. }
  1444. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1445. return errLimitExceeded
  1446. }
  1447. ac.Certfps = append(ac.Certfps, certfp)
  1448. return nil
  1449. }
  1450. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1451. found := false
  1452. newList := make([]string, 0, len(ac.Certfps))
  1453. for _, current := range ac.Certfps {
  1454. if current == certfp {
  1455. found = true
  1456. } else {
  1457. newList = append(newList, current)
  1458. }
  1459. }
  1460. if !found {
  1461. // this is important because it prevents you from deleting someone else's
  1462. // fingerprint record
  1463. return errNoop
  1464. }
  1465. ac.Certfps = newList
  1466. return nil
  1467. }
  1468. type MulticlientAllowedSetting int
  1469. const (
  1470. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1471. MulticlientDisallowedByUser
  1472. MulticlientAllowedByUser
  1473. )
  1474. // controls whether/when clients without event-playback support see fake
  1475. // PRIVMSGs for JOINs
  1476. type ReplayJoinsSetting uint
  1477. const (
  1478. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1479. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1480. ReplayJoinsNever // never replay
  1481. )
  1482. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1483. switch strings.ToLower(str) {
  1484. case "commands-only":
  1485. result = ReplayJoinsCommandsOnly
  1486. case "always":
  1487. result = ReplayJoinsAlways
  1488. case "never":
  1489. result = ReplayJoinsNever
  1490. default:
  1491. err = errInvalidParams
  1492. }
  1493. return
  1494. }
  1495. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1496. // persistent JSON blobs in the database
  1497. type AccountSettings struct {
  1498. AutoreplayLines *int
  1499. NickEnforcement NickEnforcementMethod
  1500. AllowBouncer MulticlientAllowedSetting
  1501. ReplayJoins ReplayJoinsSetting
  1502. AlwaysOn PersistentStatus
  1503. AutoreplayMissed bool
  1504. DMHistory HistoryStatus
  1505. }
  1506. // ClientAccount represents a user account.
  1507. type ClientAccount struct {
  1508. // Name of the account.
  1509. Name string
  1510. NameCasefolded string
  1511. RegisteredAt time.Time
  1512. Credentials AccountCredentials
  1513. Verified bool
  1514. AdditionalNicks []string
  1515. VHost VHostInfo
  1516. Settings AccountSettings
  1517. }
  1518. // convenience for passing around raw serialized account data
  1519. type rawClientAccount struct {
  1520. Name string
  1521. RegisteredAt string
  1522. Credentials string
  1523. Callback string
  1524. Verified bool
  1525. AdditionalNicks string
  1526. VHost string
  1527. Settings string
  1528. }
  1529. // logoutOfAccount logs the client out of their current account.
  1530. func (am *AccountManager) logoutOfAccount(client *Client) {
  1531. if client.Account() == "" {
  1532. // already logged out
  1533. return
  1534. }
  1535. client.Logout()
  1536. go client.nickTimer.Touch(nil)
  1537. // dispatch account-notify
  1538. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1539. go func() {
  1540. for friend := range client.Friends(caps.AccountNotify) {
  1541. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1542. }
  1543. }()
  1544. }