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 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright (c) 2016-2017 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. const (
  17. keyAccountExists = "account.exists %s"
  18. keyAccountVerified = "account.verified %s"
  19. keyAccountName = "account.name %s" // stores the 'preferred name' of the account, not casemapped
  20. keyAccountRegTime = "account.registered.time %s"
  21. keyAccountCredentials = "account.credentials %s"
  22. keyCertToAccount = "account.creds.certfp %s"
  23. )
  24. var (
  25. // EnabledSaslMechanisms contains the SASL mechanisms that exist and that we support.
  26. // This can be moved to some other data structure/place if we need to load/unload mechs later.
  27. EnabledSaslMechanisms = map[string]func(*Server, *Client, string, []byte) bool{
  28. "PLAIN": authPlainHandler,
  29. "EXTERNAL": authExternalHandler,
  30. }
  31. // NoAccount is a placeholder which means that the user is not logged into an account.
  32. NoAccount = ClientAccount{
  33. Name: "*", // * is used until actual account name is set
  34. }
  35. // generic sasl fail error
  36. errSaslFail = errors.New("SASL failed")
  37. )
  38. // ClientAccount represents a user account.
  39. type ClientAccount struct {
  40. // Name of the account.
  41. Name string
  42. // RegisteredAt represents the time that the account was registered.
  43. RegisteredAt time.Time
  44. // Clients that are currently logged into this account (useful for notifications).
  45. Clients []*Client
  46. }
  47. // loadAccountCredentials loads an account's credentials from the store.
  48. func loadAccountCredentials(tx *buntdb.Tx, accountKey string) (*AccountCredentials, error) {
  49. credText, err := tx.Get(fmt.Sprintf(keyAccountCredentials, accountKey))
  50. if err != nil {
  51. return nil, err
  52. }
  53. var creds AccountCredentials
  54. err = json.Unmarshal([]byte(credText), &creds)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return &creds, nil
  59. }
  60. // loadAccount loads an account from the store, note that the account must actually exist.
  61. func loadAccount(server *Server, tx *buntdb.Tx, accountKey string) *ClientAccount {
  62. name, _ := tx.Get(fmt.Sprintf(keyAccountName, accountKey))
  63. regTime, _ := tx.Get(fmt.Sprintf(keyAccountRegTime, accountKey))
  64. regTimeInt, _ := strconv.ParseInt(regTime, 10, 64)
  65. accountInfo := ClientAccount{
  66. Name: name,
  67. RegisteredAt: time.Unix(regTimeInt, 0),
  68. Clients: []*Client{},
  69. }
  70. server.accounts[accountKey] = &accountInfo
  71. return &accountInfo
  72. }
  73. // authenticateHandler parses the AUTHENTICATE command (for SASL authentication).
  74. func authenticateHandler(server *Server, client *Client, msg ircmsg.IrcMessage) bool {
  75. // sasl abort
  76. if !server.accountAuthenticationEnabled || len(msg.Params) == 1 && msg.Params[0] == "*" {
  77. if client.saslInProgress {
  78. client.Send(nil, server.name, ERR_SASLABORTED, client.nick, "SASL authentication aborted")
  79. } else {
  80. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  81. }
  82. client.saslInProgress = false
  83. client.saslMechanism = ""
  84. client.saslValue = ""
  85. return false
  86. }
  87. // start new sasl session
  88. if !client.saslInProgress {
  89. mechanism := strings.ToUpper(msg.Params[0])
  90. _, mechanismIsEnabled := EnabledSaslMechanisms[mechanism]
  91. if mechanismIsEnabled {
  92. client.saslInProgress = true
  93. client.saslMechanism = mechanism
  94. client.Send(nil, server.name, "AUTHENTICATE", "+")
  95. } else {
  96. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  97. }
  98. return false
  99. }
  100. // continue existing sasl session
  101. rawData := msg.Params[0]
  102. if len(rawData) > 400 {
  103. client.Send(nil, server.name, ERR_SASLTOOLONG, client.nick, "SASL message too long")
  104. client.saslInProgress = false
  105. client.saslMechanism = ""
  106. client.saslValue = ""
  107. return false
  108. } else if len(rawData) == 400 {
  109. client.saslValue += rawData
  110. // allow 4 'continuation' lines before rejecting for length
  111. if len(client.saslValue) > 400*4 {
  112. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Passphrase too long")
  113. client.saslInProgress = false
  114. client.saslMechanism = ""
  115. client.saslValue = ""
  116. return false
  117. }
  118. return false
  119. }
  120. if rawData != "+" {
  121. client.saslValue += rawData
  122. }
  123. var data []byte
  124. var err error
  125. if client.saslValue != "+" {
  126. data, err = base64.StdEncoding.DecodeString(client.saslValue)
  127. if err != nil {
  128. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Invalid b64 encoding")
  129. client.saslInProgress = false
  130. client.saslMechanism = ""
  131. client.saslValue = ""
  132. return false
  133. }
  134. }
  135. // call actual handler
  136. handler, handlerExists := EnabledSaslMechanisms[client.saslMechanism]
  137. // like 100% not required, but it's good to be safe I guess
  138. if !handlerExists {
  139. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  140. client.saslInProgress = false
  141. client.saslMechanism = ""
  142. client.saslValue = ""
  143. return false
  144. }
  145. // let the SASL handler do its thing
  146. exiting := handler(server, client, client.saslMechanism, data)
  147. // wait 'til SASL is done before emptying the sasl vars
  148. client.saslInProgress = false
  149. client.saslMechanism = ""
  150. client.saslValue = ""
  151. return exiting
  152. }
  153. // authPlainHandler parses the SASL PLAIN mechanism.
  154. func authPlainHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  155. splitValue := bytes.Split(value, []byte{'\000'})
  156. var accountKey, authzid string
  157. if len(splitValue) == 3 {
  158. accountKey = string(splitValue[0])
  159. authzid = string(splitValue[1])
  160. if accountKey == "" {
  161. accountKey = authzid
  162. } else if accountKey != authzid {
  163. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: authcid and authzid should be the same")
  164. return false
  165. }
  166. } else {
  167. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Invalid auth blob")
  168. return false
  169. }
  170. // keep it the same as in the REG CREATE stage
  171. accountKey, err := CasefoldName(accountKey)
  172. if err != nil {
  173. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed: Bad account name")
  174. return false
  175. }
  176. // load and check acct data all in one update to prevent races.
  177. // as noted elsewhere, change to proper locking for Account type later probably
  178. err = server.store.Update(func(tx *buntdb.Tx) error {
  179. // confirm account is verified
  180. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  181. if err != nil {
  182. return errSaslFail
  183. }
  184. creds, err := loadAccountCredentials(tx, accountKey)
  185. if err != nil {
  186. return err
  187. }
  188. // ensure creds are valid
  189. password := string(splitValue[2])
  190. if len(creds.PassphraseHash) < 1 || len(creds.PassphraseSalt) < 1 || len(password) < 1 {
  191. return errSaslFail
  192. }
  193. err = server.passwords.CompareHashAndPassword(creds.PassphraseHash, creds.PassphraseSalt, password)
  194. // succeeded, load account info if necessary
  195. account, exists := server.accounts[accountKey]
  196. if !exists {
  197. account = loadAccount(server, tx, accountKey)
  198. }
  199. client.LoginToAccount(account)
  200. return err
  201. })
  202. if err != nil {
  203. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  204. return false
  205. }
  206. client.successfulSaslAuth()
  207. return false
  208. }
  209. // LoginToAccount logs the client into the given account.
  210. func (client *Client) LoginToAccount(account *ClientAccount) {
  211. if client.account == account {
  212. // already logged into this acct, no changing necessary
  213. return
  214. } else if client.account != nil {
  215. // logout of existing acct
  216. var newClientAccounts []*Client
  217. for _, c := range account.Clients {
  218. if c != client {
  219. newClientAccounts = append(newClientAccounts, c)
  220. }
  221. }
  222. account.Clients = newClientAccounts
  223. }
  224. account.Clients = append(account.Clients, client)
  225. client.account = account
  226. }
  227. // authExternalHandler parses the SASL EXTERNAL mechanism.
  228. func authExternalHandler(server *Server, client *Client, mechanism string, value []byte) bool {
  229. if client.certfp == "" {
  230. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed, you are not connecting with a caertificate")
  231. return false
  232. }
  233. err := server.store.Update(func(tx *buntdb.Tx) error {
  234. // certfp lookup key
  235. accountKey, err := tx.Get(fmt.Sprintf(keyCertToAccount, client.certfp))
  236. if err != nil {
  237. return errSaslFail
  238. }
  239. // confirm account exists
  240. _, err = tx.Get(fmt.Sprintf(keyAccountExists, accountKey))
  241. if err != nil {
  242. return errSaslFail
  243. }
  244. // confirm account is verified
  245. _, err = tx.Get(fmt.Sprintf(keyAccountVerified, accountKey))
  246. if err != nil {
  247. return errSaslFail
  248. }
  249. // confirm the certfp in that account's credentials
  250. creds, err := loadAccountCredentials(tx, accountKey)
  251. if err != nil || creds.Certificate != client.certfp {
  252. return errSaslFail
  253. }
  254. // succeeded, load account info if necessary
  255. account, exists := server.accounts[accountKey]
  256. if !exists {
  257. account = loadAccount(server, tx, accountKey)
  258. }
  259. client.LoginToAccount(account)
  260. return nil
  261. })
  262. if err != nil {
  263. client.Send(nil, server.name, ERR_SASLFAIL, client.nick, "SASL authentication failed")
  264. return false
  265. }
  266. client.successfulSaslAuth()
  267. return false
  268. }
  269. // successfulSaslAuth means that a SASL auth attempt completed successfully, and is used to dispatch messages.
  270. func (c *Client) successfulSaslAuth() {
  271. 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))
  272. c.Send(nil, c.server.name, RPL_SASLSUCCESS, c.nick, "SASL authentication successful")
  273. // dispatch account-notify
  274. for friend := range c.Friends(AccountNotify) {
  275. friend.Send(nil, c.nickMaskString, "ACCOUNT", c.account.Name)
  276. }
  277. }