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

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