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.

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