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

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