Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

accounts.go 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  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. // validate that the passphrase contains no spaces, and furthermore is valid as a
  420. // non-final IRC parameter. we already checked that it is nonempty:
  421. if passphrase[0] == ':' {
  422. return errAccountBadPassphrase
  423. }
  424. for _, r := range passphrase {
  425. if unicode.IsSpace(r) {
  426. return errAccountBadPassphrase
  427. }
  428. }
  429. return nil
  430. }
  431. // changes the password for an account
  432. func (am *AccountManager) setPassword(account string, password string, hasPrivs bool) (err error) {
  433. cfAccount, err := CasefoldName(account)
  434. if err != nil {
  435. return errAccountDoesNotExist
  436. }
  437. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  438. var credStr string
  439. am.server.store.View(func(tx *buntdb.Tx) error {
  440. // no need to check verification status here or below;
  441. // you either need to be auth'ed to the account or be an oper to do this
  442. credStr, err = tx.Get(credKey)
  443. return nil
  444. })
  445. if err != nil {
  446. return errAccountDoesNotExist
  447. }
  448. var creds AccountCredentials
  449. err = json.Unmarshal([]byte(credStr), &creds)
  450. if err != nil {
  451. return err
  452. }
  453. if !hasPrivs && creds.Empty() {
  454. return errCredsExternallyManaged
  455. }
  456. err = creds.SetPassphrase(password, am.server.Config().Accounts.Registration.BcryptCost)
  457. if err != nil {
  458. return err
  459. }
  460. if creds.Empty() && !hasPrivs {
  461. return errEmptyCredentials
  462. }
  463. newCredStr, err := creds.Serialize()
  464. if err != nil {
  465. return err
  466. }
  467. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  468. curCredStr, err := tx.Get(credKey)
  469. if credStr != curCredStr {
  470. return errCASFailed
  471. }
  472. _, _, err = tx.Set(credKey, newCredStr, nil)
  473. return err
  474. })
  475. return err
  476. }
  477. type alwaysOnChannelStatus struct {
  478. Modes string
  479. JoinTime int64
  480. }
  481. func (am *AccountManager) saveChannels(account string, channelToModes map[string]alwaysOnChannelStatus) {
  482. j, err := json.Marshal(channelToModes)
  483. if err != nil {
  484. am.server.logger.Error("internal", "couldn't marshal channel-to-modes", account, err.Error())
  485. return
  486. }
  487. jStr := string(j)
  488. key := fmt.Sprintf(keyAccountChannelToModes, account)
  489. am.server.store.Update(func(tx *buntdb.Tx) error {
  490. tx.Set(key, jStr, nil)
  491. return nil
  492. })
  493. }
  494. func (am *AccountManager) loadChannels(account string) (channelToModes map[string]alwaysOnChannelStatus) {
  495. key := fmt.Sprintf(keyAccountChannelToModes, account)
  496. var channelsStr string
  497. am.server.store.View(func(tx *buntdb.Tx) error {
  498. channelsStr, _ = tx.Get(key)
  499. return nil
  500. })
  501. if channelsStr == "" {
  502. return nil
  503. }
  504. err := json.Unmarshal([]byte(channelsStr), &channelToModes)
  505. if err != nil {
  506. am.server.logger.Error("internal", "couldn't marshal channel-to-modes", account, err.Error())
  507. return nil
  508. }
  509. return
  510. }
  511. func (am *AccountManager) saveModes(account string, uModes modes.Modes) {
  512. modeStr := uModes.String()
  513. key := fmt.Sprintf(keyAccountModes, account)
  514. am.server.store.Update(func(tx *buntdb.Tx) error {
  515. tx.Set(key, modeStr, nil)
  516. return nil
  517. })
  518. }
  519. func (am *AccountManager) loadModes(account string) (uModes modes.Modes) {
  520. key := fmt.Sprintf(keyAccountModes, account)
  521. var modeStr string
  522. am.server.store.View(func(tx *buntdb.Tx) error {
  523. modeStr, _ = tx.Get(key)
  524. return nil
  525. })
  526. for _, m := range modeStr {
  527. uModes = append(uModes, modes.Mode(m))
  528. }
  529. return
  530. }
  531. func (am *AccountManager) saveLastSeen(account string, lastSeen map[string]time.Time) {
  532. key := fmt.Sprintf(keyAccountLastSeen, account)
  533. var val string
  534. if len(lastSeen) != 0 {
  535. text, _ := json.Marshal(lastSeen)
  536. val = string(text)
  537. }
  538. am.server.store.Update(func(tx *buntdb.Tx) error {
  539. if val != "" {
  540. tx.Set(key, val, nil)
  541. } else {
  542. tx.Delete(key)
  543. }
  544. return nil
  545. })
  546. }
  547. func (am *AccountManager) loadLastSeen(account string) (lastSeen map[string]time.Time) {
  548. key := fmt.Sprintf(keyAccountLastSeen, account)
  549. var lsText string
  550. am.server.store.Update(func(tx *buntdb.Tx) error {
  551. lsText, _ = tx.Get(key)
  552. return nil
  553. })
  554. if lsText == "" {
  555. return nil
  556. }
  557. err := json.Unmarshal([]byte(lsText), &lastSeen)
  558. if err != nil {
  559. return nil
  560. }
  561. return
  562. }
  563. func (am *AccountManager) saveRealname(account string, realname string) {
  564. key := fmt.Sprintf(keyAccountRealname, account)
  565. am.server.store.Update(func(tx *buntdb.Tx) error {
  566. if realname != "" {
  567. tx.Set(key, realname, nil)
  568. } else {
  569. tx.Delete(key)
  570. }
  571. return nil
  572. })
  573. }
  574. func (am *AccountManager) loadRealname(account string) (realname string) {
  575. key := fmt.Sprintf(keyAccountRealname, account)
  576. am.server.store.Update(func(tx *buntdb.Tx) error {
  577. realname, _ = tx.Get(key)
  578. return nil
  579. })
  580. return
  581. }
  582. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  583. certfp, err = utils.NormalizeCertfp(certfp)
  584. if err != nil {
  585. return err
  586. }
  587. cfAccount, err := CasefoldName(account)
  588. if err != nil {
  589. return errAccountDoesNotExist
  590. }
  591. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  592. var credStr string
  593. am.server.store.View(func(tx *buntdb.Tx) error {
  594. credStr, err = tx.Get(credKey)
  595. return nil
  596. })
  597. if err != nil {
  598. return errAccountDoesNotExist
  599. }
  600. var creds AccountCredentials
  601. err = json.Unmarshal([]byte(credStr), &creds)
  602. if err != nil {
  603. return err
  604. }
  605. if !hasPrivs && creds.Empty() {
  606. return errCredsExternallyManaged
  607. }
  608. if add {
  609. err = creds.AddCertfp(certfp)
  610. } else {
  611. err = creds.RemoveCertfp(certfp)
  612. }
  613. if err != nil {
  614. return err
  615. }
  616. if creds.Empty() && !hasPrivs {
  617. return errEmptyCredentials
  618. }
  619. newCredStr, err := creds.Serialize()
  620. if err != nil {
  621. return err
  622. }
  623. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  624. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  625. curCredStr, err := tx.Get(credKey)
  626. if credStr != curCredStr {
  627. return errCASFailed
  628. }
  629. if add {
  630. _, err = tx.Get(certfpKey)
  631. if err != buntdb.ErrNotFound {
  632. return errCertfpAlreadyExists
  633. }
  634. tx.Set(certfpKey, cfAccount, nil)
  635. } else {
  636. tx.Delete(certfpKey)
  637. }
  638. _, _, err = tx.Set(credKey, newCredStr, nil)
  639. return err
  640. })
  641. return err
  642. }
  643. func (am *AccountManager) dispatchCallback(client *Client, account string, callbackNamespace string, callbackValue string) (string, error) {
  644. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  645. return "", nil
  646. } else if callbackNamespace == "mailto" {
  647. return am.dispatchMailtoCallback(client, account, callbackValue)
  648. } else {
  649. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  650. }
  651. }
  652. func (am *AccountManager) dispatchMailtoCallback(client *Client, account string, callbackValue string) (code string, err error) {
  653. config := am.server.Config().Accounts.Registration.EmailVerification
  654. code = utils.GenerateSecretToken()
  655. subject := config.VerifyMessageSubject
  656. if subject == "" {
  657. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  658. }
  659. var message bytes.Buffer
  660. fmt.Fprintf(&message, "From: %s\r\n", config.Sender)
  661. fmt.Fprintf(&message, "To: %s\r\n", callbackValue)
  662. if config.DKIM.Domain != "" {
  663. fmt.Fprintf(&message, "Message-ID: <%s@%s>\r\n", utils.GenerateSecretKey(), config.DKIM.Domain)
  664. }
  665. fmt.Fprintf(&message, "Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
  666. fmt.Fprintf(&message, "Subject: %s\r\n", subject)
  667. message.WriteString("\r\n") // blank line: end headers, begin message body
  668. fmt.Fprintf(&message, client.t("Account: %s"), account)
  669. message.WriteString("\r\n")
  670. fmt.Fprintf(&message, client.t("Verification code: %s"), code)
  671. message.WriteString("\r\n")
  672. message.WriteString("\r\n")
  673. message.WriteString(client.t("To verify your account, issue the following command:"))
  674. message.WriteString("\r\n")
  675. fmt.Fprintf(&message, "/MSG NickServ VERIFY %s %s\r\n", account, code)
  676. err = email.SendMail(config, callbackValue, message.Bytes())
  677. if err != nil {
  678. am.server.logger.Error("internal", "Failed to dispatch e-mail to", callbackValue, err.Error())
  679. }
  680. return
  681. }
  682. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  683. casefoldedAccount, err := CasefoldName(account)
  684. var skeleton string
  685. if err != nil || account == "" || account == "*" {
  686. return errAccountVerificationFailed
  687. }
  688. if client != nil && client.Account() != "" {
  689. return errAccountAlreadyLoggedIn
  690. }
  691. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  692. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  693. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  694. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  695. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  696. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  697. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  698. var raw rawClientAccount
  699. func() {
  700. am.serialCacheUpdateMutex.Lock()
  701. defer am.serialCacheUpdateMutex.Unlock()
  702. // do a final check for confusability (in case someone already verified
  703. // a confusable identifier):
  704. var unfoldedName string
  705. err = am.server.store.View(func(tx *buntdb.Tx) error {
  706. unfoldedName, err = tx.Get(accountNameKey)
  707. return err
  708. })
  709. if err != nil {
  710. err = errAccountDoesNotExist
  711. return
  712. }
  713. skeleton, err = Skeleton(unfoldedName)
  714. if err != nil {
  715. err = errAccountDoesNotExist
  716. return
  717. }
  718. err = func() error {
  719. am.RLock()
  720. defer am.RUnlock()
  721. if _, ok := am.skeletonToAccount[skeleton]; ok {
  722. return errConfusableIdentifier
  723. }
  724. return nil
  725. }()
  726. if err != nil {
  727. return
  728. }
  729. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  730. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  731. if err == errAccountDoesNotExist {
  732. return errAccountDoesNotExist
  733. } else if err != nil {
  734. return errAccountVerificationFailed
  735. } else if raw.Verified {
  736. return errAccountAlreadyVerified
  737. }
  738. // actually verify the code
  739. // a stored code of "" means a none callback / no code required
  740. success := false
  741. storedCode, err := tx.Get(verificationCodeKey)
  742. if err == nil {
  743. // this is probably unnecessary
  744. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  745. success = true
  746. }
  747. }
  748. if !success {
  749. return errAccountVerificationInvalidCode
  750. }
  751. // verify the account
  752. tx.Set(verifiedKey, "1", nil)
  753. // don't need the code anymore
  754. tx.Delete(verificationCodeKey)
  755. // re-set all other keys, removing the TTL
  756. tx.Set(accountKey, "1", nil)
  757. tx.Set(accountNameKey, raw.Name, nil)
  758. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  759. tx.Set(callbackKey, raw.Callback, nil)
  760. tx.Set(credentialsKey, raw.Credentials, nil)
  761. var creds AccountCredentials
  762. // XXX we shouldn't do (de)serialization inside the txn,
  763. // but this is like 2 usec on my system
  764. json.Unmarshal([]byte(raw.Credentials), &creds)
  765. for _, cert := range creds.Certfps {
  766. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  767. tx.Set(certFPKey, casefoldedAccount, nil)
  768. }
  769. return nil
  770. })
  771. if err == nil {
  772. am.Lock()
  773. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  774. am.skeletonToAccount[skeleton] = casefoldedAccount
  775. am.Unlock()
  776. }
  777. }()
  778. if err != nil {
  779. return err
  780. }
  781. nick := "[server admin]"
  782. if client != nil {
  783. nick = client.Nick()
  784. }
  785. am.server.logger.Info("accounts", "client", nick, "registered account", account)
  786. raw.Verified = true
  787. clientAccount, err := am.deserializeRawAccount(raw, casefoldedAccount)
  788. if err != nil {
  789. return err
  790. }
  791. if client != nil {
  792. am.Login(client, clientAccount)
  793. if client.AlwaysOn() {
  794. client.markDirty(IncludeRealname)
  795. }
  796. }
  797. // we may need to do nick enforcement here:
  798. _, method := am.EnforcementStatus(casefoldedAccount, skeleton)
  799. if method == NickEnforcementStrict {
  800. currentClient := am.server.clients.Get(casefoldedAccount)
  801. if currentClient != nil && currentClient != client && currentClient.Account() != casefoldedAccount {
  802. am.server.RandomlyRename(currentClient)
  803. }
  804. }
  805. return nil
  806. }
  807. // register and verify an account, for internal use
  808. func (am *AccountManager) SARegister(account, passphrase string) (err error) {
  809. err = am.Register(nil, account, "admin", "", passphrase, "")
  810. if err == nil {
  811. err = am.Verify(nil, account, "")
  812. }
  813. return
  814. }
  815. func marshalReservedNicks(nicks []string) string {
  816. return strings.Join(nicks, ",")
  817. }
  818. func unmarshalReservedNicks(nicks string) (result []string) {
  819. if nicks == "" {
  820. return
  821. }
  822. return strings.Split(nicks, ",")
  823. }
  824. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  825. cfnick, err := CasefoldName(nick)
  826. skeleton, skerr := Skeleton(nick)
  827. // garbage nick, or garbage options, or disabled
  828. nrconfig := am.server.Config().Accounts.NickReservation
  829. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  830. return errAccountNickReservationFailed
  831. }
  832. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  833. am.serialCacheUpdateMutex.Lock()
  834. defer am.serialCacheUpdateMutex.Unlock()
  835. // find the affected account, which is usually the client's:
  836. account := client.Account()
  837. if saUnreserve {
  838. // unless this is a sadrop:
  839. account := func() string {
  840. am.RLock()
  841. defer am.RUnlock()
  842. return am.nickToAccount[cfnick]
  843. }()
  844. if account == "" {
  845. // nothing to do
  846. return nil
  847. }
  848. }
  849. if account == "" {
  850. return errAccountNotLoggedIn
  851. }
  852. am.Lock()
  853. accountForNick := am.nickToAccount[cfnick]
  854. var accountForSkeleton string
  855. if reserve {
  856. accountForSkeleton = am.skeletonToAccount[skeleton]
  857. }
  858. am.Unlock()
  859. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  860. return errNicknameReserved
  861. } else if !reserve && !saUnreserve && accountForNick != account {
  862. return errNicknameReserved
  863. } else if !reserve && cfnick == account {
  864. return errAccountCantDropPrimaryNick
  865. }
  866. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  867. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  868. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  869. if reserve {
  870. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  871. // however you shouldn't be able to reserve a nick out from under them
  872. _, err := tx.Get(unverifiedAccountKey)
  873. if err == nil {
  874. return errNicknameReserved
  875. }
  876. }
  877. rawNicks, err := tx.Get(nicksKey)
  878. if err != nil && err != buntdb.ErrNotFound {
  879. return err
  880. }
  881. nicks := unmarshalReservedNicks(rawNicks)
  882. if reserve {
  883. if len(nicks) >= nrconfig.AdditionalNickLimit {
  884. return errAccountTooManyNicks
  885. }
  886. nicks = append(nicks, nick)
  887. } else {
  888. // compute (original reserved nicks) minus cfnick
  889. var newNicks []string
  890. for _, reservedNick := range nicks {
  891. cfreservednick, _ := CasefoldName(reservedNick)
  892. if cfreservednick != cfnick {
  893. newNicks = append(newNicks, reservedNick)
  894. } else {
  895. // found the original, unfolded version of the nick we're dropping;
  896. // recompute the true skeleton from it
  897. skeleton, _ = Skeleton(reservedNick)
  898. }
  899. }
  900. nicks = newNicks
  901. }
  902. marshaledNicks := marshalReservedNicks(nicks)
  903. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  904. return err
  905. })
  906. if err == errAccountTooManyNicks || err == errNicknameReserved {
  907. return err
  908. } else if err != nil {
  909. return errAccountNickReservationFailed
  910. }
  911. // success
  912. am.Lock()
  913. defer am.Unlock()
  914. if reserve {
  915. am.nickToAccount[cfnick] = account
  916. am.skeletonToAccount[skeleton] = account
  917. } else {
  918. delete(am.nickToAccount, cfnick)
  919. delete(am.skeletonToAccount, skeleton)
  920. }
  921. return nil
  922. }
  923. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  924. account, err = am.LoadAccount(accountName)
  925. // #1476: if grouped nicks are allowed, attempt to interpret accountName as a grouped nick
  926. if err == errAccountDoesNotExist && !am.server.Config().Accounts.NickReservation.ForceNickEqualsAccount {
  927. cfnick, cfErr := CasefoldName(accountName)
  928. if cfErr != nil {
  929. return
  930. }
  931. accountName = func() string {
  932. am.RLock()
  933. defer am.RUnlock()
  934. return am.nickToAccount[cfnick]
  935. }()
  936. if accountName != "" {
  937. account, err = am.LoadAccount(accountName)
  938. }
  939. }
  940. if err != nil {
  941. return
  942. }
  943. if !account.Verified {
  944. err = errAccountUnverified
  945. return
  946. } else if account.Suspended != nil {
  947. err = errAccountSuspended
  948. return
  949. }
  950. switch account.Credentials.Version {
  951. case 0:
  952. err = am.checkLegacyPassphrase(migrations.CheckOragonoPassphraseV0, accountName, account.Credentials.PassphraseHash, passphrase)
  953. case 1:
  954. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  955. err = errAccountInvalidCredentials
  956. }
  957. case -1:
  958. err = am.checkLegacyPassphrase(migrations.CheckAthemePassphrase, accountName, account.Credentials.PassphraseHash, passphrase)
  959. case -2:
  960. err = am.checkLegacyPassphrase(migrations.CheckAnopePassphrase, accountName, account.Credentials.PassphraseHash, passphrase)
  961. default:
  962. err = errAccountInvalidCredentials
  963. }
  964. return
  965. }
  966. func (am *AccountManager) checkLegacyPassphrase(check migrations.PassphraseCheck, account string, hash []byte, passphrase string) (err error) {
  967. err = check(hash, []byte(passphrase))
  968. if err != nil {
  969. if err == migrations.ErrHashInvalid {
  970. am.server.logger.Error("internal", "invalid legacy credentials for account", account)
  971. }
  972. return errAccountInvalidCredentials
  973. }
  974. // re-hash the passphrase with the latest algorithm
  975. err = am.setPassword(account, passphrase, true)
  976. if err != nil {
  977. am.server.logger.Error("internal", "could not upgrade user password", err.Error())
  978. }
  979. return nil
  980. }
  981. func (am *AccountManager) loadWithAutocreation(accountName string, autocreate bool) (account ClientAccount, err error) {
  982. account, err = am.LoadAccount(accountName)
  983. if err == errAccountDoesNotExist && autocreate {
  984. err = am.SARegister(accountName, "")
  985. if err != nil {
  986. return
  987. }
  988. account, err = am.LoadAccount(accountName)
  989. }
  990. return
  991. }
  992. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) (err error) {
  993. // XXX check this now, so we don't allow a redundant login for an always-on client
  994. // even for a brief period. the other potential source of nick-account conflicts
  995. // is from force-nick-equals-account, but those will be caught later by
  996. // fixupNickEqualsAccount and if there is a conflict, they will be logged out.
  997. if client.registered {
  998. if clientAlready := am.server.clients.Get(accountName); clientAlready != nil && clientAlready.AlwaysOn() {
  999. return errNickAccountMismatch
  1000. }
  1001. }
  1002. if throttled, remainingTime := client.checkLoginThrottle(); throttled {
  1003. return &ThrottleError{remainingTime}
  1004. }
  1005. var account ClientAccount
  1006. defer func() {
  1007. if err == nil {
  1008. am.Login(client, account)
  1009. }
  1010. }()
  1011. config := am.server.Config()
  1012. if config.Accounts.AuthScript.Enabled {
  1013. var output AuthScriptOutput
  1014. output, err = CheckAuthScript(am.server.semaphores.AuthScript, config.Accounts.AuthScript.ScriptConfig,
  1015. AuthScriptInput{AccountName: accountName, Passphrase: passphrase, IP: client.IP().String()})
  1016. if err != nil {
  1017. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  1018. } else if output.Success {
  1019. if output.AccountName != "" {
  1020. accountName = output.AccountName
  1021. }
  1022. account, err = am.loadWithAutocreation(accountName, config.Accounts.AuthScript.Autocreate)
  1023. return
  1024. }
  1025. }
  1026. account, err = am.checkPassphrase(accountName, passphrase)
  1027. return err
  1028. }
  1029. // AllNicks returns the uncasefolded nicknames for all accounts, including additional (grouped) nicks.
  1030. func (am *AccountManager) AllNicks() (result []string) {
  1031. accountNamePrefix := fmt.Sprintf(keyAccountName, "")
  1032. accountAdditionalNicksPrefix := fmt.Sprintf(keyAccountAdditionalNicks, "")
  1033. am.server.store.View(func(tx *buntdb.Tx) error {
  1034. // Account names
  1035. err := tx.AscendGreaterOrEqual("", accountNamePrefix, func(key, value string) bool {
  1036. if !strings.HasPrefix(key, accountNamePrefix) {
  1037. return false
  1038. }
  1039. result = append(result, value)
  1040. return true
  1041. })
  1042. if err != nil {
  1043. return err
  1044. }
  1045. // Additional nicks
  1046. return tx.AscendGreaterOrEqual("", accountAdditionalNicksPrefix, func(key, value string) bool {
  1047. if !strings.HasPrefix(key, accountAdditionalNicksPrefix) {
  1048. return false
  1049. }
  1050. additionalNicks := unmarshalReservedNicks(value)
  1051. for _, additionalNick := range additionalNicks {
  1052. result = append(result, additionalNick)
  1053. }
  1054. return true
  1055. })
  1056. })
  1057. sort.Strings(result)
  1058. return
  1059. }
  1060. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  1061. casefoldedAccount, err := CasefoldName(accountName)
  1062. if err != nil {
  1063. err = errAccountDoesNotExist
  1064. return
  1065. }
  1066. var raw rawClientAccount
  1067. am.server.store.View(func(tx *buntdb.Tx) error {
  1068. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  1069. return nil
  1070. })
  1071. if err != nil {
  1072. return
  1073. }
  1074. result, err = am.deserializeRawAccount(raw, casefoldedAccount)
  1075. return
  1076. }
  1077. // look up the unfolded version of an account name, possibly after deletion
  1078. func (am *AccountManager) AccountToAccountName(account string) (result string) {
  1079. casefoldedAccount, err := CasefoldName(account)
  1080. if err != nil {
  1081. return
  1082. }
  1083. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1084. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1085. am.server.store.View(func(tx *buntdb.Tx) error {
  1086. if name, err := tx.Get(accountNameKey); err == nil {
  1087. result = name
  1088. return nil
  1089. }
  1090. if name, err := tx.Get(unregisteredKey); err == nil {
  1091. result = name
  1092. }
  1093. return nil
  1094. })
  1095. return
  1096. }
  1097. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount, cfName string) (result ClientAccount, err error) {
  1098. result.Name = raw.Name
  1099. result.NameCasefolded = cfName
  1100. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  1101. result.RegisteredAt = time.Unix(0, regTimeInt).UTC()
  1102. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  1103. if e != nil {
  1104. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  1105. err = errAccountDoesNotExist
  1106. return
  1107. }
  1108. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  1109. result.Verified = raw.Verified
  1110. if raw.VHost != "" {
  1111. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  1112. if e != nil {
  1113. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  1114. // pretend they have no vhost and move on
  1115. }
  1116. }
  1117. if raw.Settings != "" {
  1118. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  1119. if e != nil {
  1120. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  1121. }
  1122. }
  1123. if raw.Suspended != "" {
  1124. sus := new(AccountSuspension)
  1125. e := json.Unmarshal([]byte(raw.Suspended), sus)
  1126. if e != nil {
  1127. am.server.logger.Error("internal", "corrupt suspension data", result.Name, e.Error())
  1128. } else {
  1129. result.Suspended = sus
  1130. }
  1131. }
  1132. return
  1133. }
  1134. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  1135. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1136. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1137. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1138. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1139. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1140. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1141. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1142. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1143. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1144. suspendedKey := fmt.Sprintf(keyAccountSuspended, casefoldedAccount)
  1145. _, e := tx.Get(accountKey)
  1146. if e == buntdb.ErrNotFound {
  1147. err = errAccountDoesNotExist
  1148. return
  1149. }
  1150. result.Name, _ = tx.Get(accountNameKey)
  1151. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  1152. result.Credentials, _ = tx.Get(credentialsKey)
  1153. result.Callback, _ = tx.Get(callbackKey)
  1154. result.AdditionalNicks, _ = tx.Get(nicksKey)
  1155. result.VHost, _ = tx.Get(vhostKey)
  1156. result.Settings, _ = tx.Get(settingsKey)
  1157. result.Suspended, _ = tx.Get(suspendedKey)
  1158. if _, e = tx.Get(verifiedKey); e == nil {
  1159. result.Verified = true
  1160. }
  1161. return
  1162. }
  1163. type AccountSuspension struct {
  1164. AccountName string `json:"AccountName,omitempty"`
  1165. TimeCreated time.Time
  1166. Duration time.Duration
  1167. OperName string
  1168. Reason string
  1169. }
  1170. func (am *AccountManager) Suspend(accountName string, duration time.Duration, operName, reason string) (err error) {
  1171. account, err := CasefoldName(accountName)
  1172. if err != nil {
  1173. return errAccountDoesNotExist
  1174. }
  1175. suspension := AccountSuspension{
  1176. TimeCreated: time.Now().UTC(),
  1177. Duration: duration,
  1178. OperName: operName,
  1179. Reason: reason,
  1180. }
  1181. suspensionStr, err := json.Marshal(suspension)
  1182. if err != nil {
  1183. am.server.logger.Error("internal", "suspension json unserializable", err.Error())
  1184. return errAccountDoesNotExist
  1185. }
  1186. existsKey := fmt.Sprintf(keyAccountExists, account)
  1187. suspensionKey := fmt.Sprintf(keyAccountSuspended, account)
  1188. var setOptions *buntdb.SetOptions
  1189. if duration != time.Duration(0) {
  1190. setOptions = &buntdb.SetOptions{Expires: true, TTL: duration}
  1191. }
  1192. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1193. _, err := tx.Get(existsKey)
  1194. if err != nil {
  1195. return errAccountDoesNotExist
  1196. }
  1197. _, _, err = tx.Set(suspensionKey, string(suspensionStr), setOptions)
  1198. return err
  1199. })
  1200. if err == errAccountDoesNotExist {
  1201. return err
  1202. } else if err != nil {
  1203. am.server.logger.Error("internal", "couldn't persist suspension", account, err.Error())
  1204. } // keep going
  1205. am.Lock()
  1206. clients := am.accountToClients[account]
  1207. delete(am.accountToClients, account)
  1208. am.Unlock()
  1209. // kill clients, sending them the reason
  1210. suspension.AccountName = accountName
  1211. for _, client := range clients {
  1212. client.Logout()
  1213. client.Quit(suspensionToString(client, suspension), nil)
  1214. client.destroy(nil)
  1215. }
  1216. return nil
  1217. }
  1218. func (am *AccountManager) killClients(clients []*Client) {
  1219. for _, client := range clients {
  1220. client.Logout()
  1221. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  1222. client.destroy(nil)
  1223. }
  1224. }
  1225. func (am *AccountManager) Unsuspend(accountName string) (err error) {
  1226. cfaccount, err := CasefoldName(accountName)
  1227. if err != nil {
  1228. return errAccountDoesNotExist
  1229. }
  1230. existsKey := fmt.Sprintf(keyAccountExists, cfaccount)
  1231. suspensionKey := fmt.Sprintf(keyAccountSuspended, cfaccount)
  1232. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1233. _, err := tx.Get(existsKey)
  1234. if err != nil {
  1235. return errAccountDoesNotExist
  1236. }
  1237. _, err = tx.Delete(suspensionKey)
  1238. if err != nil {
  1239. return errNoop
  1240. }
  1241. return nil
  1242. })
  1243. return err
  1244. }
  1245. func (am *AccountManager) ListSuspended() (result []AccountSuspension) {
  1246. var names []string
  1247. var raw []string
  1248. prefix := fmt.Sprintf(keyAccountSuspended, "")
  1249. am.server.store.View(func(tx *buntdb.Tx) error {
  1250. err := tx.AscendGreaterOrEqual("", prefix, func(key, value string) bool {
  1251. if !strings.HasPrefix(key, prefix) {
  1252. return false
  1253. }
  1254. raw = append(raw, value)
  1255. cfname := strings.TrimPrefix(key, prefix)
  1256. name, _ := tx.Get(fmt.Sprintf(keyAccountName, cfname))
  1257. names = append(names, name)
  1258. return true
  1259. })
  1260. return err
  1261. })
  1262. result = make([]AccountSuspension, 0, len(raw))
  1263. for i := 0; i < len(raw); i++ {
  1264. var sus AccountSuspension
  1265. err := json.Unmarshal([]byte(raw[i]), &sus)
  1266. if err != nil {
  1267. am.server.logger.Error("internal", "corrupt data for suspension", names[i], err.Error())
  1268. continue
  1269. }
  1270. sus.AccountName = names[i]
  1271. result = append(result, sus)
  1272. }
  1273. return
  1274. }
  1275. // renames an account (within very restrictive limits); see #1380
  1276. func (am *AccountManager) Rename(oldName, newName string) (err error) {
  1277. accountData, err := am.LoadAccount(oldName)
  1278. if err != nil {
  1279. return
  1280. }
  1281. newCfName, err := CasefoldName(newName)
  1282. if err != nil {
  1283. return errNicknameInvalid
  1284. }
  1285. if newCfName != accountData.NameCasefolded {
  1286. return errInvalidAccountRename
  1287. }
  1288. key := fmt.Sprintf(keyAccountName, accountData.NameCasefolded)
  1289. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1290. tx.Set(key, newName, nil)
  1291. return nil
  1292. })
  1293. if err != nil {
  1294. return err
  1295. }
  1296. am.RLock()
  1297. defer am.RUnlock()
  1298. for _, client := range am.accountToClients[accountData.NameCasefolded] {
  1299. client.setAccountName(newName)
  1300. }
  1301. return nil
  1302. }
  1303. func (am *AccountManager) Unregister(account string, erase bool) error {
  1304. config := am.server.Config()
  1305. casefoldedAccount, err := CasefoldName(account)
  1306. if err != nil {
  1307. return errAccountDoesNotExist
  1308. }
  1309. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  1310. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  1311. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  1312. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  1313. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  1314. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  1315. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  1316. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  1317. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1318. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  1319. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  1320. joinedChannelsKey := fmt.Sprintf(keyAccountChannelToModes, casefoldedAccount)
  1321. lastSeenKey := fmt.Sprintf(keyAccountLastSeen, casefoldedAccount)
  1322. unregisteredKey := fmt.Sprintf(keyAccountUnregistered, casefoldedAccount)
  1323. modesKey := fmt.Sprintf(keyAccountModes, casefoldedAccount)
  1324. realnameKey := fmt.Sprintf(keyAccountRealname, casefoldedAccount)
  1325. suspendedKey := fmt.Sprintf(keyAccountSuspended, casefoldedAccount)
  1326. var clients []*Client
  1327. defer func() {
  1328. am.killClients(clients)
  1329. }()
  1330. var registeredChannels []string
  1331. // on our way out, unregister all the account's channels and delete them from the db
  1332. defer func() {
  1333. for _, channelName := range registeredChannels {
  1334. err := am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  1335. if err != nil {
  1336. am.server.logger.Error("internal", "couldn't unregister channel", channelName, err.Error())
  1337. }
  1338. }
  1339. }()
  1340. var credText string
  1341. var rawNicks string
  1342. am.serialCacheUpdateMutex.Lock()
  1343. defer am.serialCacheUpdateMutex.Unlock()
  1344. var accountName string
  1345. var channelsStr string
  1346. keepProtections := false
  1347. am.server.store.Update(func(tx *buntdb.Tx) error {
  1348. // get the unfolded account name; for an active account, this is
  1349. // stored under accountNameKey, for an unregistered account under unregisteredKey
  1350. accountName, _ = tx.Get(accountNameKey)
  1351. if accountName == "" {
  1352. accountName, _ = tx.Get(unregisteredKey)
  1353. }
  1354. if erase {
  1355. tx.Delete(unregisteredKey)
  1356. } else {
  1357. if _, err := tx.Get(verifiedKey); err == nil {
  1358. tx.Set(unregisteredKey, accountName, nil)
  1359. keepProtections = true
  1360. }
  1361. }
  1362. tx.Delete(accountKey)
  1363. tx.Delete(accountNameKey)
  1364. tx.Delete(verifiedKey)
  1365. tx.Delete(registeredTimeKey)
  1366. tx.Delete(callbackKey)
  1367. tx.Delete(verificationCodeKey)
  1368. tx.Delete(settingsKey)
  1369. rawNicks, _ = tx.Get(nicksKey)
  1370. tx.Delete(nicksKey)
  1371. credText, err = tx.Get(credentialsKey)
  1372. tx.Delete(credentialsKey)
  1373. tx.Delete(vhostKey)
  1374. channelsStr, _ = tx.Get(channelsKey)
  1375. tx.Delete(channelsKey)
  1376. tx.Delete(joinedChannelsKey)
  1377. tx.Delete(lastSeenKey)
  1378. tx.Delete(modesKey)
  1379. tx.Delete(realnameKey)
  1380. tx.Delete(suspendedKey)
  1381. return nil
  1382. })
  1383. if err == nil {
  1384. var creds AccountCredentials
  1385. if err := json.Unmarshal([]byte(credText), &creds); err == nil {
  1386. for _, cert := range creds.Certfps {
  1387. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  1388. am.server.store.Update(func(tx *buntdb.Tx) error {
  1389. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  1390. tx.Delete(certFPKey)
  1391. }
  1392. return nil
  1393. })
  1394. }
  1395. }
  1396. }
  1397. skeleton, _ := Skeleton(accountName)
  1398. additionalNicks := unmarshalReservedNicks(rawNicks)
  1399. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  1400. am.Lock()
  1401. defer am.Unlock()
  1402. clients = am.accountToClients[casefoldedAccount]
  1403. delete(am.accountToClients, casefoldedAccount)
  1404. // protect the account name itself where applicable, but not any grouped nicks
  1405. if !(keepProtections && config.Accounts.NickReservation.Method == NickEnforcementStrict) {
  1406. delete(am.nickToAccount, casefoldedAccount)
  1407. delete(am.skeletonToAccount, skeleton)
  1408. }
  1409. for _, nick := range additionalNicks {
  1410. delete(am.nickToAccount, nick)
  1411. additionalSkel, _ := Skeleton(nick)
  1412. delete(am.skeletonToAccount, additionalSkel)
  1413. }
  1414. if err != nil && !erase {
  1415. return errAccountDoesNotExist
  1416. }
  1417. return nil
  1418. }
  1419. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  1420. if channelsStr != "" {
  1421. result = strings.Split(channelsStr, ",")
  1422. }
  1423. return
  1424. }
  1425. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  1426. cfaccount, err := CasefoldName(account)
  1427. if err != nil {
  1428. return
  1429. }
  1430. var channelStr string
  1431. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  1432. am.server.store.View(func(tx *buntdb.Tx) error {
  1433. channelStr, _ = tx.Get(key)
  1434. return nil
  1435. })
  1436. return unmarshalRegisteredChannels(channelStr)
  1437. }
  1438. func (am *AccountManager) AuthenticateByCertificate(client *Client, certfp string, peerCerts []*x509.Certificate, authzid string) (err error) {
  1439. if certfp == "" {
  1440. return errAccountInvalidCredentials
  1441. }
  1442. var clientAccount ClientAccount
  1443. defer func() {
  1444. if err != nil {
  1445. return
  1446. } else if !clientAccount.Verified {
  1447. err = errAccountUnverified
  1448. return
  1449. } else if clientAccount.Suspended != nil {
  1450. err = errAccountSuspended
  1451. return
  1452. }
  1453. // TODO(#1109) clean this check up?
  1454. if client.registered {
  1455. if clientAlready := am.server.clients.Get(clientAccount.Name); clientAlready != nil && clientAlready.AlwaysOn() {
  1456. err = errNickAccountMismatch
  1457. return
  1458. }
  1459. }
  1460. am.Login(client, clientAccount)
  1461. return
  1462. }()
  1463. config := am.server.Config()
  1464. if config.Accounts.AuthScript.Enabled {
  1465. var output AuthScriptOutput
  1466. output, err = CheckAuthScript(am.server.semaphores.AuthScript, config.Accounts.AuthScript.ScriptConfig,
  1467. AuthScriptInput{Certfp: certfp, IP: client.IP().String(), peerCerts: peerCerts})
  1468. if err != nil {
  1469. am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
  1470. } else if output.Success && output.AccountName != "" {
  1471. clientAccount, err = am.loadWithAutocreation(output.AccountName, config.Accounts.AuthScript.Autocreate)
  1472. return
  1473. }
  1474. }
  1475. var account string
  1476. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  1477. err = am.server.store.View(func(tx *buntdb.Tx) error {
  1478. account, _ = tx.Get(certFPKey)
  1479. if account == "" {
  1480. return errAccountInvalidCredentials
  1481. }
  1482. return nil
  1483. })
  1484. if err != nil {
  1485. return err
  1486. }
  1487. if authzid != "" && authzid != account {
  1488. return errAuthzidAuthcidMismatch
  1489. }
  1490. // ok, we found an account corresponding to their certificate
  1491. clientAccount, err = am.LoadAccount(account)
  1492. return err
  1493. }
  1494. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  1495. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  1496. casefoldedAccount, err := CasefoldName(account)
  1497. if err != nil {
  1498. return newSettings, errAccountDoesNotExist
  1499. }
  1500. // TODO implement this in general via a compare-and-swap API
  1501. accountData, err := am.LoadAccount(casefoldedAccount)
  1502. if err != nil {
  1503. return
  1504. } else if !accountData.Verified {
  1505. return newSettings, errAccountUnverified
  1506. }
  1507. newSettings, err = munger(accountData.Settings)
  1508. if err != nil {
  1509. return
  1510. }
  1511. text, err := json.Marshal(newSettings)
  1512. if err != nil {
  1513. return
  1514. }
  1515. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  1516. serializedValue := string(text)
  1517. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  1518. _, _, err = tx.Set(key, serializedValue, nil)
  1519. return
  1520. })
  1521. if err != nil {
  1522. err = errAccountUpdateFailed
  1523. return
  1524. }
  1525. // success, push new settings into the client objects
  1526. am.Lock()
  1527. defer am.Unlock()
  1528. for _, client := range am.accountToClients[casefoldedAccount] {
  1529. client.SetAccountSettings(newSettings)
  1530. }
  1531. return
  1532. }
  1533. // represents someone's status in hostserv
  1534. type VHostInfo struct {
  1535. ApprovedVHost string
  1536. Enabled bool
  1537. }
  1538. // callback type implementing the actual business logic of vhost operations
  1539. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  1540. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  1541. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1542. output = input
  1543. output.Enabled = true
  1544. output.ApprovedVHost = vhost
  1545. return
  1546. }
  1547. return am.performVHostChange(account, munger)
  1548. }
  1549. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1550. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1551. if input.ApprovedVHost == "" {
  1552. err = errNoVhost
  1553. return
  1554. }
  1555. output = input
  1556. output.Enabled = enabled
  1557. return
  1558. }
  1559. return am.performVHostChange(client.Account(), munger)
  1560. }
  1561. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1562. account, err = CasefoldName(account)
  1563. if err != nil || account == "" {
  1564. err = errAccountDoesNotExist
  1565. return
  1566. }
  1567. if am.server.Defcon() <= 3 {
  1568. err = errFeatureDisabled
  1569. return
  1570. }
  1571. clientAccount, err := am.LoadAccount(account)
  1572. if err != nil {
  1573. err = errAccountDoesNotExist
  1574. return
  1575. } else if !clientAccount.Verified {
  1576. err = errAccountUnverified
  1577. return
  1578. }
  1579. result, err = munger(clientAccount.VHost)
  1580. if err != nil {
  1581. return
  1582. }
  1583. vhtext, err := json.Marshal(result)
  1584. if err != nil {
  1585. err = errAccountUpdateFailed
  1586. return
  1587. }
  1588. vhstr := string(vhtext)
  1589. key := fmt.Sprintf(keyAccountVHost, account)
  1590. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1591. _, _, err := tx.Set(key, vhstr, nil)
  1592. return err
  1593. })
  1594. if err != nil {
  1595. err = errAccountUpdateFailed
  1596. return
  1597. }
  1598. am.applyVhostToClients(account, result)
  1599. return result, nil
  1600. }
  1601. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1602. // if hostserv is disabled in config, then don't grant vhosts
  1603. // that were previously approved while it was enabled
  1604. if !am.server.Config().Accounts.VHosts.Enabled {
  1605. return
  1606. }
  1607. vhost := ""
  1608. if info.Enabled {
  1609. vhost = info.ApprovedVHost
  1610. }
  1611. oldNickmask := client.NickMaskString()
  1612. updated := client.SetVHost(vhost)
  1613. if updated && client.Registered() {
  1614. // TODO: doing I/O here is kind of a kludge
  1615. client.sendChghost(oldNickmask, client.Hostname())
  1616. }
  1617. }
  1618. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1619. am.RLock()
  1620. clients := am.accountToClients[account]
  1621. am.RUnlock()
  1622. for _, client := range clients {
  1623. am.applyVHostInfo(client, result)
  1624. }
  1625. }
  1626. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1627. client.Login(account)
  1628. am.applyVHostInfo(client, account.VHost)
  1629. casefoldedAccount := client.Account()
  1630. am.Lock()
  1631. defer am.Unlock()
  1632. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1633. }
  1634. func (am *AccountManager) Logout(client *Client) {
  1635. am.Lock()
  1636. defer am.Unlock()
  1637. casefoldedAccount := client.Account()
  1638. if casefoldedAccount == "" {
  1639. return
  1640. }
  1641. client.Logout()
  1642. clients := am.accountToClients[casefoldedAccount]
  1643. if len(clients) <= 1 {
  1644. delete(am.accountToClients, casefoldedAccount)
  1645. return
  1646. }
  1647. remainingClients := make([]*Client, len(clients)-1)
  1648. remainingPos := 0
  1649. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1650. if clients[currentPos] != client {
  1651. remainingClients[remainingPos] = clients[currentPos]
  1652. remainingPos++
  1653. }
  1654. }
  1655. am.accountToClients[casefoldedAccount] = remainingClients
  1656. }
  1657. var (
  1658. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1659. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1660. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1661. "PLAIN": authPlainHandler,
  1662. "EXTERNAL": authExternalHandler,
  1663. }
  1664. )
  1665. type CredentialsVersion int
  1666. const (
  1667. CredentialsLegacy CredentialsVersion = 0
  1668. CredentialsSHA3Bcrypt CredentialsVersion = 1
  1669. // negative numbers for migration
  1670. CredentialsAtheme = -1
  1671. CredentialsAnope = -2
  1672. )
  1673. // AccountCredentials stores the various methods for verifying accounts.
  1674. type AccountCredentials struct {
  1675. Version CredentialsVersion
  1676. PassphraseHash []byte
  1677. Certfps []string
  1678. }
  1679. func (ac *AccountCredentials) Empty() bool {
  1680. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1681. }
  1682. // helper to assemble the serialized JSON for an account's credentials
  1683. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1684. ac.Version = 1
  1685. credText, err := json.Marshal(*ac)
  1686. if err != nil {
  1687. return "", err
  1688. }
  1689. return string(credText), nil
  1690. }
  1691. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1692. if passphrase == "" {
  1693. ac.PassphraseHash = nil
  1694. return nil
  1695. }
  1696. if validatePassphrase(passphrase) != nil {
  1697. return errAccountBadPassphrase
  1698. }
  1699. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1700. if err != nil {
  1701. return errAccountBadPassphrase
  1702. }
  1703. return nil
  1704. }
  1705. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1706. // XXX we require that certfp is already normalized (rather than normalize here
  1707. // and pass back the normalized version as an additional return parameter);
  1708. // this is just a final sanity check:
  1709. if len(certfp) != 64 {
  1710. return utils.ErrInvalidCertfp
  1711. }
  1712. for _, current := range ac.Certfps {
  1713. if certfp == current {
  1714. return errNoop
  1715. }
  1716. }
  1717. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1718. return errLimitExceeded
  1719. }
  1720. ac.Certfps = append(ac.Certfps, certfp)
  1721. return nil
  1722. }
  1723. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1724. found := false
  1725. newList := make([]string, 0, len(ac.Certfps))
  1726. for _, current := range ac.Certfps {
  1727. if current == certfp {
  1728. found = true
  1729. } else {
  1730. newList = append(newList, current)
  1731. }
  1732. }
  1733. if !found {
  1734. // this is important because it prevents you from deleting someone else's
  1735. // fingerprint record
  1736. return errNoop
  1737. }
  1738. ac.Certfps = newList
  1739. return nil
  1740. }
  1741. type MulticlientAllowedSetting int
  1742. const (
  1743. MulticlientAllowedServerDefault MulticlientAllowedSetting = iota
  1744. MulticlientDisallowedByUser
  1745. MulticlientAllowedByUser
  1746. )
  1747. // controls whether/when clients without event-playback support see fake
  1748. // PRIVMSGs for JOINs
  1749. type ReplayJoinsSetting uint
  1750. const (
  1751. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1752. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1753. ReplayJoinsNever // never replay
  1754. )
  1755. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1756. switch strings.ToLower(str) {
  1757. case "commands-only":
  1758. result = ReplayJoinsCommandsOnly
  1759. case "always":
  1760. result = ReplayJoinsAlways
  1761. case "never":
  1762. result = ReplayJoinsNever
  1763. default:
  1764. err = errInvalidParams
  1765. }
  1766. return
  1767. }
  1768. // XXX: AllowBouncer cannot be renamed AllowMulticlient because it is stored in
  1769. // persistent JSON blobs in the database
  1770. type AccountSettings struct {
  1771. AutoreplayLines *int
  1772. NickEnforcement NickEnforcementMethod
  1773. AllowBouncer MulticlientAllowedSetting
  1774. ReplayJoins ReplayJoinsSetting
  1775. AlwaysOn PersistentStatus
  1776. AutoreplayMissed bool
  1777. DMHistory HistoryStatus
  1778. AutoAway PersistentStatus
  1779. }
  1780. // ClientAccount represents a user account.
  1781. type ClientAccount struct {
  1782. // Name of the account.
  1783. Name string
  1784. NameCasefolded string
  1785. RegisteredAt time.Time
  1786. Credentials AccountCredentials
  1787. Verified bool
  1788. Suspended *AccountSuspension
  1789. AdditionalNicks []string
  1790. VHost VHostInfo
  1791. Settings AccountSettings
  1792. }
  1793. // convenience for passing around raw serialized account data
  1794. type rawClientAccount struct {
  1795. Name string
  1796. RegisteredAt string
  1797. Credentials string
  1798. Callback string
  1799. Verified bool
  1800. AdditionalNicks string
  1801. VHost string
  1802. Settings string
  1803. Suspended string
  1804. }