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.

twofactor.go 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "context"
  6. "crypto/md5"
  7. "crypto/subtle"
  8. "encoding/base32"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "code.gitea.io/gitea/models/db"
  13. "code.gitea.io/gitea/modules/secret"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/timeutil"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/minio/sha256-simd"
  18. "github.com/pquerna/otp/totp"
  19. "golang.org/x/crypto/pbkdf2"
  20. )
  21. //
  22. // Two-factor authentication
  23. //
  24. // ErrTwoFactorNotEnrolled indicates that a user is not enrolled in two-factor authentication.
  25. type ErrTwoFactorNotEnrolled struct {
  26. UID int64
  27. }
  28. // IsErrTwoFactorNotEnrolled checks if an error is a ErrTwoFactorNotEnrolled.
  29. func IsErrTwoFactorNotEnrolled(err error) bool {
  30. _, ok := err.(ErrTwoFactorNotEnrolled)
  31. return ok
  32. }
  33. func (err ErrTwoFactorNotEnrolled) Error() string {
  34. return fmt.Sprintf("user not enrolled in 2FA [uid: %d]", err.UID)
  35. }
  36. // Unwrap unwraps this as a ErrNotExist err
  37. func (err ErrTwoFactorNotEnrolled) Unwrap() error {
  38. return util.ErrNotExist
  39. }
  40. // TwoFactor represents a two-factor authentication token.
  41. type TwoFactor struct {
  42. ID int64 `xorm:"pk autoincr"`
  43. UID int64 `xorm:"UNIQUE"`
  44. Secret string
  45. ScratchSalt string
  46. ScratchHash string
  47. LastUsedPasscode string `xorm:"VARCHAR(10)"`
  48. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  49. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  50. }
  51. func init() {
  52. db.RegisterModel(new(TwoFactor))
  53. }
  54. // GenerateScratchToken recreates the scratch token the user is using.
  55. func (t *TwoFactor) GenerateScratchToken() (string, error) {
  56. tokenBytes, err := util.CryptoRandomBytes(6)
  57. if err != nil {
  58. return "", err
  59. }
  60. // these chars are specially chosen, avoid ambiguous chars like `0`, `O`, `1`, `I`.
  61. const base32Chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
  62. token := base32.NewEncoding(base32Chars).WithPadding(base32.NoPadding).EncodeToString(tokenBytes)
  63. t.ScratchSalt, _ = util.CryptoRandomString(10)
  64. t.ScratchHash = HashToken(token, t.ScratchSalt)
  65. return token, nil
  66. }
  67. // HashToken return the hashable salt
  68. func HashToken(token, salt string) string {
  69. tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New)
  70. return hex.EncodeToString(tempHash)
  71. }
  72. // VerifyScratchToken verifies if the specified scratch token is valid.
  73. func (t *TwoFactor) VerifyScratchToken(token string) bool {
  74. if len(token) == 0 {
  75. return false
  76. }
  77. tempHash := HashToken(token, t.ScratchSalt)
  78. return subtle.ConstantTimeCompare([]byte(t.ScratchHash), []byte(tempHash)) == 1
  79. }
  80. func (t *TwoFactor) getEncryptionKey() []byte {
  81. k := md5.Sum([]byte(setting.SecretKey))
  82. return k[:]
  83. }
  84. // SetSecret sets the 2FA secret.
  85. func (t *TwoFactor) SetSecret(secretString string) error {
  86. secretBytes, err := secret.AesEncrypt(t.getEncryptionKey(), []byte(secretString))
  87. if err != nil {
  88. return err
  89. }
  90. t.Secret = base64.StdEncoding.EncodeToString(secretBytes)
  91. return nil
  92. }
  93. // ValidateTOTP validates the provided passcode.
  94. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  95. decodedStoredSecret, err := base64.StdEncoding.DecodeString(t.Secret)
  96. if err != nil {
  97. return false, err
  98. }
  99. secretBytes, err := secret.AesDecrypt(t.getEncryptionKey(), decodedStoredSecret)
  100. if err != nil {
  101. return false, err
  102. }
  103. secretStr := string(secretBytes)
  104. return totp.Validate(passcode, secretStr), nil
  105. }
  106. // NewTwoFactor creates a new two-factor authentication token.
  107. func NewTwoFactor(ctx context.Context, t *TwoFactor) error {
  108. _, err := db.GetEngine(ctx).Insert(t)
  109. return err
  110. }
  111. // UpdateTwoFactor updates a two-factor authentication token.
  112. func UpdateTwoFactor(ctx context.Context, t *TwoFactor) error {
  113. _, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t)
  114. return err
  115. }
  116. // GetTwoFactorByUID returns the two-factor authentication token associated with
  117. // the user, if any.
  118. func GetTwoFactorByUID(ctx context.Context, uid int64) (*TwoFactor, error) {
  119. twofa := &TwoFactor{}
  120. has, err := db.GetEngine(ctx).Where("uid=?", uid).Get(twofa)
  121. if err != nil {
  122. return nil, err
  123. } else if !has {
  124. return nil, ErrTwoFactorNotEnrolled{uid}
  125. }
  126. return twofa, nil
  127. }
  128. // HasTwoFactorByUID returns the two-factor authentication token associated with
  129. // the user, if any.
  130. func HasTwoFactorByUID(ctx context.Context, uid int64) (bool, error) {
  131. return db.GetEngine(ctx).Where("uid=?", uid).Exist(&TwoFactor{})
  132. }
  133. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
  134. func DeleteTwoFactorByID(ctx context.Context, id, userID int64) error {
  135. cnt, err := db.GetEngine(ctx).ID(id).Delete(&TwoFactor{
  136. UID: userID,
  137. })
  138. if err != nil {
  139. return err
  140. } else if cnt != 1 {
  141. return ErrTwoFactorNotEnrolled{userID}
  142. }
  143. return nil
  144. }