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

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