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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "net/smtp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode"
  14. "github.com/oragono/oragono/irc/caps"
  15. "github.com/oragono/oragono/irc/passwd"
  16. "github.com/oragono/oragono/irc/utils"
  17. "github.com/tidwall/buntdb"
  18. )
  19. const (
  20. keyAccountExists = "account.exists %s"
  21. keyAccountVerified = "account.verified %s"
  22. keyAccountCallback = "account.callback %s"
  23. keyAccountVerificationCode = "account.verificationcode %s"
  24. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  25. keyAccountRegTime = "account.registered.time %s"
  26. keyAccountCredentials = "account.credentials %s"
  27. keyAccountAdditionalNicks = "account.additionalnicks %s"
  28. keyAccountSettings = "account.settings %s"
  29. keyAccountVHost = "account.vhost %s"
  30. keyCertToAccount = "account.creds.certfp %s"
  31. keyAccountChannels = "account.channels %s"
  32. keyVHostQueueAcctToId = "vhostQueue %s"
  33. vhostRequestIdx = "vhostQueue"
  34. maxCertfpsPerAccount = 5
  35. )
  36. // everything about accounts is persistent; therefore, the database is the authoritative
  37. // source of truth for all account information. anything on the heap is just a cache
  38. type AccountManager struct {
  39. // XXX these are up here so they can be aligned to a 64-bit boundary, please forgive me
  40. // autoincrementing ID for vhost requests:
  41. vhostRequestID uint64
  42. vhostRequestPendingCount uint64
  43. sync.RWMutex // tier 2
  44. serialCacheUpdateMutex sync.Mutex // tier 3
  45. vHostUpdateMutex sync.Mutex // tier 3
  46. server *Server
  47. // track clients logged in to accounts
  48. accountToClients map[string][]*Client
  49. nickToAccount map[string]string
  50. skeletonToAccount map[string]string
  51. accountToMethod map[string]NickEnforcementMethod
  52. }
  53. func (am *AccountManager) Initialize(server *Server) {
  54. am.accountToClients = make(map[string][]*Client)
  55. am.nickToAccount = make(map[string]string)
  56. am.skeletonToAccount = make(map[string]string)
  57. am.accountToMethod = make(map[string]NickEnforcementMethod)
  58. am.server = server
  59. config := server.Config()
  60. am.buildNickToAccountIndex(config)
  61. am.initVHostRequestQueue(config)
  62. }
  63. func (am *AccountManager) buildNickToAccountIndex(config *Config) {
  64. if !config.Accounts.NickReservation.Enabled {
  65. return
  66. }
  67. nickToAccount := make(map[string]string)
  68. skeletonToAccount := make(map[string]string)
  69. accountToMethod := make(map[string]NickEnforcementMethod)
  70. existsPrefix := fmt.Sprintf(keyAccountExists, "")
  71. am.serialCacheUpdateMutex.Lock()
  72. defer am.serialCacheUpdateMutex.Unlock()
  73. err := am.server.store.View(func(tx *buntdb.Tx) error {
  74. err := tx.AscendGreaterOrEqual("", existsPrefix, func(key, value string) bool {
  75. if !strings.HasPrefix(key, existsPrefix) {
  76. return false
  77. }
  78. account := strings.TrimPrefix(key, existsPrefix)
  79. if _, err := tx.Get(fmt.Sprintf(keyAccountVerified, account)); err == nil {
  80. nickToAccount[account] = account
  81. accountName, err := tx.Get(fmt.Sprintf(keyAccountName, account))
  82. if err != nil {
  83. am.server.logger.Error("internal", "missing account name for", account)
  84. } else {
  85. skeleton, _ := Skeleton(accountName)
  86. skeletonToAccount[skeleton] = account
  87. }
  88. }
  89. if rawNicks, err := tx.Get(fmt.Sprintf(keyAccountAdditionalNicks, account)); err == nil {
  90. additionalNicks := unmarshalReservedNicks(rawNicks)
  91. for _, nick := range additionalNicks {
  92. cfnick, _ := CasefoldName(nick)
  93. nickToAccount[cfnick] = account
  94. skeleton, _ := Skeleton(nick)
  95. skeletonToAccount[skeleton] = account
  96. }
  97. }
  98. if rawPrefs, err := tx.Get(fmt.Sprintf(keyAccountSettings, account)); err == nil {
  99. var prefs AccountSettings
  100. err := json.Unmarshal([]byte(rawPrefs), &prefs)
  101. if err == nil && prefs.NickEnforcement != NickEnforcementOptional {
  102. accountToMethod[account] = prefs.NickEnforcement
  103. } else if err != nil {
  104. am.server.logger.Error("internal", "corrupt account creds", account)
  105. }
  106. }
  107. return true
  108. })
  109. return err
  110. })
  111. if err != nil {
  112. am.server.logger.Error("internal", "couldn't read reserved nicks", err.Error())
  113. } else {
  114. am.Lock()
  115. am.nickToAccount = nickToAccount
  116. am.skeletonToAccount = skeletonToAccount
  117. am.accountToMethod = accountToMethod
  118. am.Unlock()
  119. }
  120. }
  121. func (am *AccountManager) initVHostRequestQueue(config *Config) {
  122. if !config.Accounts.VHosts.Enabled {
  123. return
  124. }
  125. am.vHostUpdateMutex.Lock()
  126. defer am.vHostUpdateMutex.Unlock()
  127. // the db maps the account name to the autoincrementing integer ID of its request
  128. // create an numerically ordered index on ID, so we can list the oldest requests
  129. // finally, collect the integer id of the newest request and the total request count
  130. var total uint64
  131. var lastIDStr string
  132. err := am.server.store.Update(func(tx *buntdb.Tx) error {
  133. err := tx.CreateIndex(vhostRequestIdx, fmt.Sprintf(keyVHostQueueAcctToId, "*"), buntdb.IndexInt)
  134. if err != nil {
  135. return err
  136. }
  137. return tx.Descend(vhostRequestIdx, func(key, value string) bool {
  138. if lastIDStr == "" {
  139. lastIDStr = value
  140. }
  141. total++
  142. return true
  143. })
  144. })
  145. if err != nil {
  146. am.server.logger.Error("internal", "could not create vhost queue index", err.Error())
  147. }
  148. lastID, _ := strconv.ParseUint(lastIDStr, 10, 64)
  149. am.server.logger.Debug("services", fmt.Sprintf("vhost queue length is %d, autoincrementing id is %d", total, lastID))
  150. atomic.StoreUint64(&am.vhostRequestID, lastID)
  151. atomic.StoreUint64(&am.vhostRequestPendingCount, total)
  152. }
  153. func (am *AccountManager) NickToAccount(nick string) string {
  154. cfnick, err := CasefoldName(nick)
  155. if err != nil {
  156. return ""
  157. }
  158. am.RLock()
  159. defer am.RUnlock()
  160. return am.nickToAccount[cfnick]
  161. }
  162. // given an account, combine stored enforcement method with the config settings
  163. // to compute the actual enforcement method
  164. func configuredEnforcementMethod(config *Config, storedMethod NickEnforcementMethod) (result NickEnforcementMethod) {
  165. if !config.Accounts.NickReservation.Enabled {
  166. return NickEnforcementNone
  167. }
  168. result = storedMethod
  169. // if they don't have a custom setting, or customization is disabled, use the default
  170. if result == NickEnforcementOptional || !config.Accounts.NickReservation.AllowCustomEnforcement {
  171. result = config.Accounts.NickReservation.Method
  172. }
  173. if result == NickEnforcementOptional {
  174. // enforcement was explicitly enabled neither in the config or by the user
  175. result = NickEnforcementNone
  176. }
  177. return
  178. }
  179. // Given a nick, looks up the account that owns it and the method (none/timeout/strict)
  180. // used to enforce ownership.
  181. func (am *AccountManager) EnforcementStatus(cfnick, skeleton string) (account string, method NickEnforcementMethod) {
  182. config := am.server.Config()
  183. if !config.Accounts.NickReservation.Enabled {
  184. return "", NickEnforcementNone
  185. }
  186. am.RLock()
  187. defer am.RUnlock()
  188. finalEnforcementMethod := func(account_ string) (result NickEnforcementMethod) {
  189. storedMethod := am.accountToMethod[account_]
  190. return configuredEnforcementMethod(config, storedMethod)
  191. }
  192. nickAccount := am.nickToAccount[cfnick]
  193. skelAccount := am.skeletonToAccount[skeleton]
  194. if nickAccount == "" && skelAccount == "" {
  195. return "", NickEnforcementNone
  196. } else if nickAccount != "" && (skelAccount == nickAccount || skelAccount == "") {
  197. return nickAccount, finalEnforcementMethod(nickAccount)
  198. } else if skelAccount != "" && nickAccount == "" {
  199. return skelAccount, finalEnforcementMethod(skelAccount)
  200. } else {
  201. // nickAccount != skelAccount and both are nonempty:
  202. // two people have competing claims on (this casefolding of) this nick!
  203. nickMethod := finalEnforcementMethod(nickAccount)
  204. skelMethod := finalEnforcementMethod(skelAccount)
  205. switch {
  206. case skelMethod == NickEnforcementNone:
  207. return nickAccount, nickMethod
  208. case nickMethod == NickEnforcementNone:
  209. return skelAccount, skelMethod
  210. default:
  211. // nobody can use this nick
  212. return "!", NickEnforcementStrict
  213. }
  214. }
  215. }
  216. // Sets a custom enforcement method for an account and stores it in the database.
  217. func (am *AccountManager) SetEnforcementStatus(account string, method NickEnforcementMethod) (finalSettings AccountSettings, err error) {
  218. config := am.server.Config()
  219. if !(config.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.AllowCustomEnforcement) {
  220. err = errFeatureDisabled
  221. return
  222. }
  223. setter := func(in AccountSettings) (out AccountSettings, err error) {
  224. out = in
  225. out.NickEnforcement = method
  226. return out, nil
  227. }
  228. _, err = am.ModifyAccountSettings(account, setter)
  229. if err != nil {
  230. return
  231. }
  232. // this update of the data plane is racey, but it's probably fine
  233. am.Lock()
  234. defer am.Unlock()
  235. if method == NickEnforcementOptional {
  236. delete(am.accountToMethod, account)
  237. } else {
  238. am.accountToMethod[account] = method
  239. }
  240. return
  241. }
  242. func (am *AccountManager) AccountToClients(account string) (result []*Client) {
  243. cfaccount, err := CasefoldName(account)
  244. if err != nil {
  245. return
  246. }
  247. am.RLock()
  248. defer am.RUnlock()
  249. return am.accountToClients[cfaccount]
  250. }
  251. func (am *AccountManager) Register(client *Client, account string, callbackNamespace string, callbackValue string, passphrase string, certfp string) error {
  252. casefoldedAccount, err := CasefoldName(account)
  253. skeleton, skerr := Skeleton(account)
  254. if err != nil || skerr != nil || account == "" || account == "*" {
  255. return errAccountCreation
  256. }
  257. if restrictedCasefoldedNicks[casefoldedAccount] || restrictedSkeletons[skeleton] {
  258. return errAccountAlreadyRegistered
  259. }
  260. config := am.server.AccountConfig()
  261. // final "is registration allowed" check, probably redundant:
  262. if !(config.Registration.Enabled || callbackNamespace == "admin") {
  263. return errFeatureDisabled
  264. }
  265. // if nick reservation is enabled, you can only register your current nickname
  266. // as an account; this prevents "land-grab" situations where someone else
  267. // registers your nick out from under you and then NS GHOSTs you
  268. // n.b. client is nil during a SAREGISTER:
  269. if config.NickReservation.Enabled && client != nil && client.NickCasefolded() != casefoldedAccount {
  270. return errAccountMustHoldNick
  271. }
  272. // can't register a guest nickname
  273. renamePrefix := strings.ToLower(config.NickReservation.RenamePrefix)
  274. if renamePrefix != "" && strings.HasPrefix(casefoldedAccount, renamePrefix) {
  275. return errAccountAlreadyRegistered
  276. }
  277. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  278. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  279. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  280. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  281. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  282. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  283. certFPKey := fmt.Sprintf(keyCertToAccount, certfp)
  284. var creds AccountCredentials
  285. creds.Version = 1
  286. err = creds.SetPassphrase(passphrase, am.server.Config().Accounts.Registration.BcryptCost)
  287. if err != nil {
  288. return err
  289. }
  290. creds.AddCertfp(certfp)
  291. credStr, err := creds.Serialize()
  292. if err != nil {
  293. return err
  294. }
  295. registeredTimeStr := strconv.FormatInt(time.Now().Unix(), 10)
  296. callbackSpec := fmt.Sprintf("%s:%s", callbackNamespace, callbackValue)
  297. var setOptions *buntdb.SetOptions
  298. ttl := config.Registration.VerifyTimeout
  299. if ttl != 0 {
  300. setOptions = &buntdb.SetOptions{Expires: true, TTL: ttl}
  301. }
  302. err = func() error {
  303. am.serialCacheUpdateMutex.Lock()
  304. defer am.serialCacheUpdateMutex.Unlock()
  305. // can't register an account with the same name as a registered nick
  306. if am.NickToAccount(casefoldedAccount) != "" {
  307. return errAccountAlreadyRegistered
  308. }
  309. return am.server.store.Update(func(tx *buntdb.Tx) error {
  310. _, err := am.loadRawAccount(tx, casefoldedAccount)
  311. if err != errAccountDoesNotExist {
  312. return errAccountAlreadyRegistered
  313. }
  314. if certfp != "" {
  315. // make sure certfp doesn't already exist because that'd be silly
  316. _, err := tx.Get(certFPKey)
  317. if err != buntdb.ErrNotFound {
  318. return errCertfpAlreadyExists
  319. }
  320. }
  321. tx.Set(accountKey, "1", setOptions)
  322. tx.Set(accountNameKey, account, setOptions)
  323. tx.Set(registeredTimeKey, registeredTimeStr, setOptions)
  324. tx.Set(credentialsKey, credStr, setOptions)
  325. tx.Set(callbackKey, callbackSpec, setOptions)
  326. if certfp != "" {
  327. tx.Set(certFPKey, casefoldedAccount, setOptions)
  328. }
  329. return nil
  330. })
  331. }()
  332. if err != nil {
  333. return err
  334. }
  335. code, err := am.dispatchCallback(client, casefoldedAccount, callbackNamespace, callbackValue)
  336. if err != nil {
  337. am.Unregister(casefoldedAccount)
  338. return errCallbackFailed
  339. } else {
  340. return am.server.store.Update(func(tx *buntdb.Tx) error {
  341. _, _, err = tx.Set(verificationCodeKey, code, setOptions)
  342. return err
  343. })
  344. }
  345. }
  346. // validatePassphrase checks whether a passphrase is allowed by our rules
  347. func validatePassphrase(passphrase string) error {
  348. // sanity check the length
  349. if len(passphrase) == 0 || len(passphrase) > 600 {
  350. return errAccountBadPassphrase
  351. }
  352. // we use * as a placeholder in some places, if it's gotten this far then fail
  353. if passphrase == "*" {
  354. return errAccountBadPassphrase
  355. }
  356. // for now, just enforce that spaces are not allowed
  357. for _, r := range passphrase {
  358. if unicode.IsSpace(r) {
  359. return errAccountBadPassphrase
  360. }
  361. }
  362. return nil
  363. }
  364. // changes the password for an account
  365. func (am *AccountManager) setPassword(account string, password string, hasPrivs bool) (err error) {
  366. cfAccount, err := CasefoldName(account)
  367. if err != nil {
  368. return errAccountDoesNotExist
  369. }
  370. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  371. var credStr string
  372. am.server.store.View(func(tx *buntdb.Tx) error {
  373. // no need to check verification status here or below;
  374. // you either need to be auth'ed to the account or be an oper to do this
  375. credStr, err = tx.Get(credKey)
  376. return nil
  377. })
  378. if err != nil {
  379. return errAccountDoesNotExist
  380. }
  381. var creds AccountCredentials
  382. err = json.Unmarshal([]byte(credStr), &creds)
  383. if err != nil {
  384. return err
  385. }
  386. err = creds.SetPassphrase(password, am.server.Config().Accounts.Registration.BcryptCost)
  387. if err != nil {
  388. return err
  389. }
  390. if creds.Empty() && !hasPrivs {
  391. return errEmptyCredentials
  392. }
  393. newCredStr, err := creds.Serialize()
  394. if err != nil {
  395. return err
  396. }
  397. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  398. curCredStr, err := tx.Get(credKey)
  399. if credStr != curCredStr {
  400. return errCASFailed
  401. }
  402. _, _, err = tx.Set(credKey, newCredStr, nil)
  403. return err
  404. })
  405. return err
  406. }
  407. func (am *AccountManager) addRemoveCertfp(account, certfp string, add bool, hasPrivs bool) (err error) {
  408. certfp, err = utils.NormalizeCertfp(certfp)
  409. if err != nil {
  410. return err
  411. }
  412. cfAccount, err := CasefoldName(account)
  413. if err != nil {
  414. return errAccountDoesNotExist
  415. }
  416. credKey := fmt.Sprintf(keyAccountCredentials, cfAccount)
  417. var credStr string
  418. am.server.store.View(func(tx *buntdb.Tx) error {
  419. credStr, err = tx.Get(credKey)
  420. return nil
  421. })
  422. if err != nil {
  423. return errAccountDoesNotExist
  424. }
  425. var creds AccountCredentials
  426. err = json.Unmarshal([]byte(credStr), &creds)
  427. if err != nil {
  428. return err
  429. }
  430. if add {
  431. err = creds.AddCertfp(certfp)
  432. } else {
  433. err = creds.RemoveCertfp(certfp)
  434. }
  435. if err != nil {
  436. return err
  437. }
  438. if creds.Empty() && !hasPrivs {
  439. return errEmptyCredentials
  440. }
  441. newCredStr, err := creds.Serialize()
  442. if err != nil {
  443. return err
  444. }
  445. certfpKey := fmt.Sprintf(keyCertToAccount, certfp)
  446. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  447. curCredStr, err := tx.Get(credKey)
  448. if credStr != curCredStr {
  449. return errCASFailed
  450. }
  451. if add {
  452. _, err = tx.Get(certfpKey)
  453. if err != buntdb.ErrNotFound {
  454. return errCertfpAlreadyExists
  455. }
  456. tx.Set(certfpKey, cfAccount, nil)
  457. } else {
  458. tx.Delete(certfpKey)
  459. }
  460. _, _, err = tx.Set(credKey, newCredStr, nil)
  461. return err
  462. })
  463. return err
  464. }
  465. func (am *AccountManager) dispatchCallback(client *Client, casefoldedAccount string, callbackNamespace string, callbackValue string) (string, error) {
  466. if callbackNamespace == "*" || callbackNamespace == "none" || callbackNamespace == "admin" {
  467. return "", nil
  468. } else if callbackNamespace == "mailto" {
  469. return am.dispatchMailtoCallback(client, casefoldedAccount, callbackValue)
  470. } else {
  471. return "", fmt.Errorf("Callback not implemented: %s", callbackNamespace)
  472. }
  473. }
  474. func (am *AccountManager) dispatchMailtoCallback(client *Client, casefoldedAccount string, callbackValue string) (code string, err error) {
  475. config := am.server.AccountConfig().Registration.Callbacks.Mailto
  476. code = utils.GenerateSecretToken()
  477. subject := config.VerifyMessageSubject
  478. if subject == "" {
  479. subject = fmt.Sprintf(client.t("Verify your account on %s"), am.server.name)
  480. }
  481. messageStrings := []string{
  482. fmt.Sprintf("From: %s\r\n", config.Sender),
  483. fmt.Sprintf("To: %s\r\n", callbackValue),
  484. fmt.Sprintf("Subject: %s\r\n", subject),
  485. "\r\n", // end headers, begin message body
  486. fmt.Sprintf(client.t("Account: %s"), casefoldedAccount) + "\r\n",
  487. fmt.Sprintf(client.t("Verification code: %s"), code) + "\r\n",
  488. "\r\n",
  489. client.t("To verify your account, issue the following command:") + "\r\n",
  490. fmt.Sprintf("/MSG NickServ VERIFY %s %s", casefoldedAccount, code) + "\r\n",
  491. }
  492. var message []byte
  493. for i := 0; i < len(messageStrings); i++ {
  494. message = append(message, []byte(messageStrings[i])...)
  495. }
  496. addr := fmt.Sprintf("%s:%d", config.Server, config.Port)
  497. var auth smtp.Auth
  498. if config.Username != "" && config.Password != "" {
  499. auth = smtp.PlainAuth("", config.Username, config.Password, config.Server)
  500. }
  501. // TODO: this will never send the password in plaintext over a nonlocal link,
  502. // but it might send the email in plaintext, regardless of the value of
  503. // config.TLS.InsecureSkipVerify
  504. err = smtp.SendMail(addr, auth, config.Sender, []string{callbackValue}, message)
  505. if err != nil {
  506. am.server.logger.Error("internal", "Failed to dispatch e-mail", err.Error())
  507. }
  508. return
  509. }
  510. func (am *AccountManager) Verify(client *Client, account string, code string) error {
  511. casefoldedAccount, err := CasefoldName(account)
  512. if err != nil || account == "" || account == "*" {
  513. return errAccountVerificationFailed
  514. }
  515. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  516. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  517. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  518. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  519. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  520. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  521. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  522. var raw rawClientAccount
  523. func() {
  524. am.serialCacheUpdateMutex.Lock()
  525. defer am.serialCacheUpdateMutex.Unlock()
  526. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  527. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  528. if err == errAccountDoesNotExist {
  529. return errAccountDoesNotExist
  530. } else if err != nil {
  531. return errAccountVerificationFailed
  532. } else if raw.Verified {
  533. return errAccountAlreadyVerified
  534. }
  535. // actually verify the code
  536. // a stored code of "" means a none callback / no code required
  537. success := false
  538. storedCode, err := tx.Get(verificationCodeKey)
  539. if err == nil {
  540. // this is probably unnecessary
  541. if storedCode == "" || utils.SecretTokensMatch(storedCode, code) {
  542. success = true
  543. }
  544. }
  545. if !success {
  546. return errAccountVerificationInvalidCode
  547. }
  548. // verify the account
  549. tx.Set(verifiedKey, "1", nil)
  550. // don't need the code anymore
  551. tx.Delete(verificationCodeKey)
  552. // re-set all other keys, removing the TTL
  553. tx.Set(accountKey, "1", nil)
  554. tx.Set(accountNameKey, raw.Name, nil)
  555. tx.Set(registeredTimeKey, raw.RegisteredAt, nil)
  556. tx.Set(callbackKey, raw.Callback, nil)
  557. tx.Set(credentialsKey, raw.Credentials, nil)
  558. var creds AccountCredentials
  559. // XXX we shouldn't do (de)serialization inside the txn,
  560. // but this is like 2 usec on my system
  561. json.Unmarshal([]byte(raw.Credentials), &creds)
  562. for _, cert := range creds.Certfps {
  563. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  564. tx.Set(certFPKey, casefoldedAccount, nil)
  565. }
  566. return nil
  567. })
  568. if err == nil {
  569. skeleton, _ := Skeleton(raw.Name)
  570. am.Lock()
  571. am.nickToAccount[casefoldedAccount] = casefoldedAccount
  572. am.skeletonToAccount[skeleton] = casefoldedAccount
  573. am.Unlock()
  574. }
  575. }()
  576. if err != nil {
  577. return err
  578. }
  579. nick := "[server admin]"
  580. if client != nil {
  581. nick = client.Nick()
  582. }
  583. am.server.logger.Info("accounts", "client", nick, "registered account", casefoldedAccount)
  584. raw.Verified = true
  585. clientAccount, err := am.deserializeRawAccount(raw)
  586. if err != nil {
  587. return err
  588. }
  589. if client != nil {
  590. am.Login(client, clientAccount)
  591. }
  592. return nil
  593. }
  594. func marshalReservedNicks(nicks []string) string {
  595. return strings.Join(nicks, ",")
  596. }
  597. func unmarshalReservedNicks(nicks string) (result []string) {
  598. if nicks == "" {
  599. return
  600. }
  601. return strings.Split(nicks, ",")
  602. }
  603. func (am *AccountManager) SetNickReserved(client *Client, nick string, saUnreserve bool, reserve bool) error {
  604. cfnick, err := CasefoldName(nick)
  605. skeleton, skerr := Skeleton(nick)
  606. // garbage nick, or garbage options, or disabled
  607. nrconfig := am.server.AccountConfig().NickReservation
  608. if err != nil || skerr != nil || cfnick == "" || (reserve && saUnreserve) || !nrconfig.Enabled {
  609. return errAccountNickReservationFailed
  610. }
  611. // the cache is in sync with the DB while we hold serialCacheUpdateMutex
  612. am.serialCacheUpdateMutex.Lock()
  613. defer am.serialCacheUpdateMutex.Unlock()
  614. // find the affected account, which is usually the client's:
  615. account := client.Account()
  616. if saUnreserve {
  617. // unless this is a sadrop:
  618. account = am.NickToAccount(cfnick)
  619. if account == "" {
  620. // nothing to do
  621. return nil
  622. }
  623. }
  624. if account == "" {
  625. return errAccountNotLoggedIn
  626. }
  627. am.Lock()
  628. accountForNick := am.nickToAccount[cfnick]
  629. var accountForSkeleton string
  630. if reserve {
  631. accountForSkeleton = am.skeletonToAccount[skeleton]
  632. }
  633. am.Unlock()
  634. if reserve && (accountForNick != "" || accountForSkeleton != "") {
  635. return errNicknameReserved
  636. } else if !reserve && !saUnreserve && accountForNick != account {
  637. return errNicknameReserved
  638. } else if !reserve && cfnick == account {
  639. return errAccountCantDropPrimaryNick
  640. }
  641. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, account)
  642. unverifiedAccountKey := fmt.Sprintf(keyAccountExists, cfnick)
  643. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  644. if reserve {
  645. // unverified accounts don't show up in NickToAccount yet (which is intentional),
  646. // however you shouldn't be able to reserve a nick out from under them
  647. _, err := tx.Get(unverifiedAccountKey)
  648. if err == nil {
  649. return errNicknameReserved
  650. }
  651. }
  652. rawNicks, err := tx.Get(nicksKey)
  653. if err != nil && err != buntdb.ErrNotFound {
  654. return err
  655. }
  656. nicks := unmarshalReservedNicks(rawNicks)
  657. if reserve {
  658. if len(nicks) >= nrconfig.AdditionalNickLimit {
  659. return errAccountTooManyNicks
  660. }
  661. nicks = append(nicks, nick)
  662. } else {
  663. // compute (original reserved nicks) minus cfnick
  664. var newNicks []string
  665. for _, reservedNick := range nicks {
  666. cfreservednick, _ := CasefoldName(reservedNick)
  667. if cfreservednick != cfnick {
  668. newNicks = append(newNicks, reservedNick)
  669. } else {
  670. // found the original, unfolded version of the nick we're dropping;
  671. // recompute the true skeleton from it
  672. skeleton, _ = Skeleton(reservedNick)
  673. }
  674. }
  675. nicks = newNicks
  676. }
  677. marshaledNicks := marshalReservedNicks(nicks)
  678. _, _, err = tx.Set(nicksKey, string(marshaledNicks), nil)
  679. return err
  680. })
  681. if err == errAccountTooManyNicks || err == errNicknameReserved {
  682. return err
  683. } else if err != nil {
  684. return errAccountNickReservationFailed
  685. }
  686. // success
  687. am.Lock()
  688. defer am.Unlock()
  689. if reserve {
  690. am.nickToAccount[cfnick] = account
  691. am.skeletonToAccount[skeleton] = account
  692. } else {
  693. delete(am.nickToAccount, cfnick)
  694. delete(am.skeletonToAccount, skeleton)
  695. }
  696. return nil
  697. }
  698. func (am *AccountManager) checkPassphrase(accountName, passphrase string) (account ClientAccount, err error) {
  699. account, err = am.LoadAccount(accountName)
  700. if err != nil {
  701. return
  702. }
  703. if !account.Verified {
  704. err = errAccountUnverified
  705. return
  706. }
  707. switch account.Credentials.Version {
  708. case 0:
  709. err = handleLegacyPasswordV0(am.server, accountName, account.Credentials, passphrase)
  710. case 1:
  711. if passwd.CompareHashAndPassword(account.Credentials.PassphraseHash, []byte(passphrase)) != nil {
  712. err = errAccountInvalidCredentials
  713. }
  714. default:
  715. err = errAccountInvalidCredentials
  716. }
  717. return
  718. }
  719. func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName string, passphrase string) error {
  720. account, err := am.checkPassphrase(accountName, passphrase)
  721. if err != nil {
  722. return err
  723. }
  724. am.Login(client, account)
  725. return nil
  726. }
  727. func (am *AccountManager) LoadAccount(accountName string) (result ClientAccount, err error) {
  728. casefoldedAccount, err := CasefoldName(accountName)
  729. if err != nil {
  730. err = errAccountDoesNotExist
  731. return
  732. }
  733. var raw rawClientAccount
  734. am.server.store.View(func(tx *buntdb.Tx) error {
  735. raw, err = am.loadRawAccount(tx, casefoldedAccount)
  736. return nil
  737. })
  738. if err != nil {
  739. return
  740. }
  741. result, err = am.deserializeRawAccount(raw)
  742. result.NameCasefolded = casefoldedAccount
  743. return
  744. }
  745. func (am *AccountManager) deserializeRawAccount(raw rawClientAccount) (result ClientAccount, err error) {
  746. result.Name = raw.Name
  747. regTimeInt, _ := strconv.ParseInt(raw.RegisteredAt, 10, 64)
  748. result.RegisteredAt = time.Unix(regTimeInt, 0).UTC()
  749. e := json.Unmarshal([]byte(raw.Credentials), &result.Credentials)
  750. if e != nil {
  751. am.server.logger.Error("internal", "could not unmarshal credentials", e.Error())
  752. err = errAccountDoesNotExist
  753. return
  754. }
  755. result.AdditionalNicks = unmarshalReservedNicks(raw.AdditionalNicks)
  756. result.Verified = raw.Verified
  757. if raw.VHost != "" {
  758. e := json.Unmarshal([]byte(raw.VHost), &result.VHost)
  759. if e != nil {
  760. am.server.logger.Warning("internal", "could not unmarshal vhost for account", result.Name, e.Error())
  761. // pretend they have no vhost and move on
  762. }
  763. }
  764. if raw.Settings != "" {
  765. e := json.Unmarshal([]byte(raw.Settings), &result.Settings)
  766. if e != nil {
  767. am.server.logger.Warning("internal", "could not unmarshal settings for account", result.Name, e.Error())
  768. }
  769. }
  770. return
  771. }
  772. func (am *AccountManager) loadRawAccount(tx *buntdb.Tx, casefoldedAccount string) (result rawClientAccount, err error) {
  773. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  774. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  775. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  776. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  777. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  778. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  779. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  780. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  781. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  782. _, e := tx.Get(accountKey)
  783. if e == buntdb.ErrNotFound {
  784. err = errAccountDoesNotExist
  785. return
  786. }
  787. result.Name, _ = tx.Get(accountNameKey)
  788. result.RegisteredAt, _ = tx.Get(registeredTimeKey)
  789. result.Credentials, _ = tx.Get(credentialsKey)
  790. result.Callback, _ = tx.Get(callbackKey)
  791. result.AdditionalNicks, _ = tx.Get(nicksKey)
  792. result.VHost, _ = tx.Get(vhostKey)
  793. result.Settings, _ = tx.Get(settingsKey)
  794. if _, e = tx.Get(verifiedKey); e == nil {
  795. result.Verified = true
  796. }
  797. return
  798. }
  799. func (am *AccountManager) Unregister(account string) error {
  800. config := am.server.Config()
  801. casefoldedAccount, err := CasefoldName(account)
  802. if err != nil {
  803. return errAccountDoesNotExist
  804. }
  805. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  806. accountNameKey := fmt.Sprintf(keyAccountName, casefoldedAccount)
  807. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  808. credentialsKey := fmt.Sprintf(keyAccountCredentials, casefoldedAccount)
  809. callbackKey := fmt.Sprintf(keyAccountCallback, casefoldedAccount)
  810. verificationCodeKey := fmt.Sprintf(keyAccountVerificationCode, casefoldedAccount)
  811. verifiedKey := fmt.Sprintf(keyAccountVerified, casefoldedAccount)
  812. nicksKey := fmt.Sprintf(keyAccountAdditionalNicks, casefoldedAccount)
  813. settingsKey := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  814. vhostKey := fmt.Sprintf(keyAccountVHost, casefoldedAccount)
  815. vhostQueueKey := fmt.Sprintf(keyVHostQueueAcctToId, casefoldedAccount)
  816. channelsKey := fmt.Sprintf(keyAccountChannels, casefoldedAccount)
  817. var clients []*Client
  818. var registeredChannels []string
  819. // on our way out, unregister all the account's channels and delete them from the db
  820. defer func() {
  821. for _, channelName := range registeredChannels {
  822. am.server.channels.SetUnregistered(channelName, casefoldedAccount)
  823. }
  824. }()
  825. var credText string
  826. var rawNicks string
  827. am.serialCacheUpdateMutex.Lock()
  828. defer am.serialCacheUpdateMutex.Unlock()
  829. var accountName string
  830. var channelsStr string
  831. am.server.store.Update(func(tx *buntdb.Tx) error {
  832. tx.Delete(accountKey)
  833. accountName, _ = tx.Get(accountNameKey)
  834. tx.Delete(accountNameKey)
  835. tx.Delete(verifiedKey)
  836. tx.Delete(registeredTimeKey)
  837. tx.Delete(callbackKey)
  838. tx.Delete(verificationCodeKey)
  839. tx.Delete(settingsKey)
  840. rawNicks, _ = tx.Get(nicksKey)
  841. tx.Delete(nicksKey)
  842. credText, err = tx.Get(credentialsKey)
  843. tx.Delete(credentialsKey)
  844. tx.Delete(vhostKey)
  845. channelsStr, _ = tx.Get(channelsKey)
  846. tx.Delete(channelsKey)
  847. _, err := tx.Delete(vhostQueueKey)
  848. am.decrementVHostQueueCount(casefoldedAccount, err)
  849. return nil
  850. })
  851. if err == nil {
  852. var creds AccountCredentials
  853. if err = json.Unmarshal([]byte(credText), &creds); err == nil {
  854. for _, cert := range creds.Certfps {
  855. certFPKey := fmt.Sprintf(keyCertToAccount, cert)
  856. am.server.store.Update(func(tx *buntdb.Tx) error {
  857. if account, err := tx.Get(certFPKey); err == nil && account == casefoldedAccount {
  858. tx.Delete(certFPKey)
  859. }
  860. return nil
  861. })
  862. }
  863. }
  864. }
  865. skeleton, _ := Skeleton(accountName)
  866. additionalNicks := unmarshalReservedNicks(rawNicks)
  867. registeredChannels = unmarshalRegisteredChannels(channelsStr)
  868. am.Lock()
  869. defer am.Unlock()
  870. clients = am.accountToClients[casefoldedAccount]
  871. delete(am.accountToClients, casefoldedAccount)
  872. delete(am.nickToAccount, casefoldedAccount)
  873. delete(am.skeletonToAccount, skeleton)
  874. for _, nick := range additionalNicks {
  875. delete(am.nickToAccount, nick)
  876. additionalSkel, _ := Skeleton(nick)
  877. delete(am.skeletonToAccount, additionalSkel)
  878. }
  879. for _, client := range clients {
  880. if config.Accounts.RequireSasl.Enabled {
  881. client.Quit(client.t("You are no longer authorized to be on this server"), nil)
  882. // destroy acquires a semaphore so we can't call it while holding a lock
  883. go client.destroy(nil)
  884. } else {
  885. am.logoutOfAccount(client)
  886. }
  887. }
  888. if err != nil {
  889. return errAccountDoesNotExist
  890. }
  891. return nil
  892. }
  893. func unmarshalRegisteredChannels(channelsStr string) (result []string) {
  894. if channelsStr != "" {
  895. result = strings.Split(channelsStr, ",")
  896. }
  897. return
  898. }
  899. func (am *AccountManager) ChannelsForAccount(account string) (channels []string) {
  900. cfaccount, err := CasefoldName(account)
  901. if err != nil {
  902. return
  903. }
  904. var channelStr string
  905. key := fmt.Sprintf(keyAccountChannels, cfaccount)
  906. am.server.store.View(func(tx *buntdb.Tx) error {
  907. channelStr, _ = tx.Get(key)
  908. return nil
  909. })
  910. return unmarshalRegisteredChannels(channelStr)
  911. }
  912. func (am *AccountManager) AuthenticateByCertFP(client *Client, authzid string) error {
  913. if client.certfp == "" {
  914. return errAccountInvalidCredentials
  915. }
  916. var account string
  917. certFPKey := fmt.Sprintf(keyCertToAccount, client.certfp)
  918. err := am.server.store.View(func(tx *buntdb.Tx) error {
  919. account, _ = tx.Get(certFPKey)
  920. if account == "" {
  921. return errAccountInvalidCredentials
  922. }
  923. return nil
  924. })
  925. if err != nil {
  926. return err
  927. }
  928. if authzid != "" && authzid != account {
  929. return errAuthzidAuthcidMismatch
  930. }
  931. // ok, we found an account corresponding to their certificate
  932. clientAccount, err := am.LoadAccount(account)
  933. if err != nil {
  934. return err
  935. } else if !clientAccount.Verified {
  936. return errAccountUnverified
  937. }
  938. am.Login(client, clientAccount)
  939. return nil
  940. }
  941. type settingsMunger func(input AccountSettings) (output AccountSettings, err error)
  942. func (am *AccountManager) ModifyAccountSettings(account string, munger settingsMunger) (newSettings AccountSettings, err error) {
  943. casefoldedAccount, err := CasefoldName(account)
  944. if err != nil {
  945. return newSettings, errAccountDoesNotExist
  946. }
  947. // TODO implement this in general via a compare-and-swap API
  948. accountData, err := am.LoadAccount(casefoldedAccount)
  949. if err != nil {
  950. return
  951. } else if !accountData.Verified {
  952. return newSettings, errAccountUnverified
  953. }
  954. newSettings, err = munger(accountData.Settings)
  955. if err != nil {
  956. return
  957. }
  958. text, err := json.Marshal(newSettings)
  959. if err != nil {
  960. return
  961. }
  962. key := fmt.Sprintf(keyAccountSettings, casefoldedAccount)
  963. serializedValue := string(text)
  964. err = am.server.store.Update(func(tx *buntdb.Tx) (err error) {
  965. _, _, err = tx.Set(key, serializedValue, nil)
  966. return
  967. })
  968. if err != nil {
  969. err = errAccountUpdateFailed
  970. return
  971. }
  972. // success, push new settings into the client objects
  973. am.Lock()
  974. defer am.Unlock()
  975. for _, client := range am.accountToClients[casefoldedAccount] {
  976. client.SetAccountSettings(newSettings)
  977. }
  978. return
  979. }
  980. // represents someone's status in hostserv
  981. type VHostInfo struct {
  982. ApprovedVHost string
  983. Enabled bool
  984. RequestedVHost string
  985. RejectedVHost string
  986. RejectionReason string
  987. LastRequestTime time.Time
  988. }
  989. // pair type, <VHostInfo, accountName>
  990. type PendingVHostRequest struct {
  991. VHostInfo
  992. Account string
  993. }
  994. // callback type implementing the actual business logic of vhost operations
  995. type vhostMunger func(input VHostInfo) (output VHostInfo, err error)
  996. func (am *AccountManager) VHostSet(account string, vhost string) (result VHostInfo, err error) {
  997. munger := func(input VHostInfo) (output VHostInfo, err error) {
  998. output = input
  999. output.Enabled = true
  1000. output.ApprovedVHost = vhost
  1001. return
  1002. }
  1003. return am.performVHostChange(account, munger)
  1004. }
  1005. func (am *AccountManager) VHostRequest(account string, vhost string) (result VHostInfo, err error) {
  1006. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1007. output = input
  1008. output.RequestedVHost = vhost
  1009. output.RejectedVHost = ""
  1010. output.RejectionReason = ""
  1011. output.LastRequestTime = time.Now().UTC()
  1012. return
  1013. }
  1014. return am.performVHostChange(account, munger)
  1015. }
  1016. func (am *AccountManager) VHostApprove(account string) (result VHostInfo, err error) {
  1017. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1018. output = input
  1019. output.Enabled = true
  1020. output.ApprovedVHost = input.RequestedVHost
  1021. output.RequestedVHost = ""
  1022. output.RejectionReason = ""
  1023. return
  1024. }
  1025. return am.performVHostChange(account, munger)
  1026. }
  1027. func (am *AccountManager) VHostReject(account string, reason string) (result VHostInfo, err error) {
  1028. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1029. output = input
  1030. output.RejectedVHost = output.RequestedVHost
  1031. output.RequestedVHost = ""
  1032. output.RejectionReason = reason
  1033. return
  1034. }
  1035. return am.performVHostChange(account, munger)
  1036. }
  1037. func (am *AccountManager) VHostSetEnabled(client *Client, enabled bool) (result VHostInfo, err error) {
  1038. munger := func(input VHostInfo) (output VHostInfo, err error) {
  1039. if input.ApprovedVHost == "" {
  1040. err = errNoVhost
  1041. return
  1042. }
  1043. output = input
  1044. output.Enabled = enabled
  1045. return
  1046. }
  1047. return am.performVHostChange(client.Account(), munger)
  1048. }
  1049. func (am *AccountManager) performVHostChange(account string, munger vhostMunger) (result VHostInfo, err error) {
  1050. account, err = CasefoldName(account)
  1051. if err != nil || account == "" {
  1052. err = errAccountDoesNotExist
  1053. return
  1054. }
  1055. am.vHostUpdateMutex.Lock()
  1056. defer am.vHostUpdateMutex.Unlock()
  1057. clientAccount, err := am.LoadAccount(account)
  1058. if err != nil {
  1059. err = errAccountDoesNotExist
  1060. return
  1061. } else if !clientAccount.Verified {
  1062. err = errAccountUnverified
  1063. return
  1064. }
  1065. result, err = munger(clientAccount.VHost)
  1066. if err != nil {
  1067. return
  1068. }
  1069. vhtext, err := json.Marshal(result)
  1070. if err != nil {
  1071. err = errAccountUpdateFailed
  1072. return
  1073. }
  1074. vhstr := string(vhtext)
  1075. key := fmt.Sprintf(keyAccountVHost, account)
  1076. queueKey := fmt.Sprintf(keyVHostQueueAcctToId, account)
  1077. err = am.server.store.Update(func(tx *buntdb.Tx) error {
  1078. if _, _, err := tx.Set(key, vhstr, nil); err != nil {
  1079. return err
  1080. }
  1081. // update request queue
  1082. if clientAccount.VHost.RequestedVHost == "" && result.RequestedVHost != "" {
  1083. id := atomic.AddUint64(&am.vhostRequestID, 1)
  1084. if _, _, err = tx.Set(queueKey, strconv.FormatUint(id, 10), nil); err != nil {
  1085. return err
  1086. }
  1087. atomic.AddUint64(&am.vhostRequestPendingCount, 1)
  1088. } else if clientAccount.VHost.RequestedVHost != "" && result.RequestedVHost == "" {
  1089. _, err = tx.Delete(queueKey)
  1090. am.decrementVHostQueueCount(account, err)
  1091. }
  1092. return nil
  1093. })
  1094. if err != nil {
  1095. err = errAccountUpdateFailed
  1096. return
  1097. }
  1098. am.applyVhostToClients(account, result)
  1099. return result, nil
  1100. }
  1101. // XXX annoying helper method for keeping the queue count in sync with the DB
  1102. // `err` is the buntdb error returned from deleting the queue key
  1103. func (am *AccountManager) decrementVHostQueueCount(account string, err error) {
  1104. if err == nil {
  1105. // successfully deleted a queue entry, do a 2's complement decrement:
  1106. atomic.AddUint64(&am.vhostRequestPendingCount, ^uint64(0))
  1107. } else if err != buntdb.ErrNotFound {
  1108. am.server.logger.Error("internal", "buntdb dequeue error", account, err.Error())
  1109. }
  1110. }
  1111. func (am *AccountManager) VHostListRequests(limit int) (requests []PendingVHostRequest, total int) {
  1112. am.vHostUpdateMutex.Lock()
  1113. defer am.vHostUpdateMutex.Unlock()
  1114. total = int(atomic.LoadUint64(&am.vhostRequestPendingCount))
  1115. prefix := fmt.Sprintf(keyVHostQueueAcctToId, "")
  1116. accounts := make([]string, 0, limit)
  1117. err := am.server.store.View(func(tx *buntdb.Tx) error {
  1118. return tx.Ascend(vhostRequestIdx, func(key, value string) bool {
  1119. accounts = append(accounts, strings.TrimPrefix(key, prefix))
  1120. return len(accounts) < limit
  1121. })
  1122. })
  1123. if err != nil {
  1124. am.server.logger.Error("internal", "couldn't traverse vhost queue", err.Error())
  1125. return
  1126. }
  1127. for _, account := range accounts {
  1128. accountInfo, err := am.LoadAccount(account)
  1129. if err == nil {
  1130. requests = append(requests, PendingVHostRequest{
  1131. Account: account,
  1132. VHostInfo: accountInfo.VHost,
  1133. })
  1134. } else {
  1135. am.server.logger.Error("internal", "corrupt account", account, err.Error())
  1136. }
  1137. }
  1138. return
  1139. }
  1140. func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) {
  1141. // if hostserv is disabled in config, then don't grant vhosts
  1142. // that were previously approved while it was enabled
  1143. if !am.server.AccountConfig().VHosts.Enabled {
  1144. return
  1145. }
  1146. vhost := ""
  1147. if info.Enabled {
  1148. vhost = info.ApprovedVHost
  1149. }
  1150. oldNickmask := client.NickMaskString()
  1151. updated := client.SetVHost(vhost)
  1152. if updated {
  1153. // TODO: doing I/O here is kind of a kludge
  1154. go client.sendChghost(oldNickmask, client.Hostname())
  1155. }
  1156. }
  1157. func (am *AccountManager) applyVhostToClients(account string, result VHostInfo) {
  1158. am.RLock()
  1159. clients := am.accountToClients[account]
  1160. am.RUnlock()
  1161. for _, client := range clients {
  1162. am.applyVHostInfo(client, result)
  1163. }
  1164. }
  1165. func (am *AccountManager) Login(client *Client, account ClientAccount) {
  1166. changed := client.SetAccountName(account.Name)
  1167. if !changed {
  1168. return
  1169. }
  1170. client.nickTimer.Touch(nil)
  1171. am.applyVHostInfo(client, account.VHost)
  1172. casefoldedAccount := client.Account()
  1173. am.Lock()
  1174. defer am.Unlock()
  1175. am.accountToClients[casefoldedAccount] = append(am.accountToClients[casefoldedAccount], client)
  1176. for _, client := range am.accountToClients[casefoldedAccount] {
  1177. client.SetAccountSettings(account.Settings)
  1178. }
  1179. }
  1180. func (am *AccountManager) Logout(client *Client) {
  1181. am.Lock()
  1182. defer am.Unlock()
  1183. casefoldedAccount := client.Account()
  1184. if casefoldedAccount == "" {
  1185. return
  1186. }
  1187. am.logoutOfAccount(client)
  1188. clients := am.accountToClients[casefoldedAccount]
  1189. if len(clients) <= 1 {
  1190. delete(am.accountToClients, casefoldedAccount)
  1191. return
  1192. }
  1193. remainingClients := make([]*Client, len(clients)-1)
  1194. remainingPos := 0
  1195. for currentPos := 0; currentPos < len(clients); currentPos++ {
  1196. if clients[currentPos] != client {
  1197. remainingClients[remainingPos] = clients[currentPos]
  1198. remainingPos++
  1199. }
  1200. }
  1201. am.accountToClients[casefoldedAccount] = remainingClients
  1202. }
  1203. var (
  1204. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  1205. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  1206. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte, *ResponseBuffer) bool{
  1207. "PLAIN": authPlainHandler,
  1208. "EXTERNAL": authExternalHandler,
  1209. }
  1210. )
  1211. // AccountCredentials stores the various methods for verifying accounts.
  1212. type AccountCredentials struct {
  1213. Version uint
  1214. PassphraseSalt []byte // legacy field, not used by v1 and later
  1215. PassphraseHash []byte
  1216. Certfps []string
  1217. }
  1218. func (ac *AccountCredentials) Empty() bool {
  1219. return len(ac.PassphraseHash) == 0 && len(ac.Certfps) == 0
  1220. }
  1221. // helper to assemble the serialized JSON for an account's credentials
  1222. func (ac *AccountCredentials) Serialize() (result string, err error) {
  1223. ac.Version = 1
  1224. credText, err := json.Marshal(*ac)
  1225. if err != nil {
  1226. return "", err
  1227. }
  1228. return string(credText), nil
  1229. }
  1230. func (ac *AccountCredentials) SetPassphrase(passphrase string, bcryptCost uint) (err error) {
  1231. if passphrase == "" {
  1232. ac.PassphraseHash = nil
  1233. return nil
  1234. }
  1235. if validatePassphrase(passphrase) != nil {
  1236. return errAccountBadPassphrase
  1237. }
  1238. ac.PassphraseHash, err = passwd.GenerateFromPassword([]byte(passphrase), int(bcryptCost))
  1239. if err != nil {
  1240. return errAccountBadPassphrase
  1241. }
  1242. return nil
  1243. }
  1244. func (ac *AccountCredentials) AddCertfp(certfp string) (err error) {
  1245. for _, current := range ac.Certfps {
  1246. if certfp == current {
  1247. return errNoop
  1248. }
  1249. }
  1250. if maxCertfpsPerAccount <= len(ac.Certfps) {
  1251. return errLimitExceeded
  1252. }
  1253. ac.Certfps = append(ac.Certfps, certfp)
  1254. return nil
  1255. }
  1256. func (ac *AccountCredentials) RemoveCertfp(certfp string) (err error) {
  1257. found := false
  1258. newList := make([]string, 0, len(ac.Certfps))
  1259. for _, current := range ac.Certfps {
  1260. if current == certfp {
  1261. found = true
  1262. } else {
  1263. newList = append(newList, current)
  1264. }
  1265. }
  1266. if !found {
  1267. // this is important because it prevents you from deleting someone else's
  1268. // fingerprint record
  1269. return errNoop
  1270. }
  1271. ac.Certfps = newList
  1272. return nil
  1273. }
  1274. type BouncerAllowedSetting int
  1275. const (
  1276. BouncerAllowedServerDefault BouncerAllowedSetting = iota
  1277. BouncerDisallowedByUser
  1278. BouncerAllowedByUser
  1279. )
  1280. // controls whether/when clients without event-playback support see fake
  1281. // PRIVMSGs for JOINs
  1282. type ReplayJoinsSetting uint
  1283. const (
  1284. ReplayJoinsCommandsOnly = iota // replay in HISTORY or CHATHISTORY output
  1285. ReplayJoinsAlways // replay in HISTORY, CHATHISTORY, or autoreplay
  1286. ReplayJoinsNever // never replay
  1287. )
  1288. func replayJoinsSettingFromString(str string) (result ReplayJoinsSetting, err error) {
  1289. switch strings.ToLower(str) {
  1290. case "commands-only":
  1291. result = ReplayJoinsCommandsOnly
  1292. case "always":
  1293. result = ReplayJoinsAlways
  1294. case "never":
  1295. result = ReplayJoinsNever
  1296. default:
  1297. err = errInvalidParams
  1298. }
  1299. return
  1300. }
  1301. type AccountSettings struct {
  1302. AutoreplayLines *int
  1303. NickEnforcement NickEnforcementMethod
  1304. AllowBouncer BouncerAllowedSetting
  1305. ReplayJoins ReplayJoinsSetting
  1306. }
  1307. // ClientAccount represents a user account.
  1308. type ClientAccount struct {
  1309. // Name of the account.
  1310. Name string
  1311. NameCasefolded string
  1312. RegisteredAt time.Time
  1313. Credentials AccountCredentials
  1314. Verified bool
  1315. AdditionalNicks []string
  1316. VHost VHostInfo
  1317. Settings AccountSettings
  1318. }
  1319. // convenience for passing around raw serialized account data
  1320. type rawClientAccount struct {
  1321. Name string
  1322. RegisteredAt string
  1323. Credentials string
  1324. Callback string
  1325. Verified bool
  1326. AdditionalNicks string
  1327. VHost string
  1328. Settings string
  1329. }
  1330. // logoutOfAccount logs the client out of their current account.
  1331. func (am *AccountManager) logoutOfAccount(client *Client) {
  1332. if client.Account() == "" {
  1333. // already logged out
  1334. return
  1335. }
  1336. client.SetAccountName("")
  1337. go client.nickTimer.Touch(nil)
  1338. // dispatch account-notify
  1339. // TODO: doing the I/O here is kind of a kludge, let's move this somewhere else
  1340. go func() {
  1341. for friend := range client.Friends(caps.AccountNotify) {
  1342. friend.Send(nil, client.NickMaskString(), "ACCOUNT", "*")
  1343. }
  1344. }()
  1345. }