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.

registration.go 9.5KB

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