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.

nickserv.go 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/goshuirc/irc-go/ircfmt"
  11. "github.com/oragono/oragono/irc/passwd"
  12. "github.com/oragono/oragono/irc/sno"
  13. "github.com/tidwall/buntdb"
  14. )
  15. const nickservHelp = `NickServ lets you register and log into a user account.
  16. To register an account:
  17. /NS REGISTER username [password]
  18. Leave out [password] if you're registering using your client certificate fingerprint.
  19. To login to an account:
  20. /NS IDENTIFY [username password]
  21. Leave out [username password] to use your client certificate fingerprint. Otherwise,
  22. the given username and password will be used.`
  23. // extractParam extracts a parameter from the given string, returning the param and the rest of the string.
  24. func extractParam(line string) (string, string) {
  25. rawParams := strings.SplitN(strings.TrimSpace(line), " ", 2)
  26. param0 := rawParams[0]
  27. var param1 string
  28. if 1 < len(rawParams) {
  29. param1 = strings.TrimSpace(rawParams[1])
  30. }
  31. return param0, param1
  32. }
  33. // nickservNoticeHandler handles NOTICEs that NickServ receives.
  34. func (server *Server) nickservNoticeHandler(client *Client, message string) {
  35. // do nothing
  36. }
  37. // nickservPrivmsgHandler handles PRIVMSGs that NickServ receives.
  38. func (server *Server) nickservPrivmsgHandler(client *Client, message string) {
  39. command, params := extractParam(message)
  40. command = strings.ToLower(command)
  41. if command == "help" {
  42. for _, line := range strings.Split(nickservHelp, "\n") {
  43. client.Notice(line)
  44. }
  45. } else if command == "register" {
  46. // get params
  47. username, passphrase := extractParam(params)
  48. // fail out if we need to
  49. if username == "" {
  50. client.Notice(client.t("No username supplied"))
  51. return
  52. }
  53. certfp := client.certfp
  54. if passphrase == "" && certfp == "" {
  55. client.Notice(client.t("You need to either supply a passphrase or be connected via TLS with a client cert"))
  56. return
  57. }
  58. if !server.accountRegistration.Enabled {
  59. client.Notice(client.t("Account registration has been disabled"))
  60. return
  61. }
  62. if client.LoggedIntoAccount() {
  63. if server.accountRegistration.AllowMultiplePerConnection {
  64. client.LogoutOfAccount()
  65. } else {
  66. client.Notice(client.t("You're already logged into an account"))
  67. return
  68. }
  69. }
  70. // get and sanitise account name
  71. account := strings.TrimSpace(username)
  72. casefoldedAccount, err := CasefoldName(account)
  73. // probably don't need explicit check for "*" here... but let's do it anyway just to make sure
  74. if err != nil || username == "*" {
  75. client.Notice(client.t("Account name is not valid"))
  76. return
  77. }
  78. // check whether account exists
  79. // do it all in one write tx to prevent races
  80. err = server.store.Update(func(tx *buntdb.Tx) error {
  81. accountKey := fmt.Sprintf(keyAccountExists, casefoldedAccount)
  82. _, err := tx.Get(accountKey)
  83. if err != buntdb.ErrNotFound {
  84. //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
  85. client.Notice(client.t("Account already exists"))
  86. return errAccountCreation
  87. }
  88. registeredTimeKey := fmt.Sprintf(keyAccountRegTime, casefoldedAccount)
  89. tx.Set(accountKey, "1", nil)
  90. tx.Set(fmt.Sprintf(keyAccountName, casefoldedAccount), account, nil)
  91. tx.Set(registeredTimeKey, strconv.FormatInt(time.Now().Unix(), 10), nil)
  92. return nil
  93. })
  94. // account could not be created and relevant numerics have been dispatched, abort
  95. if err != nil {
  96. if err != errAccountCreation {
  97. client.Notice(client.t("Account registration failed"))
  98. }
  99. return
  100. }
  101. // store details
  102. err = server.store.Update(func(tx *buntdb.Tx) error {
  103. // certfp special lookup key
  104. if passphrase == "" {
  105. assembledKeyCertToAccount := fmt.Sprintf(keyCertToAccount, client.certfp)
  106. // make sure certfp doesn't already exist because that'd be silly
  107. _, err := tx.Get(assembledKeyCertToAccount)
  108. if err != buntdb.ErrNotFound {
  109. return errCertfpAlreadyExists
  110. }
  111. tx.Set(assembledKeyCertToAccount, casefoldedAccount, nil)
  112. }
  113. // make creds
  114. var creds AccountCredentials
  115. // always set passphrase salt
  116. creds.PassphraseSalt, err = passwd.NewSalt()
  117. if err != nil {
  118. return fmt.Errorf("Could not create passphrase salt: %s", err.Error())
  119. }
  120. if passphrase == "" {
  121. creds.Certificate = client.certfp
  122. } else {
  123. creds.PassphraseHash, err = server.passwords.GenerateFromPassword(creds.PassphraseSalt, passphrase)
  124. if err != nil {
  125. return fmt.Errorf("Could not hash password: %s", err)
  126. }
  127. }
  128. credText, err := json.Marshal(creds)
  129. if err != nil {
  130. return fmt.Errorf("Could not marshal creds: %s", err)
  131. }
  132. tx.Set(fmt.Sprintf(keyAccountCredentials, account), string(credText), nil)
  133. return nil
  134. })
  135. // details could not be stored and relevant numerics have been dispatched, abort
  136. if err != nil {
  137. errMsg := "Could not register"
  138. if err == errCertfpAlreadyExists {
  139. errMsg = "An account already exists for your certificate fingerprint"
  140. }
  141. client.Notice(errMsg)
  142. removeFailedAccRegisterData(server.store, casefoldedAccount)
  143. return
  144. }
  145. err = server.store.Update(func(tx *buntdb.Tx) error {
  146. tx.Set(fmt.Sprintf(keyAccountVerified, casefoldedAccount), "1", nil)
  147. // load acct info inside store tx
  148. account := ClientAccount{
  149. Name: username,
  150. RegisteredAt: time.Now(),
  151. Clients: []*Client{client},
  152. }
  153. //TODO(dan): Consider creating ircd-wide account adding/removing/affecting lock for protecting access to these sorts of variables
  154. server.accounts[casefoldedAccount] = &account
  155. client.account = &account
  156. client.Notice(client.t("Account created"))
  157. client.Send(nil, server.name, RPL_LOGGEDIN, client.nick, client.nickMaskString, account.Name, fmt.Sprintf(client.t("You are now logged in as %s"), account.Name))
  158. client.Send(nil, server.name, RPL_SASLSUCCESS, client.nick, client.t("Authentication successful"))
  159. 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))
  160. return nil
  161. })
  162. if err != nil {
  163. client.Notice(client.t("Account registration failed"))
  164. removeFailedAccRegisterData(server.store, casefoldedAccount)
  165. return
  166. }
  167. } else if command == "identify" {
  168. // fail out if we need to
  169. if !server.accountAuthenticationEnabled {
  170. client.Notice(client.t("Login has been disabled"))
  171. return
  172. }
  173. // try passphrase
  174. username, passphrase := extractParam(params)
  175. if username != "" && passphrase != "" {
  176. // keep it the same as in the ACC CREATE stage
  177. accountKey, err := CasefoldName(username)
  178. if err != nil {
  179. client.Notice(client.t("Could not login with your username/password"))
  180. return
  181. }
  182. // load and check acct data all in one update to prevent races.
  183. // as noted elsewhere, change to proper locking for Account type later probably
  184. var accountName string
  185. err = server.store.Update(func(tx *buntdb.Tx) error {
  186. // confirm account is verified
  187. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  188. if err != nil {
  189. return errSaslFail
  190. }
  191. creds, err := loadAccountCredentials(tx, accountKey)
  192. if err != nil {
  193. return err
  194. }
  195. // ensure creds are valid
  196. if len(creds.PassphraseHash) < 1 || len(creds.PassphraseSalt) < 1 || len(passphrase) < 1 {
  197. return errSaslFail
  198. }
  199. err = server.passwords.CompareHashAndPassword(creds.PassphraseHash, creds.PassphraseSalt, passphrase)
  200. // succeeded, load account info if necessary
  201. account, exists := server.accounts[accountKey]
  202. if !exists {
  203. account = loadAccount(server, tx, accountKey)
  204. }
  205. client.LoginToAccount(account)
  206. accountName = account.Name
  207. return err
  208. })
  209. if err == nil {
  210. client.Notice(fmt.Sprintf(client.t("You're now logged in as %s"), accountName))
  211. return
  212. }
  213. }
  214. // try certfp
  215. certfp := client.certfp
  216. if certfp != "" {
  217. var accountName string
  218. err := server.store.Update(func(tx *buntdb.Tx) error {
  219. // certfp lookup key
  220. accountKey, err := tx.Get(fmt.Sprintf(keyCertToAccount, certfp))
  221. if err != nil {
  222. return errSaslFail
  223. }
  224. // confirm account exists
  225. _, err = tx.Get(fmt.Sprintf(keyAccountExists, accountKey))
  226. if err != nil {
  227. return errSaslFail
  228. }
  229. // confirm account is verified
  230. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  231. if err != nil {
  232. return errSaslFail
  233. }
  234. // confirm the certfp in that account's credentials
  235. creds, err := loadAccountCredentials(tx, accountKey)
  236. if err != nil || creds.Certificate != client.certfp {
  237. return errSaslFail
  238. }
  239. // succeeded, load account info if necessary
  240. account, exists := server.accounts[accountKey]
  241. if !exists {
  242. account = loadAccount(server, tx, accountKey)
  243. }
  244. client.LoginToAccount(account)
  245. accountName = account.Name
  246. return nil
  247. })
  248. if err == nil {
  249. client.Notice(fmt.Sprintf(client.t("You're now logged in as %s"), accountName))
  250. return
  251. }
  252. }
  253. client.Notice(client.t("Could not login with your TLS certificate or supplied username/password"))
  254. } else {
  255. client.Notice(client.t("Command not recognised. To see the available commands, run /NS HELP"))
  256. }
  257. }