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

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