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.

accounts.go 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright (c) 2016- Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "bytes"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/DanielOaks/girc-go/ircmsg"
  14. "github.com/tidwall/buntdb"
  15. )
  16. var (
  17. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  18. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  19. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte) bool{
  20. "PLAIN": authPlainHandler,
  21. "EXTERNAL": authExternalHandler,
  22. }
  23. // NoAccount is a placeholder which means that the user is not logged into an account.
  24. NoAccount = ClientAccount{
  25. Name: "*", // * is used until actual account name is set
  26. }
  27. // generic sasl fail error
  28. errSaslFail = errors.New("SASL failed")
  29. )
  30. // ClientAccount represents a user account.
  31. type ClientAccount struct {
  32. // Name of the account.
  33. Name string
  34. // RegisteredAt represents the time that the account was registered.
  35. RegisteredAt time.Time
  36. // Clients that are currently logged into this account (useful for notifications).
  37. Clients []*Client
  38. }
  39. // loadAccountCredentials loads an account's credentials from the store.
  40. func loadAccountCredentials(tx *buntdb.Tx, accountKey string) (*AccountCredentials, error) {
  41. credText, err := tx.Get(fmt.Sprintf(keyAccountCredentials, accountKey))
  42. if err != nil {
  43. return nil, err
  44. }
  45. var creds AccountCredentials
  46. err = json.Unmarshal([]byte(credText), &creds)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &creds, nil
  51. }
  52. // loadAccount loads an account from the store, note that the account must actually exist.
  53. func loadAccount(server *Server, tx *buntdb.Tx, accountKey string) *ClientAccount {
  54. name, _ := tx.Get(fmt.Sprintf(keyAccountName, accountKey))
  55. regTime, _ := tx.Get(fmt.Sprintf(keyAccountRegTime, accountKey))
  56. regTimeInt, _ := strconv.ParseInt(regTime, 10, 64)
  57. accountInfo := ClientAccount{
  58. Name: name,
  59. RegisteredAt: time.Unix(regTimeInt, 0),
  60. Clients: []*Client{},
  61. }
  62. server.accounts[accountKey] = &accountInfo
  63. return &accountInfo
  64. }
  65. // authenticateHandler parses the AUTHENTICATE command (for SASL authentication).
  66. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  67. // sasl abort
  68. if len(msg.Params) == 1 && msg.Params[0] == "*" {
  69. if client.saslInProgress {
  70. client.Send(nil, server.nameString, ERR_SASLABORTED, client.nickString, "SASL authentication aborted")
  71. } else {
  72. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed")
  73. }
  74. client.saslInProgress = false
  75. client.saslMechanism = ""
  76. client.saslValue = ""
  77. return false
  78. }
  79. // start new sasl session
  80. if !client.saslInProgress {
  81. mechanism := strings.ToUpper(msg.Params[0])
  82. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  83. if mechanismIsEnabled {
  84. client.saslInProgress = true
  85. client.saslMechanism = mechanism
  86. client.Send(nil, server.nameString, "AUTHENTICATE", "+")
  87. } else {
  88. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed")
  89. }
  90. return false
  91. }
  92. // continue existing sasl session
  93. rawData := msg.Params[0]
  94. if len(rawData) > 400 {
  95. client.Send(nil, server.nameString, ERR_SASLTOOLONG, client.nickString, "SASL message too long")
  96. client.saslInProgress = false
  97. client.saslMechanism = ""
  98. client.saslValue = ""
  99. return false
  100. } else if len(rawData) == 400 {
  101. client.saslValue += rawData
  102. // allow 4 'continuation' lines before rejecting for length
  103. if len(client.saslValue) > 400*4 {
  104. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed: Passphrase too long")
  105. client.saslInProgress = false
  106. client.saslMechanism = ""
  107. client.saslValue = ""
  108. return false
  109. }
  110. return false
  111. } else if len(client.saslValue) > 0 {
  112. client.saslValue += rawData
  113. return false
  114. }
  115. client.saslValue += rawData
  116. var data []byte
  117. var err error
  118. if client.saslValue != "+" {
  119. data, err = base64.StdEncoding.DecodeString(client.saslValue)
  120. if err != nil {
  121. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed: Invalid b64 encoding")
  122. client.saslInProgress = false
  123. client.saslMechanism = ""
  124. client.saslValue = ""
  125. return false
  126. }
  127. }
  128. // call actual handler
  129. handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
  130. // like 100% not required, but it's good to be safe I guess
  131. if !handlerExists {
  132. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed")
  133. client.saslInProgress = false
  134. client.saslMechanism = ""
  135. client.saslValue = ""
  136. return false
  137. }
  138. // sasl is being done now by the handler, so we empty the client's vars now
  139. client.saslInProgress = false
  140. client.saslMechanism = ""
  141. client.saslValue = ""
  142. return handler(server, client, client.saslMechanism, data)
  143. }
  144. // authPlainHandler parses the SASL PLAIN mechanism.
  145. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  146. splitValue := bytes.Split(value, []byte{'\000'})
  147. if len(splitValue) != 3 {
  148. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed: Invalid auth blob")
  149. return false
  150. }
  151. accountKey := string(splitValue[0])
  152. authzid := string(splitValue[1])
  153. if accountKey != authzid {
  154. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed: authcid and authzid should be the same")
  155. return false
  156. }
  157. // casefolding, rough for now bit will improve later.
  158. // keep it the same as in the REG CREATE stage
  159. accountKey = NewName(accountKey).String()
  160. // load and check acct data all in one update to prevent races.
  161. // as noted elsewhere, change to proper locking for Account type later probably
  162. err := server.store.Update(func(tx *buntdb.Tx) error {
  163. creds, err := loadAccountCredentials(tx, accountKey)
  164. if err != nil {
  165. return err
  166. }
  167. // ensure creds are valid
  168. password := string(splitValue[2])
  169. if len(creds.PassphraseHash) < 1 || len(creds.PassphraseSalt) < 1 || len(password) < 1 {
  170. return errSaslFail
  171. }
  172. err = server.passwords.CompareHashAndPassword(creds.PassphraseHash, creds.PassphraseSalt, password)
  173. // succeeded, load account info if necessary
  174. account, exists := server.accounts[accountKey]
  175. if !exists {
  176. account = loadAccount(server, tx, accountKey)
  177. }
  178. account.Clients = append(account.Clients, client)
  179. client.account = account
  180. return err
  181. })
  182. if err != nil {
  183. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed")
  184. return false
  185. }
  186. client.Send(nil, server.nameString, RPL_LOGGEDIN, client.nickString, client.nickMaskString, client.account.Name, fmt.Sprintf("You are now logged in as %s", client.account.Name))
  187. client.Send(nil, server.nameString, RPL_SASLSUCCESS, client.nickString, "SASL authentication successful")
  188. return false
  189. }
  190. // authExternalHandler parses the SASL EXTERNAL mechanism.
  191. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  192. if client.certfp == "" {
  193. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed, you are not connecting with a certificate")
  194. return false
  195. }
  196. err := server.store.Update(func(tx *buntdb.Tx) error {
  197. // certfp lookup key
  198. accountKey, err := tx.Get(fmt.Sprintf(keyCertToAccount, client.certfp))
  199. if err != nil {
  200. return errSaslFail
  201. }
  202. // confirm account exists
  203. _, err = tx.Get(fmt.Sprintf(keyAccountExists, accountKey))
  204. if err != nil {
  205. return errSaslFail
  206. }
  207. // confirm the certfp in that account's credentials
  208. creds, err := loadAccountCredentials(tx, accountKey)
  209. if err != nil || creds.Certificate != client.certfp {
  210. return errSaslFail
  211. }
  212. // succeeded, load account info if necessary
  213. account, exists := server.accounts[accountKey]
  214. if !exists {
  215. account = loadAccount(server, tx, accountKey)
  216. }
  217. account.Clients = append(account.Clients, client)
  218. client.account = account
  219. return nil
  220. })
  221. if err != nil {
  222. client.Send(nil, server.nameString, ERR_SASLFAIL, client.nickString, "SASL authentication failed")
  223. return false
  224. }
  225. client.Send(nil, server.nameString, RPL_LOGGEDIN, client.nickString, client.nickMaskString, client.account.Name, fmt.Sprintf("You are now logged in as %s", client.account.Name))
  226. client.Send(nil, server.nameString, RPL_SASLSUCCESS, client.nickString, "SASL authentication successful")
  227. return false
  228. }