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.

158 lines
4.0 KiB

  1. // Copyright 2017 The Gitea 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 models
  5. import (
  6. "crypto/aes"
  7. "crypto/cipher"
  8. "crypto/md5"
  9. "crypto/rand"
  10. "crypto/subtle"
  11. "encoding/base64"
  12. "errors"
  13. "io"
  14. "github.com/pquerna/otp/totp"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. )
  19. // TwoFactor represents a two-factor authentication token.
  20. type TwoFactor struct {
  21. ID int64 `xorm:"pk autoincr"`
  22. UID int64 `xorm:"UNIQUE"`
  23. Secret string
  24. ScratchToken string
  25. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  26. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  27. }
  28. // GenerateScratchToken recreates the scratch token the user is using.
  29. func (t *TwoFactor) GenerateScratchToken() error {
  30. token, err := base.GetRandomString(8)
  31. if err != nil {
  32. return err
  33. }
  34. t.ScratchToken = token
  35. return nil
  36. }
  37. // VerifyScratchToken verifies if the specified scratch token is valid.
  38. func (t *TwoFactor) VerifyScratchToken(token string) bool {
  39. if len(token) == 0 {
  40. return false
  41. }
  42. return subtle.ConstantTimeCompare([]byte(token), []byte(t.ScratchToken)) == 1
  43. }
  44. func (t *TwoFactor) getEncryptionKey() []byte {
  45. k := md5.Sum([]byte(setting.SecretKey))
  46. return k[:]
  47. }
  48. // SetSecret sets the 2FA secret.
  49. func (t *TwoFactor) SetSecret(secret string) error {
  50. secretBytes, err := aesEncrypt(t.getEncryptionKey(), []byte(secret))
  51. if err != nil {
  52. return err
  53. }
  54. t.Secret = base64.StdEncoding.EncodeToString(secretBytes)
  55. return nil
  56. }
  57. // ValidateTOTP validates the provided passcode.
  58. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  59. decodedStoredSecret, err := base64.StdEncoding.DecodeString(t.Secret)
  60. if err != nil {
  61. return false, err
  62. }
  63. secret, err := aesDecrypt(t.getEncryptionKey(), decodedStoredSecret)
  64. if err != nil {
  65. return false, err
  66. }
  67. secretStr := string(secret)
  68. return totp.Validate(passcode, secretStr), nil
  69. }
  70. // aesEncrypt encrypts text and given key with AES.
  71. func aesEncrypt(key, text []byte) ([]byte, error) {
  72. block, err := aes.NewCipher(key)
  73. if err != nil {
  74. return nil, err
  75. }
  76. b := base64.StdEncoding.EncodeToString(text)
  77. ciphertext := make([]byte, aes.BlockSize+len(b))
  78. iv := ciphertext[:aes.BlockSize]
  79. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  80. return nil, err
  81. }
  82. cfb := cipher.NewCFBEncrypter(block, iv)
  83. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  84. return ciphertext, nil
  85. }
  86. // aesDecrypt decrypts text and given key with AES.
  87. func aesDecrypt(key, text []byte) ([]byte, error) {
  88. block, err := aes.NewCipher(key)
  89. if err != nil {
  90. return nil, err
  91. }
  92. if len(text) < aes.BlockSize {
  93. return nil, errors.New("ciphertext too short")
  94. }
  95. iv := text[:aes.BlockSize]
  96. text = text[aes.BlockSize:]
  97. cfb := cipher.NewCFBDecrypter(block, iv)
  98. cfb.XORKeyStream(text, text)
  99. data, err := base64.StdEncoding.DecodeString(string(text))
  100. if err != nil {
  101. return nil, err
  102. }
  103. return data, nil
  104. }
  105. // NewTwoFactor creates a new two-factor authentication token.
  106. func NewTwoFactor(t *TwoFactor) error {
  107. err := t.GenerateScratchToken()
  108. if err != nil {
  109. return err
  110. }
  111. _, err = x.Insert(t)
  112. return err
  113. }
  114. // UpdateTwoFactor updates a two-factor authentication token.
  115. func UpdateTwoFactor(t *TwoFactor) error {
  116. _, err := x.ID(t.ID).AllCols().Update(t)
  117. return err
  118. }
  119. // GetTwoFactorByUID returns the two-factor authentication token associated with
  120. // the user, if any.
  121. func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
  122. twofa := &TwoFactor{UID: uid}
  123. has, err := x.Get(twofa)
  124. if err != nil {
  125. return nil, err
  126. } else if !has {
  127. return nil, ErrTwoFactorNotEnrolled{uid}
  128. }
  129. return twofa, nil
  130. }
  131. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
  132. func DeleteTwoFactorByID(id, userID int64) error {
  133. cnt, err := x.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. }