Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

accounts.go 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 !server.accountAuthenticationEnabled || 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. // let the SASL handler do its thing
  138. exiting := handler(server, client, client.saslMechanism, data)
  139. // wait 'til SASL is done before emptying the sasl vars
  140. client.saslInProgress = false
  141. client.saslMechanism = ""
  142. client.saslValue = ""
  143. return exiting
  144. }
  145. // authPlainHandler parses the SASL PLAIN mechanism.
  146. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  147. splitValue := bytes.Split(value, []byte{'\000'})
  148. var accountKey, authzid string
  149. if len(splitValue) == 3 {
  150. accountKey = string(splitValue[0])
  151. authzid = string(splitValue[1])
  152. if accountKey == "" {
  153. accountKey = authzid
  154. } else if accountKey != authzid {
  155. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: authcid and authzid should be the same")
  156. return false
  157. }
  158. } else {
  159. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Invalid auth blob")
  160. return false
  161. }
  162. // keep it the same as in the REG CREATE stage
  163. accountKey, err := CasefoldName(accountKey)
  164. if err != nil {
  165. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Bad account name")
  166. return false
  167. }
  168. // load and check acct data all in one update to prevent races.
  169. // as noted elsewhere, change to proper locking for Account type later probably
  170. err = server.store.Update(func(tx *buntdb.Tx) error {
  171. // confirm account is verified
  172. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  173. if err != nil {
  174. return errSaslFail
  175. }
  176. creds, err := loadAccountCredentials(tx, accountKey)
  177. if err != nil {
  178. return err
  179. }
  180. // ensure creds are valid
  181. password := string(splitValue[2])
  182. if len(creds.PassphraseHash) < 1 || len(creds.PassphraseSalt) < 1 || len(password) < 1 {
  183. return errSaslFail
  184. }
  185. err = server.passwords.CompareHashAndPassword(creds.PassphraseHash, creds.PassphraseSalt, password)
  186. // succeeded, load account info if necessary
  187. account, exists := server.accounts[accountKey]
  188. if !exists {
  189. account = loadAccount(server, tx, accountKey)
  190. }
  191. account.Clients = append(account.Clients, client)
  192. client.account = account
  193. return err
  194. })
  195. if err != nil {
  196. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  197. return false
  198. }
  199. client.successfulSaslAuth()
  200. return false
  201. }
  202. // authExternalHandler parses the SASL EXTERNAL mechanism.
  203. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  204. if client.certfp == "" {
  205. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed, you are not connecting with a caertificate")
  206. return false
  207. }
  208. err := server.store.Update(func(tx *buntdb.Tx) error {
  209. // certfp lookup key
  210. accountKey, err := tx.Get(fmt.Sprintf(keyCertToAccount, client.certfp))
  211. if err != nil {
  212. return errSaslFail
  213. }
  214. // confirm account exists
  215. _, err = tx.Get(fmt.Sprintf(keyAccountExists, accountKey))
  216. if err != nil {
  217. return errSaslFail
  218. }
  219. // confirm account is verified
  220. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  221. if err != nil {
  222. return errSaslFail
  223. }
  224. // confirm the certfp in that account's credentials
  225. creds, err := loadAccountCredentials(tx, accountKey)
  226. if err != nil || creds.Certificate != client.certfp {
  227. return errSaslFail
  228. }
  229. // succeeded, load account info if necessary
  230. account, exists := server.accounts[accountKey]
  231. if !exists {
  232. account = loadAccount(server, tx, accountKey)
  233. }
  234. account.Clients = append(account.Clients, client)
  235. client.account = account
  236. return nil
  237. })
  238. if err != nil {
  239. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  240. return false
  241. }
  242. client.successfulSaslAuth()
  243. return false
  244. }
  245. // successfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
  246. func (c *Client) successfulSaslAuth() {
  247. 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))
  248. c.Send(nil, c.server.name, RPL_SASLSUCCESS, c.nick, "SASL authentication successful")
  249. // dispatch account-notify
  250. for friend := range c.Friends(AccountNotify) {
  251. friend.Send(nil, c.nickMaskString, "ACCOUNT", c.account.Name)
  252. }
  253. }