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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. // clients can't reg new accounts if they're already logged in
  82. if client.account != nil {
  83. client.Send(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, "*", "You're already logged into an account")
  84. return false
  85. }
  86. // get and sanitise account name
  87. account := strings.TrimSpace(msg.Params[1])
  88. casefoldedAccount, err := CasefoldName(account)
  89. // probably don't need explicit check for "*" here... but let's do it anyway just to make sure
  90. if err != nil || msg.Params[1] == "*" {
  91. client.Send(nil, server.name, ERR_REG_UNSPECIFIED_ERROR, client.nick, account, "Account name is not valid")
  92. return false
  93. }
  94. // check whether account exists
  95. // do it all in one write tx to prevent races
  96. err = server.store.Update(func(tx *buntdb.Tx) error {
  97. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  98. _, err := tx.Get(accountKey)
  99. if err != buntdb.ErrNotFound {
  100. //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
  101. client.Send(nil, server.name, ERR_ACCOUNT_ALREADY_EXISTS, client.nick, account, "Account already exists")
  102. return errAccountCreation
  103. }
  104. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  105. tx.Set(accountKey, "1", nil)
  106. tx.Set(fmt.Sprintf(keyAccountName, casefoldedAccount), account, nil)
  107. tx.Set(registeredTimeKey, strconv.FormatInt(time.Now().Unix(), 10), nil)
  108. return nil
  109. })
  110. // account could not be created and relevant numerics have been dispatched, abort
  111. if err != nil {
  112. if err != errAccountCreation {
  113. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", "Could not register")
  114. log.Println("Could not save registration initial data:", err.Error())
  115. }
  116. return false
  117. }
  118. // account didn't already exist, continue with account creation and dispatching verification (if required)
  119. callback := strings.ToLower(msg.Params[2])
  120. var callbackNamespace, callbackValue string
  121. if callback == "*" {
  122. callbackNamespace = "*"
  123. } else if strings.Contains(callback, ":") {
  124. callbackValues := strings.SplitN(callback, ":", 2)
  125. callbackNamespace, callbackValue = callbackValues[0], callbackValues[1]
  126. } else {
  127. callbackNamespace = server.accountRegistration.EnabledCallbacks[0]
  128. callbackValue = callback
  129. }
  130. // ensure the callback namespace is valid
  131. // need to search callback list, maybe look at using a map later?
  132. var callbackValid bool
  133. for _, name := range server.accountRegistration.EnabledCallbacks {
  134. if callbackNamespace == name {
  135. callbackValid = true
  136. }
  137. }
  138. if !callbackValid {
  139. client.Send(nil, server.name, ERR_REG_INVALID_CALLBACK, client.nick, account, callbackNamespace, "Callback namespace is not supported")
  140. removeFailedAccRegisterData(server.store, casefoldedAccount)
  141. return false
  142. }
  143. // get credential type/value
  144. var credentialType, credentialValue string
  145. if len(msg.Params) > 4 {
  146. credentialType = strings.ToLower(msg.Params[3])
  147. credentialValue = msg.Params[4]
  148. } else if len(msg.Params) == 4 {
  149. credentialType = "passphrase" // default from the spec
  150. credentialValue = msg.Params[3]
  151. } else {
  152. client.Send(nil, server.name, ERR_NEEDMOREPARAMS, client.nick, msg.Command, "Not enough parameters")
  153. removeFailedAccRegisterData(server.store, casefoldedAccount)
  154. return false
  155. }
  156. // ensure the credential type is valid
  157. var credentialValid bool
  158. for _, name := range server.accountRegistration.EnabledCredentialTypes {
  159. if credentialType == name {
  160. credentialValid = true
  161. }
  162. }
  163. if credentialType == "certfp" && client.certfp == "" {
  164. client.Send(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, "You are not using a TLS certificate")
  165. removeFailedAccRegisterData(server.store, casefoldedAccount)
  166. return false
  167. }
  168. if !credentialValid {
  169. client.Send(nil, server.name, ERR_REG_INVALID_CRED_TYPE, client.nick, credentialType, callbackNamespace, "Credential type is not supported")
  170. removeFailedAccRegisterData(server.store, casefoldedAccount)
  171. return false
  172. }
  173. // store details
  174. err = server.store.Update(func(tx *buntdb.Tx) error {
  175. // certfp special lookup key
  176. if credentialType == "certfp" {
  177. assembledKeyCertToAccount := fmt.Sprintf(keyCertToAccount, client.certfp)
  178. // make sure certfp doesn't already exist because that'd be silly
  179. _, err := tx.Get(assembledKeyCertToAccount)
  180. if err != buntdb.ErrNotFound {
  181. return errCertfpAlreadyExists
  182. }
  183. tx.Set(assembledKeyCertToAccount, casefoldedAccount, nil)
  184. }
  185. // make creds
  186. var creds AccountCredentials
  187. // always set passphrase salt
  188. creds.PassphraseSalt, err = NewSalt()
  189. if err != nil {
  190. return fmt.Errorf("Could not create passphrase salt: %s", err.Error())
  191. }
  192. if credentialType == "certfp" {
  193. creds.Certificate = client.certfp
  194. } else if credentialType == "passphrase" {
  195. creds.PassphraseHash, err = server.passwords.GenerateFromPassword(creds.PassphraseSalt, credentialValue)
  196. if err != nil {
  197. return fmt.Errorf("Could not hash password: %s", err)
  198. }
  199. }
  200. credText, err := json.Marshal(creds)
  201. if err != nil {
  202. return fmt.Errorf("Could not marshal creds: %s", err)
  203. }
  204. tx.Set(fmt.Sprintf(keyAccountCredentials, account), string(credText), nil)
  205. return nil
  206. })
  207. // details could not be stored and relevant numerics have been dispatched, abort
  208. if err != nil {
  209. errMsg := "Could not register"
  210. if err == errCertfpAlreadyExists {
  211. errMsg = "An account already exists for your certificate fingerprint"
  212. }
  213. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", errMsg)
  214. log.Println("Could not save registration creds:", err.Error())
  215. removeFailedAccRegisterData(server.store, casefoldedAccount)
  216. return false
  217. }
  218. // automatically complete registration
  219. if callbackNamespace == "*" {
  220. err = server.store.Update(func(tx *buntdb.Tx) error {
  221. tx.Set(fmt.Sprintf(keyAccountVerified, casefoldedAccount), "1", nil)
  222. // load acct info inside store tx
  223. account := ClientAccount{
  224. Name: strings.TrimSpace(msg.Params[1]),
  225. RegisteredAt: time.Now(),
  226. Clients: []*Client{client},
  227. }
  228. //TODO(dan): Consider creating ircd-wide account adding/removing/affecting lock for protecting access to these sorts of variables
  229. server.accounts[casefoldedAccount] = &account
  230. client.account = &account
  231. client.Send(nil, server.name, RPL_REGISTRATION_SUCCESS, client.nick, account.Name, "Account created")
  232. client.Send(nil, server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account.Name, fmt.Sprintf("You are now logged in as %s", account.Name))
  233. client.Send(nil, server.name, RPL_SASLSUCCESS, client.nick, "Authentication successful")
  234. 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))
  235. return nil
  236. })
  237. if err != nil {
  238. client.Send(nil, server.name, ERR_UNKNOWNERROR, client.nick, "ACC", "REGISTER", "Could not register")
  239. log.Println("Could not save verification confirmation (*):", err.Error())
  240. removeFailedAccRegisterData(server.store, casefoldedAccount)
  241. return false
  242. }
  243. return false
  244. }
  245. // dispatch callback
  246. client.Notice(fmt.Sprintf("We should dispatch a real callback here to %s:%s", callbackNamespace, callbackValue))
  247. return false
  248. }