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

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