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

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