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.

126 lines
3.2 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/md5"
  7. "crypto/subtle"
  8. "encoding/base64"
  9. "time"
  10. "github.com/Unknwon/com"
  11. "github.com/pquerna/otp/totp"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/setting"
  14. )
  15. // TwoFactor represents a two-factor authentication token.
  16. type TwoFactor struct {
  17. ID int64 `xorm:"pk autoincr"`
  18. UID int64 `xorm:"UNIQUE"`
  19. Secret string
  20. ScratchToken string
  21. Created time.Time `xorm:"-"`
  22. CreatedUnix int64 `xorm:"INDEX created"`
  23. Updated time.Time `xorm:"-"`
  24. UpdatedUnix int64 `xorm:"INDEX updated"`
  25. }
  26. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  27. func (t *TwoFactor) AfterLoad() {
  28. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  29. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  30. }
  31. // GenerateScratchToken recreates the scratch token the user is using.
  32. func (t *TwoFactor) GenerateScratchToken() error {
  33. token, err := base.GetRandomString(8)
  34. if err != nil {
  35. return err
  36. }
  37. t.ScratchToken = token
  38. return nil
  39. }
  40. // VerifyScratchToken verifies if the specified scratch token is valid.
  41. func (t *TwoFactor) VerifyScratchToken(token string) bool {
  42. if len(token) == 0 {
  43. return false
  44. }
  45. return subtle.ConstantTimeCompare([]byte(token), []byte(t.ScratchToken)) == 1
  46. }
  47. func (t *TwoFactor) getEncryptionKey() []byte {
  48. k := md5.Sum([]byte(setting.SecretKey))
  49. return k[:]
  50. }
  51. // SetSecret sets the 2FA secret.
  52. func (t *TwoFactor) SetSecret(secret string) error {
  53. secretBytes, err := com.AESEncrypt(t.getEncryptionKey(), []byte(secret))
  54. if err != nil {
  55. return err
  56. }
  57. t.Secret = base64.StdEncoding.EncodeToString(secretBytes)
  58. return nil
  59. }
  60. // ValidateTOTP validates the provided passcode.
  61. func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
  62. decodedStoredSecret, err := base64.StdEncoding.DecodeString(t.Secret)
  63. if err != nil {
  64. return false, err
  65. }
  66. secret, err := com.AESDecrypt(t.getEncryptionKey(), decodedStoredSecret)
  67. if err != nil {
  68. return false, err
  69. }
  70. secretStr := string(secret)
  71. return totp.Validate(passcode, secretStr), nil
  72. }
  73. // NewTwoFactor creates a new two-factor authentication token.
  74. func NewTwoFactor(t *TwoFactor) error {
  75. err := t.GenerateScratchToken()
  76. if err != nil {
  77. return err
  78. }
  79. _, err = x.Insert(t)
  80. return err
  81. }
  82. // UpdateTwoFactor updates a two-factor authentication token.
  83. func UpdateTwoFactor(t *TwoFactor) error {
  84. _, err := x.ID(t.ID).AllCols().Update(t)
  85. return err
  86. }
  87. // GetTwoFactorByUID returns the two-factor authentication token associated with
  88. // the user, if any.
  89. func GetTwoFactorByUID(uid int64) (*TwoFactor, error) {
  90. twofa := &TwoFactor{UID: uid}
  91. has, err := x.Get(twofa)
  92. if err != nil {
  93. return nil, err
  94. } else if !has {
  95. return nil, ErrTwoFactorNotEnrolled{uid}
  96. }
  97. return twofa, nil
  98. }
  99. // DeleteTwoFactorByID deletes two-factor authentication token by given ID.
  100. func DeleteTwoFactorByID(id, userID int64) error {
  101. cnt, err := x.ID(id).Delete(&TwoFactor{
  102. UID: userID,
  103. })
  104. if err != nil {
  105. return err
  106. } else if cnt != 1 {
  107. return ErrTwoFactorNotEnrolled{userID}
  108. }
  109. return nil
  110. }