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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. var account ClientAccount
  814. defer func() {
  815. if err == nil {
  816. am.Login(client, account)
  817. }
  818. }()
  819. ldapConf := am.server.Config().Accounts.LDAP
  820. if ldapConf.Enabled {
  821. err = ldap.CheckLDAPPassphrase(ldapConf, accountName, passphrase, am.server.logger)
  822. if err == nil {
  823. account, err = am.LoadAccount(accountName)
  824. // autocreate if necessary:
  825. if err == errAccountDoesNotExist && ldapConf.Autocreate {
  826. err = am.SARegister(accountName, "")
  827. if err != nil {
  828. return
  829. }
  830. account, err = am.LoadAccount(accountName)
  831. }
  832. return
  833. }
  834. }
  835. account, err = am.checkPassphrase(accountName, passphrase)
  836. return err
  837. }
  838. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  839. casefoldedAccount, err := CasefoldName(accountName)
  840. if err != nil {
  841. err = errAccountDoesNotExist
  842. return
  843. }
  844. var raw rawClientAccount
  845. am.server.store.View(func(tx *buntdb.Tx) error {
  846. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  847. return nil
  848. })
  849. if err != nil {
  850. return
  851. }
  852. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  853. return
  854. }
  855. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  856. result.Name = raw.Name
  857. result.NameCasefolded = cfName
  858. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  859. result.RegisteredAt = time.Unix(regTimeInt, 0).UTC()
  860. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  861. if e != nil {
  862. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  863. err = errAccountDoesNotExist
  864. return
  865. }
  866. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  867. result.Verified = raw.Verified
  868. if raw.VHost != "" {
  869. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  870. if e != nil {
  871. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  872. // pretend they have no vhost and move on
  873. }
  874. }
  875. if raw.Settings != "" {
  876. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  877. if e != nil {
  878. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  879. }
  880. }
  881. return
  882. }
  883. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  884. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  885. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  886. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  887. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  888. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  889. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  890. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  891. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  892. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  893. _, e := tx.Get(accountKey)
  894. if e == buntdb.ErrNotFound {
  895. err = errAccountDoesNotExist
  896. return
  897. }
  898. result.Name, _ = tx.Get(accountNameKey)
  899. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  900. result.Credentials, _ = tx.Get(credentialsKey)
  901. result.Callback, _ = tx.Get(callbackKey)
  902. result.AdditionalNicks, _ = tx.Get(nicksKey)
  903. result.VHost, _ = tx.Get(vhostKey)
  904. result.Settings, _ = tx.Get(settingsKey)
  905. if _, e = tx.Get(verifiedKey); e == nil {
  906. result.Verified = true
  907. }
  908. return
  909. }
  910. func (am *AccountManager) Unregister(account string) error {
  911. config := am.server.Config()
  912. casefoldedAccount, err := CasefoldName(account)
  913. if err != nil {
  914. return errAccountDoesNotExist
  915. }
  916. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  917. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  918. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  919. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  920. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  921. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  922. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  923. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  924. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  925. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  926. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  927. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  928. joinedChannelsKey := fmt.Sprintf(keyAccountJoinedChannels, casefoldedAccount)
  929. lastSignoffKey := fmt.Sprintf(keyAccountLastSignoff, casefoldedAccount)
  930. var clients []*Client
  931. var registeredChannels []string
  932. // on our way out, unregister all the account's channels and delete them from the db
  933. defer func() {
  934. for _, channelName := range registeredChannels {
  935. am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  936. }
  937. }()
  938. var credText string
  939. var rawNicks string
  940. am.serialCacheUpdateMutex.Lock()
  941. defer am.serialCacheUpdateMutex.Unlock()
  942. var accountName string
  943. var channelsStr string
  944. am.server.store.Update(func(tx *buntdb.Tx) error {
  945. tx.Delete(accountKey)
  946. accountName, _ = tx.Get(accountNameKey)
  947. tx.Delete(accountNameKey)
  948. tx.Delete(verifiedKey)
  949. tx.Delete(registeredTimeKey)
  950. tx.Delete(callbackKey)
  951. tx.Delete(verificationCodeKey)
  952. tx.Delete(settingsKey)
  953. rawNicks, _ = tx.Get(nicksKey)
  954. tx.Delete(nicksKey)
  955. credText, err = tx.Get(credentialsKey)
  956. tx.Delete(credentialsKey)
  957. tx.Delete(vhostKey)
  958. channelsStr, _ = tx.Get(channelsKey)
  959. tx.Delete(channelsKey)
  960. tx.Delete(joinedChannelsKey)
  961. tx.Delete(lastSignoffKey)
  962. _, err := tx.Delete(vhostQueueKey)
  963. am.decrementVHostQueueCount(casefoldedAccount, err)
  964. return nil
  965. })
  966. if err == nil {
  967. var creds AccountCredentials
  968. if err = json.Unmarshal([]byte(credText), &creds); err == nil {
  969. for _, cert := range creds.Certfps {
  970. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  971. am.server.store.Update(func(tx *buntdb.Tx) error {
  972. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  973. tx.Delete(certFPKey)
  974. }
  975. return nil
  976. })
  977. }
  978. }
  979. }
  980. skeleton, _ := Skeleton(accountName)
  981. additionalNicks := unmarshalReservedNicks(rawNicks)
  982. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  983. am.Lock()
  984. defer am.Unlock()
  985. clients = am.accountToClients[casefoldedAccount]
  986. delete(am.accountToClients, casefoldedAccount)
  987. delete(am.nickToAccount, casefoldedAccount)
  988. delete(am.skeletonToAccount, skeleton)
  989. for _, nick := range additionalNicks {
  990. delete(am.nickToAccount, nick)
  991. additionalSkel, _ := Skeleton(nick)
  992. delete(am.skeletonToAccount, additionalSkel)
  993. }
  994. for _, client := range clients {
  995. if config.Accounts.RequireSasl.Enabled {
  996. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  997. // destroy acquires a semaphore so we can't call it while holding a lock
  998. go client.destroy(nil)
  999. } else {
  1000. am.logoutOfAccount(client)
  1001. }
  1002. }
  1003. if err != nil {
  1004. return errAccountDoesNotExist
  1005. }
  1006. return nil
  1007. }
  1008. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1009. if channelsStr != "" {
  1010. result = strings.Split(channelsStr, ",")
  1011. }
  1012. return
  1013. }
  1014. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1015. cfaccount, err := CasefoldName(account)
  1016. if err != nil {
  1017. return
  1018. }
  1019. var channelStr string
  1020. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1021. am.server.store.View(func(tx *buntdb.Tx) error {
  1022. channelStr, _ = tx.Get(key)
  1023. return nil
  1024. })
  1025. return unmarshalRegisteredChannels(channelStr)
  1026. }
  1027. func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid string) error {
  1028. if certfp == "" {
  1029. return errAccountInvalidCredentials
  1030. }
  1031. var account string
  1032. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1033. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1034. account, _ = tx.Get(certFPKey)
  1035. if account == "" {
  1036. return errAccountInvalidCredentials
  1037. }
  1038. return nil
  1039. })
  1040. if err != nil {
  1041. return err
  1042. }
  1043. if authzid != "" && authzid != account {
  1044. return errAuthzidAuthcidMismatch
  1045. }
  1046. // ok, we found an account corresponding to their certificate
  1047. clientAccount, err := am.LoadAccount(account)
  1048. if err != nil {
  1049. return err
  1050. } else if !clientAccount.Verified {
  1051. return errAccountUnverified
  1052. }
  1053. am.Login(client, clientAccount)
  1054. return nil
  1055. }
  1056. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1057. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1058. casefoldedAccount, err := CasefoldName(account)
  1059. if err != nil {
  1060. return newSettings, errAccountDoesNotExist
  1061. }
  1062. // TODO implement this in general via a compare-and-swap API
  1063. accountData, err := am.LoadAccount(casefoldedAccount)
  1064. if err != nil {
  1065. return
  1066. } else if !accountData.Verified {
  1067. return newSettings, errAccountUnverified
  1068. }
  1069. newSettings, err = munger(accountData.Settings)
  1070. if err != nil {
  1071. return
  1072. }
  1073. text, err := json.Marshal(newSettings)
  1074. if err != nil {
  1075. return
  1076. }
  1077. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1078. serializedValue := string(text)
  1079. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1080. _, _, err = tx.Set(key, serializedValue, nil)
  1081. return
  1082. })
  1083. if err != nil {
  1084. err = errAccountUpdateFailed
  1085. return
  1086. }
  1087. // success, push new settings into the client objects
  1088. am.Lock()
  1089. defer am.Unlock()
  1090. for _, client := range am.accountToClients[casefoldedAccount] {
  1091. client.SetAccountSettings(newSettings)
  1092. }
  1093. return
  1094. }
  1095. // represents someone's status in hostserv
  1096. type VHostInfo struct {
  1097. ApprovedVHost string
  1098. Enabled bool
  1099. Forbidden bool
  1100. RequestedVHost string
  1101. RejectedVHost string
  1102. RejectionReason string
  1103. LastRequestTime time.Time
  1104. }
  1105. // pair type, <VHostInfo, accountName>
  1106. type PendingVHostRequest struct {
  1107. VHostInfo
  1108. Account string
  1109. }
  1110. type vhostThrottleExceeded struct {
  1111. timeRemaining time.Duration
  1112. }
  1113. func (vhe *vhostThrottleExceeded) Error() string {
  1114. return fmt.Sprintf("Wait at least %v and try again", vhe.timeRemaining)
  1115. }
  1116. func (vh *VHostInfo) checkThrottle(cooldown time.Duration) (err error) {
  1117. if cooldown == 0 {
  1118. return nil
  1119. }
  1120. now := time.Now().UTC()
  1121. elapsed := now.Sub(vh.LastRequestTime)
  1122. if elapsed > cooldown {
  1123. // success
  1124. vh.LastRequestTime = now
  1125. return nil
  1126. } else {
  1127. return &vhostThrottleExceeded{timeRemaining: cooldown - elapsed}
  1128. }
  1129. }
  1130. // callback type implementing the actual business logic of vhost operations
  1131. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1132. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1133. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1134. output = input
  1135. output.Enabled = true
  1136. output.ApprovedVHost = vhost
  1137. return
  1138. }
  1139. return am.performVHostChange(account, munger)
  1140. }
  1141. func (am *AccountManager) VHostRequest(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1142. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1143. output = input
  1144. if input.Forbidden {
  1145. err = errVhostsForbidden
  1146. return
  1147. }
  1148. // you can update your existing request, but if you were approved or rejected,
  1149. // you can't spam a new request
  1150. if output.RequestedVHost == "" {
  1151. err = output.checkThrottle(cooldown)
  1152. }
  1153. if err != nil {
  1154. return
  1155. }
  1156. output.RequestedVHost = vhost
  1157. output.RejectedVHost = ""
  1158. output.RejectionReason = ""
  1159. output.LastRequestTime = time.Now().UTC()
  1160. return
  1161. }
  1162. return am.performVHostChange(account, munger)
  1163. }
  1164. func (am *AccountManager) VHostTake(account string, vhost string, cooldown time.Duration) (result VHostInfo, err error) {
  1165. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1166. output = input
  1167. if input.Forbidden {
  1168. err = errVhostsForbidden
  1169. return
  1170. }
  1171. // if you have a request pending, you can cancel it using take;
  1172. // otherwise, you're subject to the same throttling as if you were making a request
  1173. if output.RequestedVHost == "" {
  1174. err = output.checkThrottle(cooldown)
  1175. }
  1176. if err != nil {
  1177. return
  1178. }
  1179. output.ApprovedVHost = vhost
  1180. output.RequestedVHost = ""
  1181. output.RejectedVHost = ""
  1182. output.RejectionReason = ""
  1183. output.LastRequestTime = time.Now().UTC()
  1184. return
  1185. }
  1186. return am.performVHostChange(account, munger)
  1187. }
  1188. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1189. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1190. output = input
  1191. output.Enabled = true
  1192. output.ApprovedVHost = input.RequestedVHost
  1193. output.RequestedVHost = ""
  1194. output.RejectionReason = ""
  1195. return
  1196. }
  1197. return am.performVHostChange(account, munger)
  1198. }
  1199. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1200. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1201. output = input
  1202. output.RejectedVHost = output.RequestedVHost
  1203. output.RequestedVHost = ""
  1204. output.RejectionReason = reason
  1205. return
  1206. }
  1207. return am.performVHostChange(account, munger)
  1208. }
  1209. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1210. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1211. if input.ApprovedVHost == "" {
  1212. err = errNoVhost
  1213. return
  1214. }
  1215. output = input
  1216. output.Enabled = enabled
  1217. return
  1218. }
  1219. return am.performVHostChange(client.Account(), munger)
  1220. }
  1221. func (am *AccountManager) VHostForbid(account string, forbid bool) (result VHostInfo, err error) {
  1222. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1223. output = input
  1224. output.Forbidden = forbid
  1225. return
  1226. }
  1227. return am.performVHostChange(account, munger)
  1228. }
  1229. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1230. account, err = CasefoldName(account)
  1231. if err != nil || account == "" {
  1232. err = errAccountDoesNotExist
  1233. return
  1234. }
  1235. am.vHostUpdateMutex.Lock()
  1236. defer am.vHostUpdateMutex.Unlock()
  1237. clientAccount, err := am.LoadAccount(account)
  1238. if err != nil {
  1239. err = errAccountDoesNotExist
  1240. return
  1241. } else if !clientAccount.Verified {
  1242. err = errAccountUnverified
  1243. return
  1244. }
  1245. result, err = munger(clientAccount.VHost)
  1246. if err != nil {
  1247. return
  1248. }
  1249. vhtext, err := json.Marshal(result)
  1250. if err != nil {
  1251. err = errAccountUpdateFailed
  1252. return
  1253. }
  1254. vhstr := string(vhtext)
  1255. key := fmt.Sprintf(keyAccountVHost, account)
  1256. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1257. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1258. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1259. return err
  1260. }
  1261. // update request queue
  1262. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1263. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1264. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1265. return err
  1266. }
  1267. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1268. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1269. _, err = tx.Delete(queueKey)
  1270. am.decrementVHostQueueCount(account, err)
  1271. }
  1272. return nil
  1273. })
  1274. if err != nil {
  1275. err = errAccountUpdateFailed
  1276. return
  1277. }
  1278. am.applyVhostToClients(account, result)
  1279. return result, nil
  1280. }
  1281. // XXX annoying helper method for keeping the queue count in sync with the DB
  1282. // `err` is the buntdb error returned from deleting the queue key
  1283. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1284. if err == nil {
  1285. // successfully deleted a queue entry, do a 2's complement decrement:
  1286. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1287. } else if err != buntdb.ErrNotFound {
  1288. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1289. }
  1290. }
  1291. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1292. am.vHostUpdateMutex.Lock()
  1293. defer am.vHostUpdateMutex.Unlock()
  1294. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1295. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1296. accounts := make([]string, 0, limit)
  1297. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1298. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1299. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1300. return len(accounts) < limit
  1301. })
  1302. })
  1303. if err != nil {
  1304. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1305. return
  1306. }
  1307. for _, account := range accounts {
  1308. accountInfo, err := am.LoadAccount(account)
  1309. if err == nil {
  1310. requests = append(requests, PendingVHostRequest{
  1311. Account: account,
  1312. VHostInfo: accountInfo.VHost,
  1313. })
  1314. } else {
  1315. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1316. }
  1317. }
  1318. return
  1319. }
  1320. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1321. // if hostserv is disabled in config, then don't grant vhosts
  1322. // that were previously approved while it was enabled
  1323. if !am.server.AccountConfig().VHosts.Enabled {
  1324. return
  1325. }
  1326. vhost := ""
  1327. if info.Enabled && !info.Forbidden {
  1328. vhost = info.ApprovedVHost
  1329. }
  1330. oldNickmask := client.NickMaskString()
  1331. updated := client.SetVHost(vhost)
  1332. if updated {
  1333. // TODO: doing I/O here is kind of a kludge
  1334. go client.sendChghost(oldNickmask, client.Hostname())
  1335. }
  1336. }
  1337. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1338. am.RLock()
  1339. clients := am.accountToClients[account]
  1340. am.RUnlock()
  1341. for _, client := range clients {
  1342. am.applyVHostInfo(client, result)
  1343. }
  1344. }
  1345. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1346. client.Login(account)
  1347. client.nickTimer.Touch(nil)
  1348. am.applyVHostInfo(client, account.VHost)
  1349. casefoldedAccount := client.Account()
  1350. am.Lock()
  1351. defer am.Unlock()
  1352. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1353. }
  1354. func (am *AccountManager) Logout(client *Client) {
  1355. am.Lock()
  1356. defer am.Unlock()
  1357. casefoldedAccount := client.Account()
  1358. if casefoldedAccount == "" {
  1359. return
  1360. }
  1361. am.logoutOfAccount(client)
  1362. clients := am.accountToClients[casefoldedAccount]
  1363. if len(clients) <= 1 {
  1364. delete(am.accountToClients, casefoldedAccount)
  1365. return
  1366. }
  1367. remainingClients := make([]*Client, len(clients)-1)
  1368. remainingPos := 0
  1369. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1370. if clients[currentPos] != client {
  1371. remainingClients[remainingPos] = clients[currentPos]
  1372. remainingPos++
  1373. }
  1374. }
  1375. am.accountToClients[casefoldedAccount] = remainingClients
  1376. }
  1377. var (
  1378. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1379. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1380. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1381. "PLAIN": authPlainHandler,
  1382. "EXTERNAL": authExternalHandler,
  1383. }
  1384. )
  1385. // AccountCredentials stores the various methods for verifying accounts.
  1386. type AccountCredentials struct {
  1387. Version uint
  1388. PassphraseSalt []byte // legacy field, not used by v1 and later
  1389. PassphraseHash []byte
  1390. Certfps []string
  1391. }
  1392. func (ac *AccountCredentials) Empty() bool {
  1393. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1394. }
  1395. // helper to assemble the serialized JSON for an account's credentials
  1396. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1397. ac.Version = 1
  1398. credText, err := json.Marshal(*ac)
  1399. if err != nil {
  1400. return "", err
  1401. }
  1402. return string(credText), nil
  1403. }
  1404. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1405. if passphrase == "" {
  1406. ac.PassphraseHash = nil
  1407. return nil
  1408. }
  1409. if validatePassphrase(passphrase) != nil {
  1410. return errAccountBadPassphrase
  1411. }
  1412. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1413. if err != nil {
  1414. return errAccountBadPassphrase
  1415. }
  1416. return nil
  1417. }
  1418. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1419. // XXX we require that certfp is already normalized (rather than normalize here
  1420. // and pass back the normalized version as an additional return parameter);
  1421. // this is just a final sanity check:
  1422. if len(certfp) != 64 {
  1423. return utils.ErrInvalidCertfp
  1424. }
  1425. for _, current := range ac.Certfps {
  1426. if certfp == current {
  1427. return errNoop
  1428. }
  1429. }
  1430. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1431. return errLimitExceeded
  1432. }
  1433. ac.Certfps = append(ac.Certfps, certfp)
  1434. return nil
  1435. }
  1436. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1437. found := false
  1438. newList := make([]string, 0, len(ac.Certfps))
  1439. for _, current := range ac.Certfps {
  1440. if current == certfp {
  1441. found = true
  1442. } else {
  1443. newList = append(newList, current)
  1444. }
  1445. }
  1446. if !found {
  1447. // this is important because it prevents you from deleting someone else's
  1448. // fingerprint record
  1449. return errNoop
  1450. }
  1451. ac.Certfps = newList
  1452. return nil
  1453. }
  1454. type MulticlientAllowedSetting int
  1455. const (
  1456. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1457. MulticlientDisallowedByUser
  1458. MulticlientAllowedByUser
  1459. )
  1460. // controls whether/when clients without event-playback support see fake
  1461. // PRIVMSGs for JOINs
  1462. type ReplayJoinsSetting uint
  1463. const (
  1464. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1465. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1466. ReplayJoinsNever // never replay
  1467. )
  1468. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1469. switch strings.ToLower(str) {
  1470. case "commands-only":
  1471. result = ReplayJoinsCommandsOnly
  1472. case "always":
  1473. result = ReplayJoinsAlways
  1474. case "never":
  1475. result = ReplayJoinsNever
  1476. default:
  1477. err = errInvalidParams
  1478. }
  1479. return
  1480. }
  1481. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1482. // persistent JSON blobs in the database
  1483. type AccountSettings struct {
  1484. AutoreplayLines *int
  1485. NickEnforcement NickEnforcementMethod
  1486. AllowBouncer MulticlientAllowedSetting
  1487. ReplayJoins ReplayJoinsSetting
  1488. AlwaysOn PersistentStatus
  1489. AutoreplayMissed bool
  1490. DMHistory HistoryStatus
  1491. }
  1492. // ClientAccount represents a user account.
  1493. type ClientAccount struct {
  1494. // Name of the account.
  1495. Name string
  1496. NameCasefolded string
  1497. RegisteredAt time.Time
  1498. Credentials AccountCredentials
  1499. Verified bool
  1500. AdditionalNicks []string
  1501. VHost VHostInfo
  1502. Settings AccountSettings
  1503. }
  1504. // convenience for passing around raw serialized account data
  1505. type rawClientAccount struct {
  1506. Name string
  1507. RegisteredAt string
  1508. Credentials string
  1509. Callback string
  1510. Verified bool
  1511. AdditionalNicks string
  1512. VHost string
  1513. Settings string
  1514. }
  1515. // logoutOfAccount logs the client out of their current account.
  1516. func (am *AccountManager) logoutOfAccount(client *Client) {
  1517. if client.Account() == "" {
  1518. // already logged out
  1519. return
  1520. }
  1521. client.Logout()
  1522. go client.nickTimer.Touch(nil)
  1523. // dispatch account-notify
  1524. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1525. go func() {
  1526. for friend := range client.Friends(caps.AccountNotify) {
  1527. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1528. }
  1529. }()
  1530. }