Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

accounts.go 53KB

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