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.8KB

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