Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

accounts.go 11KB

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