two_factor.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2017 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "strings"
  9. "time"
  10. "github.com/pquerna/otp/totp"
  11. "github.com/unknwon/com"
  12. "xorm.io/xorm"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/db/errors"
  15. "gogs.io/gogs/internal/tool"
  16. )
  17. // TwoFactor represents a two-factor authentication token.
  18. type TwoFactor struct {
  19. ID int64
  20. UserID int64 `xorm:"UNIQUE"`
  21. Secret string
  22. Created time.Time `xorm:"-" json:"-"`
  23. CreatedUnix int64
  24. }
  25. func (t *TwoFactor) BeforeInsert() {
  26. t.CreatedUnix = time.Now().Unix()
  27. }
  28. func (t *TwoFactor) AfterSet(colName string, _ xorm.Cell) {
  29. switch colName {
  30. case "created_unix":
  31. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  32. }
  33. }
  34. // ValidateTOTP returns true if given passcode is valid for two-factor authentication token.
  35. // It also returns possible validation error.
  36. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  37. secret, err := base64.StdEncoding.DecodeString(t.Secret)
  38. if err != nil {
  39. return false, fmt.Errorf("DecodeString: %v", err)
  40. }
  41. decryptSecret, err := com.AESGCMDecrypt(tool.MD5Bytes(conf.Security.SecretKey), secret)
  42. if err != nil {
  43. return false, fmt.Errorf("AESGCMDecrypt: %v", err)
  44. }
  45. return totp.Validate(passcode, string(decryptSecret)), nil
  46. }
  47. func generateRecoveryCodes(userID int64) ([]*TwoFactorRecoveryCode, error) {
  48. recoveryCodes := make([]*TwoFactorRecoveryCode, 10)
  49. for i := 0; i < 10; i++ {
  50. code, err := tool.RandomString(10)
  51. if err != nil {
  52. return nil, fmt.Errorf("RandomString: %v", err)
  53. }
  54. recoveryCodes[i] = &TwoFactorRecoveryCode{
  55. UserID: userID,
  56. Code: strings.ToLower(code[:5] + "-" + code[5:]),
  57. }
  58. }
  59. return recoveryCodes, nil
  60. }
  61. // NewTwoFactor creates a new two-factor authentication token and recovery codes for given user.
  62. func NewTwoFactor(userID int64, secret string) error {
  63. t := &TwoFactor{
  64. UserID: userID,
  65. }
  66. // Encrypt secret
  67. encryptSecret, err := com.AESGCMEncrypt(tool.MD5Bytes(conf.Security.SecretKey), []byte(secret))
  68. if err != nil {
  69. return fmt.Errorf("AESGCMEncrypt: %v", err)
  70. }
  71. t.Secret = base64.StdEncoding.EncodeToString(encryptSecret)
  72. recoveryCodes, err := generateRecoveryCodes(userID)
  73. if err != nil {
  74. return fmt.Errorf("generateRecoveryCodes: %v", err)
  75. }
  76. sess := x.NewSession()
  77. defer sess.Close()
  78. if err = sess.Begin(); err != nil {
  79. return err
  80. }
  81. if _, err = sess.Insert(t); err != nil {
  82. return fmt.Errorf("insert two-factor: %v", err)
  83. } else if _, err = sess.Insert(recoveryCodes); err != nil {
  84. return fmt.Errorf("insert recovery codes: %v", err)
  85. }
  86. return sess.Commit()
  87. }
  88. // GetTwoFactorByUserID returns two-factor authentication token of given user.
  89. func GetTwoFactorByUserID(userID int64) (*TwoFactor, error) {
  90. t := new(TwoFactor)
  91. has, err := x.Where("user_id = ?", userID).Get(t)
  92. if err != nil {
  93. return nil, err
  94. } else if !has {
  95. return nil, errors.TwoFactorNotFound{UserID: userID}
  96. }
  97. return t, nil
  98. }
  99. // DeleteTwoFactor removes two-factor authentication token and recovery codes of given user.
  100. func DeleteTwoFactor(userID int64) (err error) {
  101. sess := x.NewSession()
  102. defer sess.Close()
  103. if err = sess.Begin(); err != nil {
  104. return err
  105. }
  106. if _, err = sess.Where("user_id = ?", userID).Delete(new(TwoFactor)); err != nil {
  107. return fmt.Errorf("delete two-factor: %v", err)
  108. } else if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
  109. return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
  110. }
  111. return sess.Commit()
  112. }
  113. // TwoFactorRecoveryCode represents a two-factor authentication recovery code.
  114. type TwoFactorRecoveryCode struct {
  115. ID int64
  116. UserID int64
  117. Code string `xorm:"VARCHAR(11)"`
  118. IsUsed bool
  119. }
  120. // GetRecoveryCodesByUserID returns all recovery codes of given user.
  121. func GetRecoveryCodesByUserID(userID int64) ([]*TwoFactorRecoveryCode, error) {
  122. recoveryCodes := make([]*TwoFactorRecoveryCode, 0, 10)
  123. return recoveryCodes, x.Where("user_id = ?", userID).Find(&recoveryCodes)
  124. }
  125. func deleteRecoveryCodesByUserID(e Engine, userID int64) error {
  126. _, err := e.Where("user_id = ?", userID).Delete(new(TwoFactorRecoveryCode))
  127. return err
  128. }
  129. // RegenerateRecoveryCodes regenerates new set of recovery codes for given user.
  130. func RegenerateRecoveryCodes(userID int64) error {
  131. recoveryCodes, err := generateRecoveryCodes(userID)
  132. if err != nil {
  133. return fmt.Errorf("generateRecoveryCodes: %v", err)
  134. }
  135. sess := x.NewSession()
  136. defer sess.Close()
  137. if err = sess.Begin(); err != nil {
  138. return err
  139. }
  140. if err = deleteRecoveryCodesByUserID(sess, userID); err != nil {
  141. return fmt.Errorf("deleteRecoveryCodesByUserID: %v", err)
  142. } else if _, err = sess.Insert(recoveryCodes); err != nil {
  143. return fmt.Errorf("insert new recovery codes: %v", err)
  144. }
  145. return sess.Commit()
  146. }
  147. type ErrTwoFactorRecoveryCodeNotFound struct {
  148. Code string
  149. }
  150. func IsTwoFactorRecoveryCodeNotFound(err error) bool {
  151. _, ok := err.(ErrTwoFactorRecoveryCodeNotFound)
  152. return ok
  153. }
  154. func (err ErrTwoFactorRecoveryCodeNotFound) Error() string {
  155. return fmt.Sprintf("two-factor recovery code does not found [code: %s]", err.Code)
  156. }
  157. // UseRecoveryCode validates recovery code of given user and marks it is used if valid.
  158. func UseRecoveryCode(userID int64, code string) error {
  159. recoveryCode := new(TwoFactorRecoveryCode)
  160. has, err := x.Where("code = ?", code).And("is_used = ?", false).Get(recoveryCode)
  161. if err != nil {
  162. return fmt.Errorf("get unused code: %v", err)
  163. } else if !has {
  164. return ErrTwoFactorRecoveryCodeNotFound{Code: code}
  165. }
  166. recoveryCode.IsUsed = true
  167. if _, err = x.Id(recoveryCode.ID).Cols("is_used").Update(recoveryCode); err != nil {
  168. return fmt.Errorf("mark code as used: %v", err)
  169. }
  170. return nil
  171. }