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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "crypto/rand"
  6. "crypto/x509"
  7. "encoding/json"
  8. "fmt"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "unicode"
  15. "github.com/ergochat/irc-go/ircutils"
  16. "github.com/tidwall/buntdb"
  17. "github.com/xdg-go/scram"
  18. "github.com/ergochat/ergo/irc/connection_limits"
  19. "github.com/ergochat/ergo/irc/email"
  20. "github.com/ergochat/ergo/irc/migrations"
  21. "github.com/ergochat/ergo/irc/modes"
  22. "github.com/ergochat/ergo/irc/passwd"
  23. "github.com/ergochat/ergo/irc/utils"
  24. )
  25. const (
  26. keyAccountExists = "account.exists %s"
  27. keyAccountVerified = "account.verified %s"
  28. keyAccountUnregistered = "account.unregistered %s"
  29. keyAccountVerificationCode = "account.verificationcode %s"
  30. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  31. keyAccountRegTime = "account.registered.time %s"
  32. keyAccountCredentials = "account.credentials %s"
  33. keyAccountAdditionalNicks = "account.additionalnicks %s"
  34. keyAccountSettings = "account.settings %s"
  35. keyAccountVHost = "account.vhost %s"
  36. keyCertToAccount = "account.creds.certfp %s"
  37. keyAccountChannels = "account.channels %s" // channels registered to the account
  38. keyAccountLastSeen = "account.lastseen %s"
  39. keyAccountReadMarkers = "account.readmarkers %s"
  40. keyAccountModes = "account.modes %s" // user modes for the always-on client as a string
  41. keyAccountRealname = "account.realname %s" // client realname stored as string
  42. keyAccountSuspended = "account.suspended %s" // client realname stored as string
  43. keyAccountPwReset = "account.pwreset %s"
  44. keyAccountEmailChange = "account.emailchange %s"
  45. // for an always-on client, a map of channel names they're in to their current modes
  46. // (not to be confused with their amodes, which a non-always-on client can have):
  47. keyAccountChannelToModes = "account.channeltomodes %s"
  48. maxCertfpsPerAccount = 5
  49. )
  50. // everything about accounts is persistent; therefore, the database is the authoritative
  51. // source of truth for all account information. anything on the heap is just a cache
  52. type AccountManager struct {
  53. sync.RWMutex // tier 2
  54. serialCacheUpdateMutex sync.Mutex // tier 3
  55. server *Server
  56. // track clients logged in to accounts
  57. accountToClients map[string][]*Client
  58. nickToAccount map[string]string
  59. skeletonToAccount map[string]string
  60. accountToMethod map[string]NickEnforcementMethod
  61. registerThrottle connection_limits.GenericThrottle
  62. }
  63. func (am *AccountManager) Initialize(server *Server) {
  64. am.accountToClients = make(map[string][]*Client)
  65. am.nickToAccount = make(map[string]string)
  66. am.skeletonToAccount = make(map[string]string)
  67. am.accountToMethod = make(map[string]NickEnforcementMethod)
  68. am.server = server
  69. config := server.Config()
  70. am.buildNickToAccountIndex(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 && account.Suspended == nil) &&
  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 && rawPrefs != "" {
  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 settings", account, err.Error())
  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) NickToAccount(nick string) string {
  197. cfnick, err := CasefoldName(nick)
  198. if err != nil {
  199. return ""
  200. }
  201. skel, err := Skeleton(nick)
  202. if err != nil {
  203. return ""
  204. }
  205. am.RLock()
  206. defer am.RUnlock()
  207. account := am.nickToAccount[cfnick]
  208. if account != "" {
  209. return account
  210. }
  211. return am.skeletonToAccount[skel]
  212. }
  213. // given an account, combine stored enforcement method with the config settings
  214. // to compute the actual enforcement method
  215. func configuredEnforcementMethod(config *Config, storedMethod NickEnforcementMethod) (result NickEnforcementMethod) {
  216. if !config.Accounts.NickReservation.Enabled {
  217. return NickEnforcementNone
  218. }
  219. result = storedMethod
  220. // if they don't have a custom setting, or customization is disabled, use the default
  221. if result == NickEnforcementOptional || !config.Accounts.NickReservation.AllowCustomEnforcement {
  222. result = config.Accounts.NickReservation.Method
  223. }
  224. if result == NickEnforcementOptional {
  225. // enforcement was explicitly enabled neither in the config or by the user
  226. result = NickEnforcementNone
  227. }
  228. return
  229. }
  230. // Given a nick, looks up the account that owns it and the method (none/timeout/strict)
  231. // used to enforce ownership.
  232. func (am *AccountManager) EnforcementStatus(cfnick, skeleton string) (account string, method NickEnforcementMethod) {
  233. config := am.server.Config()
  234. if !config.Accounts.NickReservation.Enabled {
  235. return "", NickEnforcementNone
  236. }
  237. am.RLock()
  238. defer am.RUnlock()
  239. finalEnforcementMethod := func(account_ string) (result NickEnforcementMethod) {
  240. storedMethod := am.accountToMethod[account_]
  241. return configuredEnforcementMethod(config, storedMethod)
  242. }
  243. nickAccount := am.nickToAccount[cfnick]
  244. skelAccount := am.skeletonToAccount[skeleton]
  245. if nickAccount == "" && skelAccount == "" {
  246. return "", NickEnforcementNone
  247. } else if nickAccount != "" && (skelAccount == nickAccount || skelAccount == "") {
  248. return nickAccount, finalEnforcementMethod(nickAccount)
  249. } else if skelAccount != "" && nickAccount == "" {
  250. return skelAccount, finalEnforcementMethod(skelAccount)
  251. } else {
  252. // nickAccount != skelAccount and both are nonempty:
  253. // two people have competing claims on (this casefolding of) this nick!
  254. nickMethod := finalEnforcementMethod(nickAccount)
  255. skelMethod := finalEnforcementMethod(skelAccount)
  256. switch {
  257. case skelMethod == NickEnforcementNone:
  258. return nickAccount, nickMethod
  259. case nickMethod == NickEnforcementNone:
  260. return skelAccount, skelMethod
  261. default:
  262. // nobody can use this nick
  263. return "!", NickEnforcementStrict
  264. }
  265. }
  266. }
  267. // Sets a custom enforcement method for an account and stores it in the database.
  268. func (am *AccountManager) SetEnforcementStatus(account string, method NickEnforcementMethod) (finalSettings AccountSettings, err error) {
  269. config := am.server.Config()
  270. if !(config.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.AllowCustomEnforcement) {
  271. err = errFeatureDisabled
  272. return
  273. }
  274. setter := func(in AccountSettings) (out AccountSettings, err error) {
  275. out = in
  276. out.NickEnforcement = method
  277. return out, nil
  278. }
  279. _, err = am.ModifyAccountSettings(account, setter)
  280. if err != nil {
  281. return
  282. }
  283. // this update of the data plane is racey, but it's probably fine
  284. am.Lock()
  285. defer am.Unlock()
  286. if method == NickEnforcementOptional {
  287. delete(am.accountToMethod, account)
  288. } else {
  289. am.accountToMethod[account] = method
  290. }
  291. return
  292. }
  293. func (am *AccountManager) AccountToClients(account string) (result []*Client) {
  294. cfaccount, err := CasefoldName(account)
  295. if err != nil {
  296. return
  297. }
  298. am.RLock()
  299. defer am.RUnlock()
  300. return am.accountToClients[cfaccount]
  301. }
  302. func (am *AccountManager) Register(client *Client, account string, callbackNamespace string, callbackValue string, passphrase string, certfp string) error {
  303. casefoldedAccount, err := CasefoldName(account)
  304. skeleton, skerr := Skeleton(account)
  305. if err != nil || skerr != nil || account == "" || account == "*" {
  306. return errAccountCreation
  307. }
  308. if restrictedCasefoldedNicks.Has(casefoldedAccount) || restrictedSkeletons.Has(skeleton) {
  309. return errAccountAlreadyRegistered
  310. }
  311. config := am.server.Config()
  312. // final "is registration allowed" check:
  313. if callbackNamespace != "admin" && (!config.Accounts.Registration.Enabled || am.server.Defcon() <= 4) {
  314. return errFeatureDisabled
  315. }
  316. if client != nil && client.Account() != "" {
  317. return errAccountAlreadyLoggedIn
  318. }
  319. if client != nil && am.touchRegisterThrottle() {
  320. am.server.logger.Warning("accounts", "global registration throttle exceeded by client", client.Nick())
  321. return errLimitExceeded
  322. }
  323. // if nick reservation is enabled, don't let people reserve nicknames
  324. // that they would not be eligible to take, e.g.,
  325. // 1. a nickname that someone else is currently holding
  326. // 2. a nickname confusable with an existing reserved nickname
  327. // this has a lot of weird edge cases because of force-guest-format
  328. // and the possibility of registering a nickname on an "unregistered connection"
  329. // (i.e., pre-handshake).
  330. if client != nil && config.Accounts.NickReservation.Enabled {
  331. _, nickAcquireError, _ := am.server.clients.SetNick(client, nil, account, true)
  332. if !(nickAcquireError == nil || nickAcquireError == errNoop) {
  333. return errAccountMustHoldNick
  334. }
  335. }
  336. // can't register a guest nickname
  337. if config.Accounts.NickReservation.guestRegexpFolded.MatchString(casefoldedAccount) {
  338. return errAccountAlreadyRegistered
  339. }
  340. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  341. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  342. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  343. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  344. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  345. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  346. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  347. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  348. var creds AccountCredentials
  349. creds.Version = 1
  350. err = creds.SetPassphrase(passphrase, am.server.Config().Accounts.Registration.BcryptCost)
  351. if err != nil {
  352. return err
  353. }
  354. creds.AddCertfp(certfp)
  355. credStr, err := creds.Serialize()
  356. if err != nil {
  357. return err
  358. }
  359. var settingsStr string
  360. if callbackNamespace == "mailto" {
  361. settings := AccountSettings{Email: callbackValue}
  362. j, err := json.Marshal(settings)
  363. if err == nil {
  364. settingsStr = string(j)
  365. }
  366. }
  367. registeredTimeStr := strconv.FormatInt(time.Now().UnixNano(), 10)
  368. var setOptions *buntdb.SetOptions
  369. ttl := time.Duration(config.Accounts.Registration.VerifyTimeout)
  370. if ttl != 0 {
  371. setOptions = &buntdb.SetOptions{Expires: true, TTL: ttl}
  372. }
  373. err = func() error {
  374. am.serialCacheUpdateMutex.Lock()
  375. defer am.serialCacheUpdateMutex.Unlock()
  376. // can't register an account with the same name as a registered nick
  377. if am.NickToAccount(account) != "" {
  378. return errAccountAlreadyRegistered
  379. }
  380. return am.server.store.Update(func(tx *buntdb.Tx) error {
  381. if _, err := tx.Get(unregisteredKey); err == nil {
  382. return errAccountAlreadyUnregistered
  383. }
  384. _, err = am.loadRawAccount(tx, casefoldedAccount)
  385. if err != errAccountDoesNotExist {
  386. return errAccountAlreadyRegistered
  387. }
  388. if certfp != "" {
  389. // make sure certfp doesn't already exist because that'd be silly
  390. _, err := tx.Get(certFPKey)
  391. if err != buntdb.ErrNotFound {
  392. return errCertfpAlreadyExists
  393. }
  394. }
  395. tx.Set(accountKey, "1", setOptions)
  396. tx.Set(accountNameKey, account, setOptions)
  397. tx.Set(registeredTimeKey, registeredTimeStr, setOptions)
  398. tx.Set(credentialsKey, credStr, setOptions)
  399. tx.Set(settingsKey, settingsStr, setOptions)
  400. if certfp != "" {
  401. tx.Set(certFPKey, casefoldedAccount, setOptions)
  402. }
  403. return nil
  404. })
  405. }()
  406. if err != nil {
  407. return err
  408. }
  409. code, err := am.dispatchCallback(client, account, callbackNamespace, callbackValue)
  410. if err != nil {
  411. am.Unregister(casefoldedAccount, true)
  412. return &registrationCallbackError{underlying: err}
  413. } else {
  414. if client != nil && code != "" {
  415. am.server.logger.Info("accounts",
  416. fmt.Sprintf("nickname %s registered account %s, pending verification", client.Nick(), account))
  417. }
  418. return am.server.store.Update(func(tx *buntdb.Tx) error {
  419. _, _, err = tx.Set(verificationCodeKey, code, setOptions)
  420. return err
  421. })
  422. }
  423. }
  424. type registrationCallbackError struct {
  425. underlying error
  426. }
  427. func (r *registrationCallbackError) Error() string {
  428. return `Account verification could not be sent`
  429. }
  430. func registrationCallbackErrorText(config *Config, client *Client, err error) string {
  431. if callbackErr, ok := err.(*registrationCallbackError); ok {
  432. // only expose a user-visible error if we are doing direct sending
  433. if config.Accounts.Registration.EmailVerification.DirectSendingEnabled() {
  434. errorText := ircutils.SanitizeText(callbackErr.underlying.Error(), 350)
  435. return fmt.Sprintf(client.t("Could not dispatch registration e-mail: %s"), errorText)
  436. } else {
  437. return client.t("Could not dispatch registration e-mail")
  438. }
  439. } else {
  440. return ""
  441. }
  442. }
  443. // ValidatePassphrase checks whether a passphrase is allowed by our rules
  444. func ValidatePassphrase(passphrase string) error {
  445. // sanity check the length
  446. if len(passphrase) == 0 || len(passphrase) > 300 {
  447. return errAccountBadPassphrase
  448. }
  449. // we use * as a placeholder in some places, if it's gotten this far then fail
  450. if passphrase == "*" {
  451. return errAccountBadPassphrase
  452. }
  453. // validate that the passphrase contains no spaces, and furthermore is valid as a
  454. // non-final IRC parameter. we already checked that it is nonempty:
  455. if passphrase[0] == ':' {
  456. return errAccountBadPassphrase
  457. }
  458. for _, r := range passphrase {
  459. if unicode.IsSpace(r) {
  460. return errAccountBadPassphrase
  461. }
  462. }
  463. return nil
  464. }
  465. // changes the password for an account
  466. func (am *AccountManager) setPassword(accountName string, password string, hasPrivs bool) (err error) {
  467. cfAccount, err := CasefoldName(accountName)
  468. if err != nil {
  469. return errAccountDoesNotExist
  470. }
  471. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  472. var credStr string
  473. am.server.store.View(func(tx *buntdb.Tx) error {
  474. // no need to check verification status here or below;
  475. // you either need to be auth'ed to the account or be an oper to do this
  476. credStr, err = tx.Get(credKey)
  477. return nil
  478. })
  479. if err != nil {
  480. return errAccountDoesNotExist
  481. }
  482. var creds AccountCredentials
  483. err = json.Unmarshal([]byte(credStr), &creds)
  484. if err != nil {
  485. return err
  486. }
  487. if !hasPrivs && creds.Empty() {
  488. return errCredsExternallyManaged
  489. }
  490. err = creds.SetPassphrase(password, am.server.Config().Accounts.Registration.BcryptCost)
  491. if err != nil {
  492. return err
  493. }
  494. if creds.Empty() && !hasPrivs {
  495. return errEmptyCredentials
  496. }
  497. newCredStr, err := creds.Serialize()
  498. if err != nil {
  499. return err
  500. }
  501. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  502. curCredStr, err := tx.Get(credKey)
  503. if credStr != curCredStr {
  504. return errCASFailed
  505. }
  506. _, _, err = tx.Set(credKey, newCredStr, nil)
  507. return err
  508. })
  509. return err
  510. }
  511. type alwaysOnChannelStatus struct {
  512. Modes string
  513. JoinTime int64
  514. }
  515. func (am *AccountManager) saveChannels(account string, channelToModes map[string]alwaysOnChannelStatus) {
  516. j, err := json.Marshal(channelToModes)
  517. if err != nil {
  518. am.server.logger.Error("internal", "couldn't marshal channel-to-modes", account, err.Error())
  519. return
  520. }
  521. jStr := string(j)
  522. key := fmt.Sprintf(keyAccountChannelToModes, account)
  523. am.server.store.Update(func(tx *buntdb.Tx) error {
  524. tx.Set(key, jStr, nil)
  525. return nil
  526. })
  527. }
  528. func (am *AccountManager) loadChannels(account string) (channelToModes map[string]alwaysOnChannelStatus) {
  529. key := fmt.Sprintf(keyAccountChannelToModes, account)
  530. var channelsStr string
  531. am.server.store.View(func(tx *buntdb.Tx) error {
  532. channelsStr, _ = tx.Get(key)
  533. return nil
  534. })
  535. if channelsStr == "" {
  536. return nil
  537. }
  538. err := json.Unmarshal([]byte(channelsStr), &channelToModes)
  539. if err != nil {
  540. am.server.logger.Error("internal", "couldn't marshal channel-to-modes", account, err.Error())
  541. return nil
  542. }
  543. return
  544. }
  545. func (am *AccountManager) saveModes(account string, uModes modes.Modes) {
  546. modeStr := uModes.String()
  547. key := fmt.Sprintf(keyAccountModes, account)
  548. am.server.store.Update(func(tx *buntdb.Tx) error {
  549. tx.Set(key, modeStr, nil)
  550. return nil
  551. })
  552. }
  553. func (am *AccountManager) loadModes(account string) (uModes modes.Modes) {
  554. key := fmt.Sprintf(keyAccountModes, account)
  555. var modeStr string
  556. am.server.store.View(func(tx *buntdb.Tx) error {
  557. modeStr, _ = tx.Get(key)
  558. return nil
  559. })
  560. for _, m := range modeStr {
  561. uModes = append(uModes, modes.Mode(m))
  562. }
  563. return
  564. }
  565. func (am *AccountManager) saveLastSeen(account string, lastSeen map[string]time.Time) {
  566. key := fmt.Sprintf(keyAccountLastSeen, account)
  567. am.saveTimeMap(account, key, lastSeen)
  568. }
  569. func (am *AccountManager) saveReadMarkers(account string, readMarkers map[string]time.Time) {
  570. key := fmt.Sprintf(keyAccountReadMarkers, account)
  571. am.saveTimeMap(account, key, readMarkers)
  572. }
  573. func (am *AccountManager) saveTimeMap(account, key string, timeMap map[string]time.Time) {
  574. var val string
  575. if len(timeMap) != 0 {
  576. text, _ := json.Marshal(timeMap)
  577. val = string(text)
  578. }
  579. err := am.server.store.Update(func(tx *buntdb.Tx) error {
  580. if val != "" {
  581. tx.Set(key, val, nil)
  582. } else {
  583. tx.Delete(key)
  584. }
  585. return nil
  586. })
  587. if err != nil {
  588. am.server.logger.Error("internal", "error persisting timeMap", key, err.Error())
  589. }
  590. }
  591. func (am *AccountManager) loadLastSeen(account string) (lastSeen map[string]time.Time) {
  592. key := fmt.Sprintf(keyAccountLastSeen, account)
  593. var lsText string
  594. am.server.store.Update(func(tx *buntdb.Tx) error {
  595. lsText, _ = tx.Get(key)
  596. return nil
  597. })
  598. if lsText == "" {
  599. return nil
  600. }
  601. err := json.Unmarshal([]byte(lsText), &lastSeen)
  602. if err != nil {
  603. return nil
  604. }
  605. return
  606. }
  607. func (am *AccountManager) saveRealname(account string, realname string) {
  608. key := fmt.Sprintf(keyAccountRealname, account)
  609. am.server.store.Update(func(tx *buntdb.Tx) error {
  610. if realname != "" {
  611. tx.Set(key, realname, nil)
  612. } else {
  613. tx.Delete(key)
  614. }
  615. return nil
  616. })
  617. }
  618. func (am *AccountManager) loadRealname(account string) (realname string) {
  619. key := fmt.Sprintf(keyAccountRealname, account)
  620. am.server.store.Update(func(tx *buntdb.Tx) error {
  621. realname, _ = tx.Get(key)
  622. return nil
  623. })
  624. return
  625. }
  626. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  627. certfp, err = utils.NormalizeCertfp(certfp)
  628. if err != nil {
  629. return err
  630. }
  631. cfAccount, err := CasefoldName(account)
  632. if err != nil {
  633. return errAccountDoesNotExist
  634. }
  635. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  636. var credStr string
  637. am.server.store.View(func(tx *buntdb.Tx) error {
  638. credStr, err = tx.Get(credKey)
  639. return nil
  640. })
  641. if err != nil {
  642. return errAccountDoesNotExist
  643. }
  644. var creds AccountCredentials
  645. err = json.Unmarshal([]byte(credStr), &creds)
  646. if err != nil {
  647. return err
  648. }
  649. if !hasPrivs && creds.Empty() {
  650. return errCredsExternallyManaged
  651. }
  652. if add {
  653. err = creds.AddCertfp(certfp)
  654. } else {
  655. err = creds.RemoveCertfp(certfp)
  656. }
  657. if err != nil {
  658. return err
  659. }
  660. if creds.Empty() && !hasPrivs {
  661. return errEmptyCredentials
  662. }
  663. newCredStr, err := creds.Serialize()
  664. if err != nil {
  665. return err
  666. }
  667. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  668. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  669. curCredStr, err := tx.Get(credKey)
  670. if credStr != curCredStr {
  671. return errCASFailed
  672. }
  673. if add {
  674. _, err = tx.Get(certfpKey)
  675. if err != buntdb.ErrNotFound {
  676. return errCertfpAlreadyExists
  677. }
  678. tx.Set(certfpKey, cfAccount, nil)
  679. } else {
  680. tx.Delete(certfpKey)
  681. }
  682. _, _, err = tx.Set(credKey, newCredStr, nil)
  683. return err
  684. })
  685. return err
  686. }
  687. func (am *AccountManager) dispatchCallback(client *Client, account string, callbackNamespace string, callbackValue string) (string, error) {
  688. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  689. return "", nil
  690. } else if callbackNamespace == "mailto" {
  691. return am.dispatchMailtoCallback(client, account, callbackValue)
  692. } else {
  693. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  694. }
  695. }
  696. func (am *AccountManager) dispatchMailtoCallback(client *Client, account string, callbackValue string) (code string, err error) {
  697. config := am.server.Config().Accounts.Registration.EmailVerification
  698. code = utils.GenerateSecretToken()
  699. subject := config.VerifyMessageSubject
  700. if subject == "" {
  701. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  702. }
  703. message := email.ComposeMail(config, callbackValue, subject)
  704. fmt.Fprintf(&message, client.t("Account: %s"), account)
  705. message.WriteString("\r\n")
  706. fmt.Fprintf(&message, client.t("Verification code: %s"), code)
  707. message.WriteString("\r\n")
  708. message.WriteString("\r\n")
  709. message.WriteString(client.t("To verify your account, issue the following command:"))
  710. message.WriteString("\r\n")
  711. fmt.Fprintf(&message, "/MSG NickServ VERIFY %s %s\r\n", account, code)
  712. err = email.SendMail(config, callbackValue, message.Bytes())
  713. if err != nil {
  714. am.server.logger.Error("internal", "Failed to dispatch e-mail to", callbackValue, err.Error())
  715. }
  716. return
  717. }
  718. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  719. casefoldedAccount, err := CasefoldName(account)
  720. var skeleton string
  721. if err != nil || account == "" || account == "*" {
  722. return errAccountVerificationFailed
  723. }
  724. if client != nil && client.Account() != "" {
  725. return errAccountAlreadyLoggedIn
  726. }
  727. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  728. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  729. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  730. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  731. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  732. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  733. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  734. var raw rawClientAccount
  735. func() {
  736. am.serialCacheUpdateMutex.Lock()
  737. defer am.serialCacheUpdateMutex.Unlock()
  738. // do a final check for confusability (in case someone already verified
  739. // a confusable identifier):
  740. var unfoldedName string
  741. err = am.server.store.View(func(tx *buntdb.Tx) error {
  742. unfoldedName, err = tx.Get(accountNameKey)
  743. return err
  744. })
  745. if err != nil {
  746. err = errAccountDoesNotExist
  747. return
  748. }
  749. skeleton, err = Skeleton(unfoldedName)
  750. if err != nil {
  751. err = errAccountDoesNotExist
  752. return
  753. }
  754. err = func() error {
  755. am.RLock()
  756. defer am.RUnlock()
  757. if _, ok := am.skeletonToAccount[skeleton]; ok {
  758. return errConfusableIdentifier
  759. }
  760. return nil
  761. }()
  762. if err != nil {
  763. return
  764. }
  765. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  766. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  767. if err == errAccountDoesNotExist {
  768. return errAccountDoesNotExist
  769. } else if err != nil {
  770. return errAccountVerificationFailed
  771. } else if raw.Verified {
  772. return errAccountAlreadyVerified
  773. }
  774. // actually verify the code
  775. // a stored code of "" means a none callback / no code required
  776. success := false
  777. storedCode, err := tx.Get(verificationCodeKey)
  778. if err == nil {
  779. // this is probably unnecessary
  780. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  781. success = true
  782. }
  783. }
  784. if !success {
  785. return errAccountVerificationInvalidCode
  786. }
  787. // verify the account
  788. tx.Set(verifiedKey, "1", nil)
  789. // don't need the code anymore
  790. tx.Delete(verificationCodeKey)
  791. // re-set all other keys, removing the TTL
  792. tx.Set(accountKey, "1", nil)
  793. tx.Set(accountNameKey, raw.Name, nil)
  794. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  795. tx.Set(credentialsKey, raw.Credentials, nil)
  796. tx.Set(settingsKey, raw.Settings, nil)
  797. var creds AccountCredentials
  798. // XXX we shouldn't do (de)serialization inside the txn,
  799. // but this is like 2 usec on my system
  800. json.Unmarshal([]byte(raw.Credentials), &creds)
  801. for _, cert := range creds.Certfps {
  802. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  803. tx.Set(certFPKey, casefoldedAccount, nil)
  804. }
  805. return nil
  806. })
  807. if err == nil {
  808. am.Lock()
  809. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  810. am.skeletonToAccount[skeleton] = casefoldedAccount
  811. am.Unlock()
  812. }
  813. }()
  814. if err != nil {
  815. return err
  816. }
  817. nick := "[server admin]"
  818. if client != nil {
  819. nick = client.Nick()
  820. }
  821. am.server.logger.Info("accounts", "client", nick, "registered account", account)
  822. raw.Verified = true
  823. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  824. if err != nil {
  825. return err
  826. }
  827. if client != nil {
  828. am.Login(client, clientAccount)
  829. if client.AlwaysOn() {
  830. client.markDirty(IncludeRealname)
  831. }
  832. }
  833. // we may need to do nick enforcement here:
  834. _, method := am.EnforcementStatus(casefoldedAccount, skeleton)
  835. if method == NickEnforcementStrict {
  836. currentClient := am.server.clients.Get(casefoldedAccount)
  837. if currentClient != nil && currentClient != client && currentClient.Account() != casefoldedAccount {
  838. am.server.RandomlyRename(currentClient)
  839. }
  840. }
  841. return nil
  842. }
  843. // register and verify an account, for internal use
  844. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  845. err = am.Register(nil, account, "admin", "", passphrase, "")
  846. if err == nil {
  847. err = am.Verify(nil, account, "")
  848. }
  849. return
  850. }
  851. type EmailChangeRecord struct {
  852. TimeCreated time.Time
  853. Code string
  854. Email string
  855. }
  856. func (am *AccountManager) NsSetEmail(client *Client, emailAddr string) (err error) {
  857. casefoldedAccount := client.Account()
  858. if casefoldedAccount == "" {
  859. return errAccountNotLoggedIn
  860. }
  861. if am.touchRegisterThrottle() {
  862. am.server.logger.Warning("accounts", "global registration throttle exceeded by client changing email", client.Nick())
  863. return errLimitExceeded
  864. }
  865. config := am.server.Config()
  866. if !config.Accounts.Registration.EmailVerification.Enabled {
  867. return errFeatureDisabled // redundant check, just in case
  868. }
  869. record := EmailChangeRecord{
  870. TimeCreated: time.Now().UTC(),
  871. Code: utils.GenerateSecretToken(),
  872. Email: emailAddr,
  873. }
  874. recordKey := fmt.Sprintf(keyAccountEmailChange, casefoldedAccount)
  875. recordBytes, _ := json.Marshal(record)
  876. recordVal := string(recordBytes)
  877. am.server.store.Update(func(tx *buntdb.Tx) error {
  878. tx.Set(recordKey, recordVal, nil)
  879. return nil
  880. })
  881. if err != nil {
  882. return err
  883. }
  884. message := email.ComposeMail(config.Accounts.Registration.EmailVerification,
  885. emailAddr,
  886. fmt.Sprintf(client.t("Verify your change of e-mail address on %s"), am.server.name))
  887. message.WriteString(fmt.Sprintf(client.t("To confirm your change of e-mail address on %s, issue the following command:"), am.server.name))
  888. message.WriteString("\r\n")
  889. fmt.Fprintf(&message, "/MSG NickServ VERIFYEMAIL %s\r\n", record.Code)
  890. err = email.SendMail(config.Accounts.Registration.EmailVerification, emailAddr, message.Bytes())
  891. if err == nil {
  892. am.server.logger.Info("services",
  893. fmt.Sprintf("email change verification sent for account %s", casefoldedAccount))
  894. return
  895. } else {
  896. am.server.logger.Error("internal", "Failed to dispatch e-mail change verification to", emailAddr, err.Error())
  897. return &registrationCallbackError{err}
  898. }
  899. }
  900. func (am *AccountManager) NsVerifyEmail(client *Client, code string) (err error) {
  901. casefoldedAccount := client.Account()
  902. if casefoldedAccount == "" {
  903. return errAccountNotLoggedIn
  904. }
  905. var record EmailChangeRecord
  906. success := false
  907. key := fmt.Sprintf(keyAccountEmailChange, casefoldedAccount)
  908. ttl := time.Duration(am.server.Config().Accounts.Registration.VerifyTimeout)
  909. am.server.store.Update(func(tx *buntdb.Tx) error {
  910. rawStr, err := tx.Get(key)
  911. if err == nil && rawStr != "" {
  912. err := json.Unmarshal([]byte(rawStr), &record)
  913. if err == nil {
  914. if (ttl == 0 || time.Since(record.TimeCreated) < ttl) && utils.SecretTokensMatch(record.Code, code) {
  915. success = true
  916. tx.Delete(key)
  917. }
  918. }
  919. }
  920. return nil
  921. })
  922. if !success {
  923. return errAccountVerificationInvalidCode
  924. }
  925. munger := func(in AccountSettings) (out AccountSettings, err error) {
  926. out = in
  927. out.Email = record.Email
  928. return
  929. }
  930. _, err = am.ModifyAccountSettings(casefoldedAccount, munger)
  931. return
  932. }
  933. func (am *AccountManager) NsSendpass(client *Client, accountName string) (err error) {
  934. config := am.server.Config()
  935. if !(config.Accounts.Registration.EmailVerification.Enabled && config.Accounts.Registration.EmailVerification.PasswordReset.Enabled) {
  936. return errFeatureDisabled
  937. }
  938. account, err := am.LoadAccount(accountName)
  939. if err != nil {
  940. return err
  941. }
  942. if !account.Verified {
  943. return errAccountUnverified
  944. }
  945. if account.Suspended != nil {
  946. return errAccountSuspended
  947. }
  948. if account.Settings.Email == "" {
  949. return errValidEmailRequired
  950. }
  951. record := PasswordResetRecord{
  952. TimeCreated: time.Now().UTC(),
  953. Code: utils.GenerateSecretToken(),
  954. }
  955. recordKey := fmt.Sprintf(keyAccountPwReset, account.NameCasefolded)
  956. recordBytes, _ := json.Marshal(record)
  957. recordVal := string(recordBytes)
  958. am.server.store.Update(func(tx *buntdb.Tx) error {
  959. recStr, recErr := tx.Get(recordKey)
  960. if recErr == nil && recStr != "" {
  961. var existing PasswordResetRecord
  962. jErr := json.Unmarshal([]byte(recStr), &existing)
  963. cooldown := time.Duration(config.Accounts.Registration.EmailVerification.PasswordReset.Cooldown)
  964. if jErr == nil && time.Since(existing.TimeCreated) < cooldown {
  965. err = errLimitExceeded
  966. return nil
  967. }
  968. }
  969. tx.Set(recordKey, recordVal, &buntdb.SetOptions{
  970. Expires: true,
  971. TTL: time.Duration(config.Accounts.Registration.EmailVerification.PasswordReset.Timeout),
  972. })
  973. return nil
  974. })
  975. if err != nil {
  976. return
  977. }
  978. subject := fmt.Sprintf(client.t("Reset your password on %s"), am.server.name)
  979. message := email.ComposeMail(config.Accounts.Registration.EmailVerification, account.Settings.Email, subject)
  980. fmt.Fprintf(&message, client.t("We received a request to reset your password on %[1]s for account: %[2]s"), am.server.name, account.Name)
  981. message.WriteString("\r\n")
  982. fmt.Fprintf(&message, client.t("If you did not initiate this request, you can safely ignore this message."))
  983. message.WriteString("\r\n")
  984. message.WriteString("\r\n")
  985. message.WriteString(client.t("Otherwise, to reset your password, issue the following command (replace `new_password` with your desired password):"))
  986. message.WriteString("\r\n")
  987. fmt.Fprintf(&message, "/MSG NickServ RESETPASS %s %s new_password\r\n", account.Name, record.Code)
  988. err = email.SendMail(config.Accounts.Registration.EmailVerification, account.Settings.Email, message.Bytes())
  989. if err == nil {
  990. am.server.logger.Info("services",
  991. fmt.Sprintf("client %s sent a password reset email for account %s", client.Nick(), account.Name))
  992. } else {
  993. am.server.logger.Error("internal", "Failed to dispatch e-mail to", account.Settings.Email, err.Error())
  994. }
  995. return
  996. }
  997. func (am *AccountManager) NsResetpass(client *Client, accountName, code, password string) (err error) {
  998. if ValidatePassphrase(password) != nil {
  999. return errAccountBadPassphrase
  1000. }
  1001. account, err := am.LoadAccount(accountName)
  1002. if err != nil {
  1003. return
  1004. }
  1005. if !account.Verified {
  1006. return errAccountUnverified
  1007. }
  1008. if account.Suspended != nil {
  1009. return errAccountSuspended
  1010. }
  1011. success := false
  1012. key := fmt.Sprintf(keyAccountPwReset, account.NameCasefolded)
  1013. am.server.store.Update(func(tx *buntdb.Tx) error {
  1014. rawStr, err := tx.Get(key)
  1015. if err == nil && rawStr != "" {
  1016. var record PasswordResetRecord
  1017. err := json.Unmarshal([]byte(rawStr), &record)
  1018. if err == nil && utils.SecretTokensMatch(record.Code, code) {
  1019. success = true
  1020. tx.Delete(key)
  1021. }
  1022. }
  1023. return nil
  1024. })
  1025. if success {
  1026. return am.setPassword(accountName, password, true)
  1027. } else {
  1028. return errAccountInvalidCredentials
  1029. }
  1030. }
  1031. type PasswordResetRecord struct {
  1032. TimeCreated time.Time
  1033. Code string
  1034. }
  1035. func marshalReservedNicks(nicks []string) string {
  1036. return strings.Join(nicks, ",")
  1037. }
  1038. func unmarshalReservedNicks(nicks string) (result []string) {
  1039. if nicks == "" {
  1040. return
  1041. }
  1042. return strings.Split(nicks, ",")
  1043. }
  1044. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  1045. cfnick, err := CasefoldName(nick)
  1046. skeleton, skerr := Skeleton(nick)
  1047. // garbage nick, or garbage options, or disabled
  1048. nrconfig := am.server.Config().Accounts.NickReservation
  1049. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  1050. return errAccountNickReservationFailed
  1051. }
  1052. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  1053. am.serialCacheUpdateMutex.Lock()
  1054. defer am.serialCacheUpdateMutex.Unlock()
  1055. // find the affected account, which is usually the client's:
  1056. account := client.Account()
  1057. if saUnreserve {
  1058. // unless this is a sadrop:
  1059. account := func() string {
  1060. am.RLock()
  1061. defer am.RUnlock()
  1062. return am.nickToAccount[cfnick]
  1063. }()
  1064. if account == "" {
  1065. // nothing to do
  1066. return nil
  1067. }
  1068. }
  1069. if account == "" {
  1070. return errAccountNotLoggedIn
  1071. }
  1072. am.Lock()
  1073. accountForNick := am.nickToAccount[cfnick]
  1074. var accountForSkeleton string
  1075. if reserve {
  1076. accountForSkeleton = am.skeletonToAccount[skeleton]
  1077. }
  1078. am.Unlock()
  1079. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  1080. return errNicknameReserved
  1081. } else if !reserve && !saUnreserve && accountForNick != account {
  1082. return errNicknameReserved
  1083. } else if !reserve && cfnick == account {
  1084. return errAccountCantDropPrimaryNick
  1085. }
  1086. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  1087. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  1088. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1089. if reserve {
  1090. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  1091. // however you shouldn't be able to reserve a nick out from under them
  1092. _, err := tx.Get(unverifiedAccountKey)
  1093. if err == nil {
  1094. return errNicknameReserved
  1095. }
  1096. }
  1097. rawNicks, err := tx.Get(nicksKey)
  1098. if err != nil && err != buntdb.ErrNotFound {
  1099. return err
  1100. }
  1101. nicks := unmarshalReservedNicks(rawNicks)
  1102. if reserve {
  1103. if len(nicks) >= nrconfig.AdditionalNickLimit {
  1104. return errAccountTooManyNicks
  1105. }
  1106. nicks = append(nicks, nick)
  1107. } else {
  1108. // compute (original reserved nicks) minus cfnick
  1109. var newNicks []string
  1110. for _, reservedNick := range nicks {
  1111. cfreservednick, _ := CasefoldName(reservedNick)
  1112. if cfreservednick != cfnick {
  1113. newNicks = append(newNicks, reservedNick)
  1114. } else {
  1115. // found the original, unfolded version of the nick we're dropping;
  1116. // recompute the true skeleton from it
  1117. skeleton, _ = Skeleton(reservedNick)
  1118. }
  1119. }
  1120. nicks = newNicks
  1121. }
  1122. marshaledNicks := marshalReservedNicks(nicks)
  1123. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  1124. return err
  1125. })
  1126. if err == errAccountTooManyNicks || err == errNicknameReserved {
  1127. return err
  1128. } else if err != nil {
  1129. return errAccountNickReservationFailed
  1130. }
  1131. // success
  1132. am.Lock()
  1133. defer am.Unlock()
  1134. if reserve {
  1135. am.nickToAccount[cfnick] = account
  1136. am.skeletonToAccount[skeleton] = account
  1137. } else {
  1138. delete(am.nickToAccount, cfnick)
  1139. delete(am.skeletonToAccount, skeleton)
  1140. }
  1141. return nil
  1142. }
  1143. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  1144. account, err = am.LoadAccount(accountName)
  1145. // #1476: if grouped nicks are allowed, attempt to interpret accountName as a grouped nick
  1146. if err == errAccountDoesNotExist && !am.server.Config().Accounts.NickReservation.ForceNickEqualsAccount {
  1147. cfnick, cfErr := CasefoldName(accountName)
  1148. if cfErr != nil {
  1149. return
  1150. }
  1151. accountName = func() string {
  1152. am.RLock()
  1153. defer am.RUnlock()
  1154. return am.nickToAccount[cfnick]
  1155. }()
  1156. if accountName != "" {
  1157. account, err = am.LoadAccount(accountName)
  1158. }
  1159. }
  1160. if err != nil {
  1161. return
  1162. }
  1163. if !account.Verified {
  1164. err = errAccountUnverified
  1165. return
  1166. } else if account.Suspended != nil {
  1167. err = errAccountSuspended
  1168. return
  1169. }
  1170. switch account.Credentials.Version {
  1171. case 0:
  1172. err = am.checkLegacyPassphrase(migrations.CheckOragonoPassphraseV0, accountName, account.Credentials.PassphraseHash, passphrase)
  1173. case 1:
  1174. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  1175. err = errAccountInvalidCredentials
  1176. }
  1177. if err == nil && account.Credentials.SCRAMCreds.Iters == 0 {
  1178. // XXX: if the account was created prior to 2.8, it doesn't have SCRAM credentials;
  1179. // since we temporarily have access to a valid plaintext password, create them:
  1180. am.rehashPassword(account.Name, passphrase)
  1181. }
  1182. case -1:
  1183. err = am.checkLegacyPassphrase(migrations.CheckAthemePassphrase, accountName, account.Credentials.PassphraseHash, passphrase)
  1184. case -2:
  1185. err = am.checkLegacyPassphrase(migrations.CheckAnopePassphrase, accountName, account.Credentials.PassphraseHash, passphrase)
  1186. default:
  1187. err = errAccountInvalidCredentials
  1188. }
  1189. return
  1190. }
  1191. func (am *AccountManager) checkLegacyPassphrase(check migrations.PassphraseCheck, account string, hash []byte, passphrase string) (err error) {
  1192. err = check(hash, []byte(passphrase))
  1193. if err != nil {
  1194. if err == migrations.ErrHashInvalid {
  1195. am.server.logger.Error("internal", "invalid legacy credentials for account", account)
  1196. }
  1197. return errAccountInvalidCredentials
  1198. }
  1199. // re-hash the passphrase with the latest algorithm
  1200. am.rehashPassword(account, passphrase)
  1201. return nil
  1202. }
  1203. func (am *AccountManager) rehashPassword(accountName, passphrase string) {
  1204. err := am.setPassword(accountName, passphrase, true)
  1205. if err != nil {
  1206. am.server.logger.Error("internal", "could not upgrade user password", accountName, err.Error())
  1207. }
  1208. }
  1209. func (am *AccountManager) loadWithAutocreation(accountName string, autocreate bool) (account ClientAccount, err error) {
  1210. account, err = am.LoadAccount(accountName)
  1211. if err == errAccountDoesNotExist && autocreate {
  1212. err = am.SARegister(accountName, "")
  1213. if err != nil {
  1214. return
  1215. }
  1216. account, err = am.LoadAccount(accountName)
  1217. }
  1218. return
  1219. }
  1220. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  1221. // XXX check this now, so we don't allow a redundant login for an always-on client
  1222. // even for a brief period. the other potential source of nick-account conflicts
  1223. // is from force-nick-equals-account, but those will be caught later by
  1224. // fixupNickEqualsAccount and if there is a conflict, they will be logged out.
  1225. if client.registered {
  1226. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  1227. return errNickAccountMismatch
  1228. }
  1229. }
  1230. if throttled, remainingTime := client.checkLoginThrottle(); throttled {
  1231. return &ThrottleError{remainingTime}
  1232. }
  1233. var account ClientAccount
  1234. defer func() {
  1235. if err == nil {
  1236. am.Login(client, account)
  1237. }
  1238. }()
  1239. config := am.server.Config()
  1240. if config.Accounts.AuthScript.Enabled {
  1241. var output AuthScriptOutput
  1242. output, err = CheckAuthScript(am.server.semaphores.AuthScript, config.Accounts.AuthScript.ScriptConfig,
  1243. AuthScriptInput{AccountName: accountName, Passphrase: passphrase, IP: client.IP().String()})
  1244. if err != nil {
  1245. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  1246. } else if output.Success {
  1247. if output.AccountName != "" {
  1248. accountName = output.AccountName
  1249. }
  1250. account, err = am.loadWithAutocreation(accountName, config.Accounts.AuthScript.Autocreate)
  1251. return
  1252. }
  1253. }
  1254. account, err = am.checkPassphrase(accountName, passphrase)
  1255. return err
  1256. }
  1257. // AllNicks returns the uncasefolded nicknames for all accounts, including additional (grouped) nicks.
  1258. func (am *AccountManager) AllNicks() (result []string) {
  1259. accountNamePrefix := fmt.Sprintf(keyAccountName, "")
  1260. accountAdditionalNicksPrefix := fmt.Sprintf(keyAccountAdditionalNicks, "")
  1261. am.server.store.View(func(tx *buntdb.Tx) error {
  1262. // Account names
  1263. err := tx.AscendGreaterOrEqual("", accountNamePrefix, func(key, value string) bool {
  1264. if !strings.HasPrefix(key, accountNamePrefix) {
  1265. return false
  1266. }
  1267. result = append(result, value)
  1268. return true
  1269. })
  1270. if err != nil {
  1271. return err
  1272. }
  1273. // Additional nicks
  1274. return tx.AscendGreaterOrEqual("", accountAdditionalNicksPrefix, func(key, value string) bool {
  1275. if !strings.HasPrefix(key, accountAdditionalNicksPrefix) {
  1276. return false
  1277. }
  1278. additionalNicks := unmarshalReservedNicks(value)
  1279. for _, additionalNick := range additionalNicks {
  1280. result = append(result, additionalNick)
  1281. }
  1282. return true
  1283. })
  1284. })
  1285. sort.Strings(result)
  1286. return
  1287. }
  1288. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  1289. casefoldedAccount, err := CasefoldName(accountName)
  1290. if err != nil {
  1291. err = errAccountDoesNotExist
  1292. return
  1293. }
  1294. var raw rawClientAccount
  1295. am.server.store.View(func(tx *buntdb.Tx) error {
  1296. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  1297. return nil
  1298. })
  1299. if err != nil {
  1300. return
  1301. }
  1302. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  1303. return
  1304. }
  1305. // look up the unfolded version of an account name, possibly after deletion
  1306. func (am *AccountManager) AccountToAccountName(account string) (result string) {
  1307. casefoldedAccount, err := CasefoldName(account)
  1308. if err != nil {
  1309. return
  1310. }
  1311. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1312. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1313. am.server.store.View(func(tx *buntdb.Tx) error {
  1314. if name, err := tx.Get(accountNameKey); err == nil {
  1315. result = name
  1316. return nil
  1317. }
  1318. if name, err := tx.Get(unregisteredKey); err == nil {
  1319. result = name
  1320. }
  1321. return nil
  1322. })
  1323. return
  1324. }
  1325. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  1326. result.Name = raw.Name
  1327. result.NameCasefolded = cfName
  1328. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  1329. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  1330. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  1331. if e != nil {
  1332. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  1333. err = errAccountDoesNotExist
  1334. return
  1335. }
  1336. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  1337. result.Verified = raw.Verified
  1338. if raw.VHost != "" {
  1339. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  1340. if e != nil {
  1341. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  1342. // pretend they have no vhost and move on
  1343. }
  1344. }
  1345. if raw.Settings != "" {
  1346. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  1347. if e != nil {
  1348. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  1349. }
  1350. }
  1351. if raw.Suspended != "" {
  1352. sus := new(AccountSuspension)
  1353. e := json.Unmarshal([]byte(raw.Suspended), sus)
  1354. if e != nil {
  1355. am.server.logger.Error("internal", "corrupt suspension data", result.Name, e.Error())
  1356. } else {
  1357. result.Suspended = sus
  1358. }
  1359. }
  1360. return
  1361. }
  1362. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  1363. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1364. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1365. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1366. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1367. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1368. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1369. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1370. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1371. suspendedKey := fmt.Sprintf(keyAccountSuspended, casefoldedAccount)
  1372. _, e := tx.Get(accountKey)
  1373. if e == buntdb.ErrNotFound {
  1374. err = errAccountDoesNotExist
  1375. return
  1376. }
  1377. result.Name, _ = tx.Get(accountNameKey)
  1378. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  1379. result.Credentials, _ = tx.Get(credentialsKey)
  1380. result.AdditionalNicks, _ = tx.Get(nicksKey)
  1381. result.VHost, _ = tx.Get(vhostKey)
  1382. result.Settings, _ = tx.Get(settingsKey)
  1383. result.Suspended, _ = tx.Get(suspendedKey)
  1384. if _, e = tx.Get(verifiedKey); e == nil {
  1385. result.Verified = true
  1386. }
  1387. return
  1388. }
  1389. type AccountSuspension struct {
  1390. AccountName string `json:"AccountName,omitempty"`
  1391. TimeCreated time.Time
  1392. Duration time.Duration
  1393. OperName string
  1394. Reason string
  1395. }
  1396. func (am *AccountManager) Suspend(accountName string, duration time.Duration, operName, reason string) (err error) {
  1397. account, err := CasefoldName(accountName)
  1398. if err != nil {
  1399. return errAccountDoesNotExist
  1400. }
  1401. suspension := AccountSuspension{
  1402. TimeCreated: time.Now().UTC(),
  1403. Duration: duration,
  1404. OperName: operName,
  1405. Reason: reason,
  1406. }
  1407. suspensionStr, err := json.Marshal(suspension)
  1408. if err != nil {
  1409. am.server.logger.Error("internal", "suspension json unserializable", err.Error())
  1410. return errAccountDoesNotExist
  1411. }
  1412. existsKey := fmt.Sprintf(keyAccountExists, account)
  1413. suspensionKey := fmt.Sprintf(keyAccountSuspended, account)
  1414. var setOptions *buntdb.SetOptions
  1415. if duration != time.Duration(0) {
  1416. setOptions = &buntdb.SetOptions{Expires: true, TTL: duration}
  1417. }
  1418. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1419. _, err := tx.Get(existsKey)
  1420. if err != nil {
  1421. return errAccountDoesNotExist
  1422. }
  1423. _, _, err = tx.Set(suspensionKey, string(suspensionStr), setOptions)
  1424. return err
  1425. })
  1426. if err == errAccountDoesNotExist {
  1427. return err
  1428. } else if err != nil {
  1429. am.server.logger.Error("internal", "couldn't persist suspension", account, err.Error())
  1430. } // keep going
  1431. am.Lock()
  1432. clients := am.accountToClients[account]
  1433. delete(am.accountToClients, account)
  1434. am.Unlock()
  1435. // kill clients, sending them the reason
  1436. suspension.AccountName = accountName
  1437. for _, client := range clients {
  1438. client.Logout()
  1439. client.Quit(suspensionToString(client, suspension), nil)
  1440. client.destroy(nil)
  1441. }
  1442. return nil
  1443. }
  1444. func (am *AccountManager) killClients(clients []*Client) {
  1445. for _, client := range clients {
  1446. client.Logout()
  1447. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1448. client.destroy(nil)
  1449. }
  1450. }
  1451. func (am *AccountManager) Unsuspend(accountName string) (err error) {
  1452. cfaccount, err := CasefoldName(accountName)
  1453. if err != nil {
  1454. return errAccountDoesNotExist
  1455. }
  1456. existsKey := fmt.Sprintf(keyAccountExists, cfaccount)
  1457. suspensionKey := fmt.Sprintf(keyAccountSuspended, cfaccount)
  1458. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1459. _, err := tx.Get(existsKey)
  1460. if err != nil {
  1461. return errAccountDoesNotExist
  1462. }
  1463. _, err = tx.Delete(suspensionKey)
  1464. if err != nil {
  1465. return errNoop
  1466. }
  1467. return nil
  1468. })
  1469. return err
  1470. }
  1471. func (am *AccountManager) ListSuspended() (result []AccountSuspension) {
  1472. var names []string
  1473. var raw []string
  1474. prefix := fmt.Sprintf(keyAccountSuspended, "")
  1475. am.server.store.View(func(tx *buntdb.Tx) error {
  1476. err := tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  1477. if !strings.HasPrefix(key, prefix) {
  1478. return false
  1479. }
  1480. raw = append(raw, value)
  1481. cfname := strings.TrimPrefix(key, prefix)
  1482. name, _ := tx.Get(fmt.Sprintf(keyAccountName, cfname))
  1483. names = append(names, name)
  1484. return true
  1485. })
  1486. return err
  1487. })
  1488. result = make([]AccountSuspension, 0, len(raw))
  1489. for i := 0; i < len(raw); i++ {
  1490. var sus AccountSuspension
  1491. err := json.Unmarshal([]byte(raw[i]), &sus)
  1492. if err != nil {
  1493. am.server.logger.Error("internal", "corrupt data for suspension", names[i], err.Error())
  1494. continue
  1495. }
  1496. sus.AccountName = names[i]
  1497. result = append(result, sus)
  1498. }
  1499. return
  1500. }
  1501. // renames an account (within very restrictive limits); see #1380
  1502. func (am *AccountManager) Rename(oldName, newName string) (err error) {
  1503. accountData, err := am.LoadAccount(oldName)
  1504. if err != nil {
  1505. return
  1506. }
  1507. newCfName, err := CasefoldName(newName)
  1508. if err != nil {
  1509. return errNicknameInvalid
  1510. }
  1511. if newCfName != accountData.NameCasefolded {
  1512. return errInvalidAccountRename
  1513. }
  1514. key := fmt.Sprintf(keyAccountName, accountData.NameCasefolded)
  1515. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1516. tx.Set(key, newName, nil)
  1517. return nil
  1518. })
  1519. if err != nil {
  1520. return err
  1521. }
  1522. am.RLock()
  1523. defer am.RUnlock()
  1524. for _, client := range am.accountToClients[accountData.NameCasefolded] {
  1525. client.setAccountName(newName)
  1526. }
  1527. return nil
  1528. }
  1529. func (am *AccountManager) Unregister(account string, erase bool) error {
  1530. config := am.server.Config()
  1531. casefoldedAccount, err := CasefoldName(account)
  1532. if err != nil {
  1533. return errAccountDoesNotExist
  1534. }
  1535. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1536. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1537. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1538. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1539. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  1540. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1541. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1542. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1543. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1544. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1545. joinedChannelsKey := fmt.Sprintf(keyAccountChannelToModes, casefoldedAccount)
  1546. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1547. readMarkersKey := fmt.Sprintf(keyAccountReadMarkers, casefoldedAccount)
  1548. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1549. modesKey := fmt.Sprintf(keyAccountModes, casefoldedAccount)
  1550. realnameKey := fmt.Sprintf(keyAccountRealname, casefoldedAccount)
  1551. suspendedKey := fmt.Sprintf(keyAccountSuspended, casefoldedAccount)
  1552. pwResetKey := fmt.Sprintf(keyAccountPwReset, casefoldedAccount)
  1553. emailChangeKey := fmt.Sprintf(keyAccountEmailChange, casefoldedAccount)
  1554. var clients []*Client
  1555. defer func() {
  1556. am.killClients(clients)
  1557. }()
  1558. var registeredChannels []string
  1559. // on our way out, unregister all the account's channels and delete them from the db
  1560. defer func() {
  1561. for _, channelName := range registeredChannels {
  1562. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1563. if err != nil {
  1564. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1565. }
  1566. }
  1567. }()
  1568. var credText string
  1569. var rawNicks string
  1570. am.serialCacheUpdateMutex.Lock()
  1571. defer am.serialCacheUpdateMutex.Unlock()
  1572. var accountName string
  1573. var channelsStr string
  1574. keepProtections := false
  1575. am.server.store.Update(func(tx *buntdb.Tx) error {
  1576. // get the unfolded account name; for an active account, this is
  1577. // stored under accountNameKey, for an unregistered account under unregisteredKey
  1578. accountName, _ = tx.Get(accountNameKey)
  1579. if accountName == "" {
  1580. accountName, _ = tx.Get(unregisteredKey)
  1581. }
  1582. if erase {
  1583. tx.Delete(unregisteredKey)
  1584. } else {
  1585. if _, err := tx.Get(verifiedKey); err == nil {
  1586. tx.Set(unregisteredKey, accountName, nil)
  1587. keepProtections = true
  1588. }
  1589. }
  1590. tx.Delete(accountKey)
  1591. tx.Delete(accountNameKey)
  1592. tx.Delete(verifiedKey)
  1593. tx.Delete(registeredTimeKey)
  1594. tx.Delete(verificationCodeKey)
  1595. tx.Delete(settingsKey)
  1596. rawNicks, _ = tx.Get(nicksKey)
  1597. tx.Delete(nicksKey)
  1598. credText, err = tx.Get(credentialsKey)
  1599. tx.Delete(credentialsKey)
  1600. tx.Delete(vhostKey)
  1601. channelsStr, _ = tx.Get(channelsKey)
  1602. tx.Delete(channelsKey)
  1603. tx.Delete(joinedChannelsKey)
  1604. tx.Delete(lastSeenKey)
  1605. tx.Delete(readMarkersKey)
  1606. tx.Delete(modesKey)
  1607. tx.Delete(realnameKey)
  1608. tx.Delete(suspendedKey)
  1609. tx.Delete(pwResetKey)
  1610. tx.Delete(emailChangeKey)
  1611. return nil
  1612. })
  1613. if err == nil {
  1614. var creds AccountCredentials
  1615. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1616. for _, cert := range creds.Certfps {
  1617. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1618. am.server.store.Update(func(tx *buntdb.Tx) error {
  1619. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1620. tx.Delete(certFPKey)
  1621. }
  1622. return nil
  1623. })
  1624. }
  1625. }
  1626. }
  1627. skeleton, _ := Skeleton(accountName)
  1628. additionalNicks := unmarshalReservedNicks(rawNicks)
  1629. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1630. am.Lock()
  1631. defer am.Unlock()
  1632. clients = am.accountToClients[casefoldedAccount]
  1633. delete(am.accountToClients, casefoldedAccount)
  1634. // protect the account name itself where applicable, but not any grouped nicks
  1635. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1636. delete(am.nickToAccount, casefoldedAccount)
  1637. delete(am.skeletonToAccount, skeleton)
  1638. }
  1639. for _, nick := range additionalNicks {
  1640. delete(am.nickToAccount, nick)
  1641. additionalSkel, _ := Skeleton(nick)
  1642. delete(am.skeletonToAccount, additionalSkel)
  1643. }
  1644. if err != nil && !erase {
  1645. return errAccountDoesNotExist
  1646. }
  1647. return nil
  1648. }
  1649. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1650. if channelsStr != "" {
  1651. result = strings.Split(channelsStr, ",")
  1652. }
  1653. return
  1654. }
  1655. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1656. cfaccount, err := CasefoldName(account)
  1657. if err != nil {
  1658. return
  1659. }
  1660. var channelStr string
  1661. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1662. am.server.store.View(func(tx *buntdb.Tx) error {
  1663. channelStr, _ = tx.Get(key)
  1664. return nil
  1665. })
  1666. return unmarshalRegisteredChannels(channelStr)
  1667. }
  1668. func (am *AccountManager) AuthenticateByCertificate(client *Client, certfp string, peerCerts []*x509.Certificate, authzid string) (err error) {
  1669. if certfp == "" {
  1670. return errAccountInvalidCredentials
  1671. }
  1672. var clientAccount ClientAccount
  1673. defer func() {
  1674. if err != nil {
  1675. return
  1676. } else if !clientAccount.Verified {
  1677. err = errAccountUnverified
  1678. return
  1679. } else if clientAccount.Suspended != nil {
  1680. err = errAccountSuspended
  1681. return
  1682. }
  1683. // TODO(#1109) clean this check up?
  1684. if client.registered {
  1685. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1686. err = errNickAccountMismatch
  1687. return
  1688. }
  1689. }
  1690. am.Login(client, clientAccount)
  1691. return
  1692. }()
  1693. config := am.server.Config()
  1694. if config.Accounts.AuthScript.Enabled {
  1695. var output AuthScriptOutput
  1696. output, err = CheckAuthScript(am.server.semaphores.AuthScript, config.Accounts.AuthScript.ScriptConfig,
  1697. AuthScriptInput{Certfp: certfp, IP: client.IP().String(), peerCerts: peerCerts})
  1698. if err != nil {
  1699. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  1700. } else if output.Success && output.AccountName != "" {
  1701. clientAccount, err = am.loadWithAutocreation(output.AccountName, config.Accounts.AuthScript.Autocreate)
  1702. return
  1703. }
  1704. }
  1705. var account string
  1706. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1707. err = am.server.store.View(func(tx *buntdb.Tx) error {
  1708. account, _ = tx.Get(certFPKey)
  1709. if account == "" {
  1710. return errAccountInvalidCredentials
  1711. }
  1712. return nil
  1713. })
  1714. if err != nil {
  1715. return err
  1716. }
  1717. if authzid != "" && authzid != account {
  1718. return errAuthzidAuthcidMismatch
  1719. }
  1720. // ok, we found an account corresponding to their certificate
  1721. clientAccount, err = am.LoadAccount(account)
  1722. return err
  1723. }
  1724. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1725. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1726. casefoldedAccount, err := CasefoldName(account)
  1727. if err != nil {
  1728. return newSettings, errAccountDoesNotExist
  1729. }
  1730. // TODO implement this in general via a compare-and-swap API
  1731. accountData, err := am.LoadAccount(casefoldedAccount)
  1732. if err != nil {
  1733. return
  1734. } else if !accountData.Verified {
  1735. return newSettings, errAccountUnverified
  1736. }
  1737. newSettings, err = munger(accountData.Settings)
  1738. if err != nil {
  1739. return
  1740. }
  1741. text, err := json.Marshal(newSettings)
  1742. if err != nil {
  1743. return
  1744. }
  1745. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1746. serializedValue := string(text)
  1747. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1748. _, _, err = tx.Set(key, serializedValue, nil)
  1749. return
  1750. })
  1751. if err != nil {
  1752. err = errAccountUpdateFailed
  1753. return
  1754. }
  1755. // success, push new settings into the client objects
  1756. am.Lock()
  1757. defer am.Unlock()
  1758. for _, client := range am.accountToClients[casefoldedAccount] {
  1759. client.SetAccountSettings(newSettings)
  1760. }
  1761. return
  1762. }
  1763. // represents someone's status in hostserv
  1764. type VHostInfo struct {
  1765. ApprovedVHost string
  1766. Enabled bool
  1767. }
  1768. // callback type implementing the actual business logic of vhost operations
  1769. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1770. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1771. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1772. output = input
  1773. output.Enabled = true
  1774. output.ApprovedVHost = vhost
  1775. return
  1776. }
  1777. return am.performVHostChange(account, munger)
  1778. }
  1779. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1780. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1781. if input.ApprovedVHost == "" {
  1782. err = errNoVhost
  1783. return
  1784. }
  1785. output = input
  1786. output.Enabled = enabled
  1787. return
  1788. }
  1789. return am.performVHostChange(client.Account(), munger)
  1790. }
  1791. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1792. account, err = CasefoldName(account)
  1793. if err != nil || account == "" {
  1794. err = errAccountDoesNotExist
  1795. return
  1796. }
  1797. if am.server.Defcon() <= 3 {
  1798. err = errFeatureDisabled
  1799. return
  1800. }
  1801. clientAccount, err := am.LoadAccount(account)
  1802. if err != nil {
  1803. err = errAccountDoesNotExist
  1804. return
  1805. } else if !clientAccount.Verified {
  1806. err = errAccountUnverified
  1807. return
  1808. }
  1809. result, err = munger(clientAccount.VHost)
  1810. if err != nil {
  1811. return
  1812. }
  1813. vhtext, err := json.Marshal(result)
  1814. if err != nil {
  1815. err = errAccountUpdateFailed
  1816. return
  1817. }
  1818. vhstr := string(vhtext)
  1819. key := fmt.Sprintf(keyAccountVHost, account)
  1820. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1821. _, _, err := tx.Set(key, vhstr, nil)
  1822. return err
  1823. })
  1824. if err != nil {
  1825. err = errAccountUpdateFailed
  1826. return
  1827. }
  1828. am.applyVhostToClients(account, result)
  1829. return result, nil
  1830. }
  1831. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1832. // if hostserv is disabled in config, then don't grant vhosts
  1833. // that were previously approved while it was enabled
  1834. if !am.server.Config().Accounts.VHosts.Enabled {
  1835. return
  1836. }
  1837. vhost := ""
  1838. if info.Enabled {
  1839. vhost = info.ApprovedVHost
  1840. }
  1841. oldNickmask := client.NickMaskString()
  1842. updated := client.SetVHost(vhost)
  1843. if updated && client.Registered() {
  1844. // TODO: doing I/O here is kind of a kludge
  1845. client.sendChghost(oldNickmask, client.Hostname())
  1846. }
  1847. }
  1848. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1849. am.RLock()
  1850. clients := am.accountToClients[account]
  1851. am.RUnlock()
  1852. for _, client := range clients {
  1853. am.applyVHostInfo(client, result)
  1854. }
  1855. }
  1856. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1857. client.Login(account)
  1858. am.applyVHostInfo(client, account.VHost)
  1859. casefoldedAccount := client.Account()
  1860. am.Lock()
  1861. defer am.Unlock()
  1862. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1863. }
  1864. func (am *AccountManager) Logout(client *Client) {
  1865. am.Lock()
  1866. defer am.Unlock()
  1867. casefoldedAccount := client.Account()
  1868. if casefoldedAccount == "" {
  1869. return
  1870. }
  1871. client.Logout()
  1872. clients := am.accountToClients[casefoldedAccount]
  1873. if len(clients) <= 1 {
  1874. delete(am.accountToClients, casefoldedAccount)
  1875. return
  1876. }
  1877. remainingClients := make([]*Client, len(clients)-1)
  1878. remainingPos := 0
  1879. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1880. if clients[currentPos] != client {
  1881. remainingClients[remainingPos] = clients[currentPos]
  1882. remainingPos++
  1883. }
  1884. }
  1885. am.accountToClients[casefoldedAccount] = remainingClients
  1886. }
  1887. var (
  1888. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1889. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1890. EnabledSaslMechanisms = map[string]func(*Server, *Client, *Session, []byte, *ResponseBuffer) bool{
  1891. "PLAIN": authPlainHandler,
  1892. "EXTERNAL": authExternalHandler,
  1893. "SCRAM-SHA-256": authScramHandler,
  1894. }
  1895. )
  1896. type CredentialsVersion int
  1897. const (
  1898. CredentialsLegacy CredentialsVersion = 0
  1899. CredentialsSHA3Bcrypt CredentialsVersion = 1
  1900. // negative numbers for migration
  1901. CredentialsAtheme = -1
  1902. CredentialsAnope = -2
  1903. )
  1904. type SCRAMCreds struct {
  1905. Salt []byte
  1906. Iters int
  1907. StoredKey []byte
  1908. ServerKey []byte
  1909. }
  1910. // AccountCredentials stores the various methods for verifying accounts.
  1911. type AccountCredentials struct {
  1912. Version CredentialsVersion
  1913. PassphraseHash []byte
  1914. Certfps []string
  1915. SCRAMCreds
  1916. }
  1917. func (ac *AccountCredentials) Empty() bool {
  1918. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1919. }
  1920. // helper to assemble the serialized JSON for an account's credentials
  1921. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1922. ac.Version = 1
  1923. credText, err := json.Marshal(*ac)
  1924. if err != nil {
  1925. return "", err
  1926. }
  1927. return string(credText), nil
  1928. }
  1929. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1930. if passphrase == "" {
  1931. ac.PassphraseHash = nil
  1932. ac.SCRAMCreds = SCRAMCreds{}
  1933. return nil
  1934. }
  1935. if ValidatePassphrase(passphrase) != nil {
  1936. return errAccountBadPassphrase
  1937. }
  1938. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1939. if err != nil {
  1940. return errAccountBadPassphrase
  1941. }
  1942. // we can pass an empty account name because it won't actually be incorporated
  1943. // into the credentials; it's just a quirk of the xdg-go/scram API that the way
  1944. // to produce server credentials is to call NewClient* and then GetStoredCredentials
  1945. scramClient, err := scram.SHA256.NewClientUnprepped("", passphrase, "")
  1946. if err != nil {
  1947. return errAccountBadPassphrase
  1948. }
  1949. salt := make([]byte, 16)
  1950. rand.Read(salt)
  1951. // xdg-go/scram says: "Clients have a default minimum PBKDF2 iteration count of 4096."
  1952. minIters := 4096
  1953. scramCreds := scramClient.GetStoredCredentials(scram.KeyFactors{Salt: string(salt), Iters: minIters})
  1954. ac.SCRAMCreds = SCRAMCreds{
  1955. Salt: salt,
  1956. Iters: minIters,
  1957. StoredKey: scramCreds.StoredKey,
  1958. ServerKey: scramCreds.ServerKey,
  1959. }
  1960. return nil
  1961. }
  1962. func (am *AccountManager) NewScramConversation() *scram.ServerConversation {
  1963. server, _ := scram.SHA256.NewServer(am.lookupSCRAMCreds)
  1964. return server.NewConversation()
  1965. }
  1966. func (am *AccountManager) lookupSCRAMCreds(accountName string) (creds scram.StoredCredentials, err error) {
  1967. // strip client ID if present:
  1968. if strudelIndex := strings.IndexByte(accountName, '@'); strudelIndex != -1 {
  1969. accountName = accountName[:strudelIndex]
  1970. }
  1971. acct, err := am.LoadAccount(accountName)
  1972. if err != nil {
  1973. return
  1974. }
  1975. if acct.Credentials.SCRAMCreds.Iters == 0 {
  1976. err = errNoSCRAMCredentials
  1977. return
  1978. }
  1979. creds.Salt = string(acct.Credentials.SCRAMCreds.Salt)
  1980. creds.Iters = acct.Credentials.SCRAMCreds.Iters
  1981. creds.StoredKey = acct.Credentials.SCRAMCreds.StoredKey
  1982. creds.ServerKey = acct.Credentials.SCRAMCreds.ServerKey
  1983. return
  1984. }
  1985. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1986. // XXX we require that certfp is already normalized (rather than normalize here
  1987. // and pass back the normalized version as an additional return parameter);
  1988. // this is just a final sanity check:
  1989. if len(certfp) != 64 {
  1990. return utils.ErrInvalidCertfp
  1991. }
  1992. for _, current := range ac.Certfps {
  1993. if certfp == current {
  1994. return errNoop
  1995. }
  1996. }
  1997. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1998. return errLimitExceeded
  1999. }
  2000. ac.Certfps = append(ac.Certfps, certfp)
  2001. return nil
  2002. }
  2003. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  2004. found := false
  2005. newList := make([]string, 0, len(ac.Certfps))
  2006. for _, current := range ac.Certfps {
  2007. if current == certfp {
  2008. found = true
  2009. } else {
  2010. newList = append(newList, current)
  2011. }
  2012. }
  2013. if !found {
  2014. // this is important because it prevents you from deleting someone else's
  2015. // fingerprint record
  2016. return errNoop
  2017. }
  2018. ac.Certfps = newList
  2019. return nil
  2020. }
  2021. type MulticlientAllowedSetting int
  2022. const (
  2023. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  2024. MulticlientDisallowedByUser
  2025. MulticlientAllowedByUser
  2026. )
  2027. // controls whether/when clients without event-playback support see fake
  2028. // PRIVMSGs for JOINs
  2029. type ReplayJoinsSetting uint
  2030. const (
  2031. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  2032. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  2033. )
  2034. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  2035. switch strings.ToLower(str) {
  2036. case "commands-only":
  2037. result = ReplayJoinsCommandsOnly
  2038. case "always":
  2039. result = ReplayJoinsAlways
  2040. default:
  2041. err = errInvalidParams
  2042. }
  2043. return
  2044. }
  2045. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  2046. // persistent JSON blobs in the database
  2047. type AccountSettings struct {
  2048. AutoreplayLines *int
  2049. NickEnforcement NickEnforcementMethod
  2050. AllowBouncer MulticlientAllowedSetting
  2051. ReplayJoins ReplayJoinsSetting
  2052. AlwaysOn PersistentStatus
  2053. AutoreplayMissed bool
  2054. DMHistory HistoryStatus
  2055. AutoAway PersistentStatus
  2056. Email string
  2057. }
  2058. // ClientAccount represents a user account.
  2059. type ClientAccount struct {
  2060. // Name of the account.
  2061. Name string
  2062. NameCasefolded string
  2063. RegisteredAt time.Time
  2064. Credentials AccountCredentials
  2065. Verified bool
  2066. Suspended *AccountSuspension
  2067. AdditionalNicks []string
  2068. VHost VHostInfo
  2069. Settings AccountSettings
  2070. }
  2071. // convenience for passing around raw serialized account data
  2072. type rawClientAccount struct {
  2073. Name string
  2074. RegisteredAt string
  2075. Credentials string
  2076. Verified bool
  2077. AdditionalNicks string
  2078. VHost string
  2079. Settings string
  2080. Suspended string
  2081. }