Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

accounts.go 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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.name, ERR_SASLABORTED, client.nick, "SASL authentication aborted")
  71. } else {
  72. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "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.name, "AUTHENTICATE", "+")
  87. } else {
  88. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "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.name, ERR_SASLTOOLONG, client.nick, "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.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Passphrase too long")
  105. client.saslInProgress = false
  106. client.saslMechanism = ""
  107. client.saslValue = ""
  108. return false
  109. }
  110. return false
  111. }
  112. if rawData != "+" {
  113. client.saslValue += rawData
  114. }
  115. var data []byte
  116. var err error
  117. if client.saslValue != "+" {
  118. data, err = base64.StdEncoding.DecodeString(client.saslValue)
  119. if err != nil {
  120. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Invalid b64 encoding")
  121. client.saslInProgress = false
  122. client.saslMechanism = ""
  123. client.saslValue = ""
  124. return false
  125. }
  126. }
  127. // call actual handler
  128. handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
  129. // like 100% not required, but it's good to be safe I guess
  130. if !handlerExists {
  131. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  132. client.saslInProgress = false
  133. client.saslMechanism = ""
  134. client.saslValue = ""
  135. return false
  136. }
  137. // sasl is being done now by the handler, so we empty the client's vars now
  138. client.saslInProgress = false
  139. client.saslMechanism = ""
  140. client.saslValue = ""
  141. return handler(server, client, client.saslMechanism, data)
  142. }
  143. // authPlainHandler parses the SASL PLAIN mechanism.
  144. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  145. splitValue := bytes.Split(value, []byte{'\000'})
  146. if len(splitValue) != 3 {
  147. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Invalid auth blob")
  148. return false
  149. }
  150. accountKey := string(splitValue[0])
  151. authzid := string(splitValue[1])
  152. if accountKey != authzid {
  153. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: authcid and authzid should be the same")
  154. return false
  155. }
  156. // keep it the same as in the REG CREATE stage
  157. accountKey, err := CasefoldName(accountKey)
  158. if err != nil {
  159. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Bad account name")
  160. return false
  161. }
  162. // load and check acct data all in one update to prevent races.
  163. // as noted elsewhere, change to proper locking for Account type later probably
  164. err = server.store.Update(func(tx *buntdb.Tx) error {
  165. creds, err := loadAccountCredentials(tx, accountKey)
  166. if err != nil {
  167. return err
  168. }
  169. // ensure creds are valid
  170. password := string(splitValue[2])
  171. if len(creds.PassphraseHash) < 1 || len(creds.PassphraseSalt) < 1 || len(password) < 1 {
  172. return errSaslFail
  173. }
  174. err = server.passwords.CompareHashAndPassword(creds.PassphraseHash, creds.PassphraseSalt, password)
  175. // succeeded, load account info if necessary
  176. account, exists := server.accounts[accountKey]
  177. if !exists {
  178. account = loadAccount(server, tx, accountKey)
  179. }
  180. account.Clients = append(account.Clients, client)
  181. client.account = account
  182. return err
  183. })
  184. if err != nil {
  185. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  186. return false
  187. }
  188. client.successfulSaslAuth()
  189. return false
  190. }
  191. // authExternalHandler parses the SASL EXTERNAL mechanism.
  192. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  193. if client.certfp == "" {
  194. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed, you are not connecting with a caertificate")
  195. return false
  196. }
  197. err := server.store.Update(func(tx *buntdb.Tx) error {
  198. // certfp lookup key
  199. accountKey, err := tx.Get(fmt.Sprintf(keyCertToAccount, client.certfp))
  200. if err != nil {
  201. return errSaslFail
  202. }
  203. // confirm account exists
  204. _, err = tx.Get(fmt.Sprintf(keyAccountExists, accountKey))
  205. if err != nil {
  206. return errSaslFail
  207. }
  208. // confirm the certfp in that account's credentials
  209. creds, err := loadAccountCredentials(tx, accountKey)
  210. if err != nil || creds.Certificate != client.certfp {
  211. return errSaslFail
  212. }
  213. // succeeded, load account info if necessary
  214. account, exists := server.accounts[accountKey]
  215. if !exists {
  216. account = loadAccount(server, tx, accountKey)
  217. }
  218. account.Clients = append(account.Clients, client)
  219. client.account = account
  220. return nil
  221. })
  222. if err != nil {
  223. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  224. return false
  225. }
  226. client.successfulSaslAuth()
  227. return false
  228. }
  229. // successfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
  230. func (c *Client) successfulSaslAuth() {
  231. c.Send(nil, c.server.name, RPL_LOGGEDIN, c.nick, c.nickMaskString, c.account.Name, fmt.Sprintf("You are now logged in as %s", c.account.Name))
  232. c.Send(nil, c.server.name, RPL_SASLSUCCESS, c.nick, "SASL authentication successful")
  233. // dispatch account-notify
  234. for friend := range c.Friends(AccountNotify) {
  235. friend.Send(nil, c.nickMaskString, "ACCOUNT", c.account.Name)
  236. }
  237. }