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

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