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 3.6KB

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