two_factors.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Copyright 2020 The Gogs 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 db
  5. import (
  6. "context"
  7. "encoding/base64"
  8. "fmt"
  9. "strings"
  10. "time"
  11. "github.com/pkg/errors"
  12. "gorm.io/gorm"
  13. log "unknwon.dev/clog/v2"
  14. "gogs.io/gogs/internal/cryptoutil"
  15. "gogs.io/gogs/internal/errutil"
  16. "gogs.io/gogs/internal/strutil"
  17. )
  18. // TwoFactorsStore is the persistent interface for 2FA.
  19. type TwoFactorsStore interface {
  20. // Create creates a new 2FA token and recovery codes for given user. The "key"
  21. // is used to encrypt and later decrypt given "secret", which should be
  22. // configured in site-level and change of the "key" will break all existing 2FA
  23. // tokens.
  24. Create(ctx context.Context, userID int64, key, secret string) error
  25. // GetByUserID returns the 2FA token of given user. It returns
  26. // ErrTwoFactorNotFound when not found.
  27. GetByUserID(ctx context.Context, userID int64) (*TwoFactor, error)
  28. // IsEnabled returns true if the user has enabled 2FA.
  29. IsEnabled(ctx context.Context, userID int64) bool
  30. UseRecoveryCode(ctx context.Context, userID int64, code string) error
  31. }
  32. var TwoFactors TwoFactorsStore
  33. // BeforeCreate implements the GORM create hook.
  34. func (t *TwoFactor) BeforeCreate(tx *gorm.DB) error {
  35. if t.CreatedUnix == 0 {
  36. t.CreatedUnix = tx.NowFunc().Unix()
  37. }
  38. return nil
  39. }
  40. // AfterFind implements the GORM query hook.
  41. func (t *TwoFactor) AfterFind(_ *gorm.DB) error {
  42. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  43. return nil
  44. }
  45. var _ TwoFactorsStore = (*twoFactors)(nil)
  46. type twoFactors struct {
  47. *gorm.DB
  48. }
  49. func (db *twoFactors) Create(ctx context.Context, userID int64, key, secret string) error {
  50. encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
  51. if err != nil {
  52. return errors.Wrap(err, "encrypt secret")
  53. }
  54. tf := &TwoFactor{
  55. UserID: userID,
  56. Secret: base64.StdEncoding.EncodeToString(encrypted),
  57. }
  58. recoveryCodes, err := generateRecoveryCodes(userID, 10)
  59. if err != nil {
  60. return errors.Wrap(err, "generate recovery codes")
  61. }
  62. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  63. err := tx.Create(tf).Error
  64. if err != nil {
  65. return err
  66. }
  67. return tx.Create(&recoveryCodes).Error
  68. })
  69. }
  70. var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil)
  71. type ErrTwoFactorNotFound struct {
  72. args errutil.Args
  73. }
  74. func IsErrTwoFactorNotFound(err error) bool {
  75. _, ok := err.(ErrTwoFactorNotFound)
  76. return ok
  77. }
  78. func (err ErrTwoFactorNotFound) Error() string {
  79. return fmt.Sprintf("2FA does not found: %v", err.args)
  80. }
  81. func (ErrTwoFactorNotFound) NotFound() bool {
  82. return true
  83. }
  84. func (db *twoFactors) GetByUserID(ctx context.Context, userID int64) (*TwoFactor, error) {
  85. tf := new(TwoFactor)
  86. err := db.WithContext(ctx).Where("user_id = ?", userID).First(tf).Error
  87. if err != nil {
  88. if err == gorm.ErrRecordNotFound {
  89. return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}}
  90. }
  91. return nil, err
  92. }
  93. return tf, nil
  94. }
  95. func (db *twoFactors) IsEnabled(ctx context.Context, userID int64) bool {
  96. var count int64
  97. err := db.WithContext(ctx).Model(new(TwoFactor)).Where("user_id = ?", userID).Count(&count).Error
  98. if err != nil {
  99. log.Error("Failed to count two factors [user_id: %d]: %v", userID, err)
  100. }
  101. return count > 0
  102. }
  103. // UseRecoveryCode validates a recovery code of given user and marks it as used
  104. // if valid. It returns ErrTwoFactorRecoveryCodeNotFound if the code is invalid
  105. // or already used.
  106. func (db *twoFactors) UseRecoveryCode(ctx context.Context, userID int64, code string) error {
  107. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  108. var recoveryCode TwoFactorRecoveryCode
  109. err := tx.Where("user_id = ? AND code = ? AND is_used = ?", userID, code, false).First(&recoveryCode).Error
  110. if err != nil {
  111. if err == gorm.ErrRecordNotFound {
  112. return ErrTwoFactorRecoveryCodeNotFound{Code: code}
  113. }
  114. return errors.Wrap(err, "get unused recovery code")
  115. }
  116. err = tx.Model(&recoveryCode).Update("is_used", true).Error
  117. if err != nil {
  118. return errors.Wrap(err, "mark recovery code as used")
  119. }
  120. return nil
  121. })
  122. }
  123. // generateRecoveryCodes generates N number of recovery codes for 2FA.
  124. func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) {
  125. recoveryCodes := make([]*TwoFactorRecoveryCode, n)
  126. for i := 0; i < n; i++ {
  127. code, err := strutil.RandomChars(10)
  128. if err != nil {
  129. return nil, errors.Wrap(err, "generate random characters")
  130. }
  131. recoveryCodes[i] = &TwoFactorRecoveryCode{
  132. UserID: userID,
  133. Code: strings.ToLower(code[:5] + "-" + code[5:]),
  134. }
  135. }
  136. return recoveryCodes, nil
  137. }