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.

accountreg.go 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. "errors"
  7. "fmt"
  8. "log"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/goshuirc/irc-go/ircfmt"
  13. "github.com/goshuirc/irc-go/ircmsg"
  14. "github.com/oragono/oragono/irc/sno"
  15. "github.com/tidwall/buntdb"
  16. )
  17. var (
  18. errAccountCreation = errors.New("Account could not be created")
  19. errCertfpAlreadyExists = errors.New("An account already exists with your certificate")
  20. )
  21. // AccountRegistration manages the registration of accounts.
  22. type AccountRegistration struct {
  23. Enabled bool
  24. EnabledCallbacks []string
  25. EnabledCredentialTypes []string
  26. }
  27. // AccountCredentials stores the various methods for verifying accounts.
  28. type AccountCredentials struct {
  29. PassphraseSalt []byte
  30. PassphraseHash []byte
  31. Certificate string // fingerprint
  32. }
  33. // NewAccountRegistration returns a new AccountRegistration, configured correctly.
  34. func NewAccountRegistration(config AccountRegistrationConfig) (accountReg AccountRegistration) {
  35. if config.Enabled {
  36. accountReg.Enabled = true
  37. for _, name := range config.EnabledCallbacks {
  38. // we store "none" as "*" internally
  39. if name == "none" {
  40. name = "*"
  41. }
  42. accountReg.EnabledCallbacks = append(accountReg.EnabledCallbacks, name)
  43. }
  44. // no need to make this configurable, right now at least
  45. accountReg.EnabledCredentialTypes = []string{
  46. "passphrase",
  47. "certfp",
  48. }
  49. }
  50. return accountReg
  51. }
  52. // accHandler parses the ACC command.
  53. func accHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  54. subcommand := strings.ToLower(msg.Params[0])
  55. if subcommand == "register" {
  56. return accRegisterHandler(server, client, msg)
  57. } else if subcommand == "verify" {
  58. client.Notice("VERIFY is not yet implemented")
  59. } else {
  60. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", msg.Params[0], "Unknown subcommand")
  61. }
  62. return false
  63. }
  64. // removeFailedAccRegisterData removes the data created by ACC REGISTER if the account creation fails early.
  65. func removeFailedAccRegisterData(store *buntdb.DB, account string) {
  66. // error is ignored here, we can't do much about it anyways
  67. store.Update(func(tx *buntdb.Tx) error {
  68. tx.Delete(fmt.Sprintf(keyAccountExists, account))
  69. tx.Delete(fmt.Sprintf(keyAccountRegTime, account))
  70. tx.Delete(fmt.Sprintf(keyAccountCredentials, account))
  71. return nil
  72. })
  73. }
  74. // accRegisterHandler parses the ACC REGISTER command.
  75. func accRegisterHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  76. // make sure reg is enabled
  77. if !server.accountRegistration.Enabled {
  78. client.Send(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, "*", "Account registration is disabled")
  79. return false
  80. }
  81. // get and sanitise account name
  82. account := strings.TrimSpace(msg.Params[1])
  83. casefoldedAccount, err := CasefoldName(account)
  84. // probably don't need explicit check for "*" here... but let's do it anyway just to make sure
  85. if err != nil || msg.Params[1] == "*" {
  86. client.Send(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, account, "Account name is not valid")
  87. return false
  88. }
  89. // check whether account exists
  90. // do it all in one write tx to prevent races
  91. err = server.store.Update(func(tx *buntdb.Tx) error {
  92. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  93. _, err := tx.Get(accountKey)
  94. if err != buntdb.ErrNotFound {
  95. //TODO(dan): if account verified key doesn't exist account is not verified, calc the maximum time without verification and expire and continue if need be
  96. client.Send(nil, server.name, ERR_ACCOUNT_ALREADY_EXISTS, client.nick, account, "Account already exists")
  97. return errAccountCreation
  98. }
  99. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  100. tx.Set(accountKey, "1", nil)
  101. tx.Set(fmt.Sprintf(keyAccountName, casefoldedAccount), account, nil)
  102. tx.Set(registeredTimeKey, strconv.FormatInt(time.Now().Unix(), 10), nil)
  103. return nil
  104. })
  105. // account could not be created and relevant numerics have been dispatched, abort
  106. if err != nil {
  107. if err != errAccountCreation {
  108. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", "Could not register")
  109. log.Println("Could not save registration initial data:", err.Error())
  110. }
  111. return false
  112. }
  113. // account didn't already exist, continue with account creation and dispatching verification (if required)
  114. callback := strings.ToLower(msg.Params[2])
  115. var callbackNamespace, callbackValue string
  116. if callback == "*" {
  117. callbackNamespace = "*"
  118. } else if strings.Contains(callback, ":") {
  119. callbackValues := strings.SplitN(callback, ":", 2)
  120. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  121. } else {
  122. callbackNamespace = server.accountRegistration.EnabledCallbacks[0]
  123. callbackValue = callback
  124. }
  125. // ensure the callback namespace is valid
  126. // need to search callback list, maybe look at using a map later?
  127. var callbackValid bool
  128. for _, name := range server.accountRegistration.EnabledCallbacks {
  129. if callbackNamespace == name {
  130. callbackValid = true
  131. }
  132. }
  133. if !callbackValid {
  134. client.Send(nil, server.name, ERR_REG_INVALID_CALLBACK, client.nick, account, callbackNamespace, "Callback namespace is not supported")
  135. removeFailedAccRegisterData(server.store, casefoldedAccount)
  136. return false
  137. }
  138. // get credential type/value
  139. var credentialType, credentialValue string
  140. if len(msg.Params) > 4 {
  141. credentialType = strings.ToLower(msg.Params[3])
  142. credentialValue = msg.Params[4]
  143. } else if len(msg.Params) == 4 {
  144. credentialType = "passphrase" // default from the spec
  145. credentialValue = msg.Params[3]
  146. } else {
  147. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  148. removeFailedAccRegisterData(server.store, casefoldedAccount)
  149. return false
  150. }
  151. // ensure the credential type is valid
  152. var credentialValid bool
  153. for _, name := range server.accountRegistration.EnabledCredentialTypes {
  154. if credentialType == name {
  155. credentialValid = true
  156. }
  157. }
  158. if credentialType == "certfp" && client.certfp == "" {
  159. client.Send(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, "You are not using a TLS certificate")
  160. removeFailedAccRegisterData(server.store, casefoldedAccount)
  161. return false
  162. }
  163. if !credentialValid {
  164. client.Send(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, "Credential type is not supported")
  165. removeFailedAccRegisterData(server.store, casefoldedAccount)
  166. return false
  167. }
  168. // store details
  169. err = server.store.Update(func(tx *buntdb.Tx) error {
  170. // certfp special lookup key
  171. if credentialType == "certfp" {
  172. assembledKeyCertToAccount := fmt.Sprintf(keyCertToAccount, client.certfp)
  173. // make sure certfp doesn't already exist because that'd be silly
  174. _, err := tx.Get(assembledKeyCertToAccount)
  175. if err != buntdb.ErrNotFound {
  176. return errCertfpAlreadyExists
  177. }
  178. tx.Set(assembledKeyCertToAccount, casefoldedAccount, nil)
  179. }
  180. // make creds
  181. var creds AccountCredentials
  182. // always set passphrase salt
  183. creds.PassphraseSalt, err = NewSalt()
  184. if err != nil {
  185. return fmt.Errorf("Could not create passphrase salt: %s", err.Error())
  186. }
  187. if credentialType == "certfp" {
  188. creds.Certificate = client.certfp
  189. } else if credentialType == "passphrase" {
  190. creds.PassphraseHash, err = server.passwords.GenerateFromPassword(creds.PassphraseSalt, credentialValue)
  191. if err != nil {
  192. return fmt.Errorf("Could not hash password: %s", err)
  193. }
  194. }
  195. credText, err := json.Marshal(creds)
  196. if err != nil {
  197. return fmt.Errorf("Could not marshal creds: %s", err)
  198. }
  199. tx.Set(fmt.Sprintf(keyAccountCredentials, account), string(credText), nil)
  200. return nil
  201. })
  202. // details could not be stored and relevant numerics have been dispatched, abort
  203. if err != nil {
  204. errMsg := "Could not register"
  205. if err == errCertfpAlreadyExists {
  206. errMsg = "An account already exists for your certificate fingerprint"
  207. }
  208. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", errMsg)
  209. log.Println("Could not save registration creds:", err.Error())
  210. removeFailedAccRegisterData(server.store, casefoldedAccount)
  211. return false
  212. }
  213. // automatically complete registration
  214. if callbackNamespace == "*" {
  215. err = server.store.Update(func(tx *buntdb.Tx) error {
  216. tx.Set(fmt.Sprintf(keyAccountVerified, casefoldedAccount), "1", nil)
  217. // load acct info inside store tx
  218. account := ClientAccount{
  219. Name: strings.TrimSpace(msg.Params[1]),
  220. RegisteredAt: time.Now(),
  221. Clients: []*Client{client},
  222. }
  223. //TODO(dan): Consider creating ircd-wide account adding/removing/affecting lock for protecting access to these sorts of variables
  224. server.accounts[casefoldedAccount] = &account
  225. client.account = &account
  226. client.Send(nil, server.name, RPL_REGISTRATION_SUCCESS, client.nick, account.Name, "Account created")
  227. client.Send(nil, server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account.Name, fmt.Sprintf("You are now logged in as %s", account.Name))
  228. client.Send(nil, server.name, RPL_SASLSUCCESS, client.nick, "Authentication successful")
  229. server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Account registered $c[grey][$r%s$c[grey]] by $c[grey][$r%s$c[grey]]"), account.Name, client.nickMaskString))
  230. return nil
  231. })
  232. if err != nil {
  233. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", "Could not register")
  234. log.Println("Could not save verification confirmation (*):", err.Error())
  235. removeFailedAccRegisterData(server.store, casefoldedAccount)
  236. return false
  237. }
  238. return false
  239. }
  240. // dispatch callback
  241. client.Notice(fmt.Sprintf("We should dispatch a real callback here to %s:%s", callbackNamespace, callbackValue))
  242. return false
  243. }