|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/aes" |
| 5 | + "crypto/cipher" |
| 6 | + "crypto/rand" |
| 7 | + "encoding/base64" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/gtsteffaniak/filebrowser/backend/common/settings" |
| 14 | + "github.com/gtsteffaniak/filebrowser/backend/database/users" |
| 15 | + "github.com/gtsteffaniak/go-cache/cache" |
| 16 | + "github.com/gtsteffaniak/go-logger/logger" |
| 17 | + "github.com/pquerna/otp" |
| 18 | + "github.com/pquerna/otp/totp" |
| 19 | +) |
| 20 | + |
| 21 | +// Constants for TOTP (Time-based One-Time Password) configuration. |
| 22 | +const ( |
| 23 | + // IssuerName is the name of the application or service. |
| 24 | + IssuerName = "FileBrowser Quantum" |
| 25 | + |
| 26 | + // TokenValidTime defines the total duration a token is considered valid. |
| 27 | + // Note: The actual validation window might be slightly longer depending on the period. |
| 28 | + TokenValidTime = time.Minute * 2 |
| 29 | + |
| 30 | + // TOTPPeriod is the standard duration in seconds that a TOTP code is valid. |
| 31 | + TOTPPeriod uint = 30 |
| 32 | + |
| 33 | + // TOTPSecretSize is the byte length of the shared secret. |
| 34 | + TOTPSecretSize uint = 20 |
| 35 | + |
| 36 | + // TOTPDigits specifies the number of digits in the OTP code. |
| 37 | + TOTPDigits = otp.DigitsSix |
| 38 | + |
| 39 | + // TOTPAlgorithm is the hashing algorithm to use. |
| 40 | + TOTPAlgorithm = otp.AlgorithmSHA1 |
| 41 | +) |
| 42 | + |
| 43 | +var ( |
| 44 | + // TOTPSkew allows for a certain number of periods of clock drift. |
| 45 | + // We calculate it to best match the TokenValidTime. |
| 46 | + // (2 * Skew + 1) * Period >= TokenValidTime |
| 47 | + // For a 2-minute (120s) window with a 30s period, we need a Skew of 2. |
| 48 | + // (2*2 + 1) * 30s = 150s (2.5 minutes). This is the closest we can get. |
| 49 | + TOTPSkew uint = uint(TokenValidTime.Seconds()) / (2 * uint(TOTPPeriod)) |
| 50 | + encryptionKey []byte |
| 51 | + TotpCache = cache.NewCache(5 * time.Minute) |
| 52 | +) |
| 53 | + |
| 54 | +func GenerateOtpForUser(user *users.User, userStore *users.Storage) (string, error) { |
| 55 | + // Generate a new TOTP key using the defined constants. |
| 56 | + key, err := totp.Generate(totp.GenerateOpts{ |
| 57 | + Issuer: IssuerName, |
| 58 | + AccountName: user.Username, |
| 59 | + Period: TOTPPeriod, |
| 60 | + SecretSize: TOTPSecretSize, |
| 61 | + Digits: TOTPDigits, |
| 62 | + Algorithm: TOTPAlgorithm, |
| 63 | + }) |
| 64 | + if err != nil { |
| 65 | + return "", fmt.Errorf("error generating TOTP key: %w", err) |
| 66 | + } |
| 67 | + |
| 68 | + secretText := key.Secret() |
| 69 | + nonce := "" |
| 70 | + if settings.Config.Auth.TotpSecret != "" { |
| 71 | + // If an encryption key is provided, encrypt the secret. |
| 72 | + secretText, nonce, err = encryptSecret(secretText, encryptionKey) |
| 73 | + if err != nil { |
| 74 | + return "", fmt.Errorf("failed to encrypt TOTP secret: %w", err) |
| 75 | + } |
| 76 | + } |
| 77 | + // set cache so verify can attempt to use it but not require it for user yet. |
| 78 | + TotpCache.Set(user.Username, secretText+"||"+nonce) |
| 79 | + url := "otpauth://totp/FileBrowser%20Quantum?secret=" + secretText |
| 80 | + return url, nil |
| 81 | +} |
| 82 | + |
| 83 | +// encryptSecret uses AES-GCM to encrypt a plaintext secret. |
| 84 | +// It returns the base64-encoded ciphertext and nonce, or an error. |
| 85 | +func encryptSecret(secret string, key []byte) (string, string, error) { |
| 86 | + if len(key) != 32 { |
| 87 | + return "", "", fmt.Errorf("invalid encryption key length: must be 32 bytes") |
| 88 | + } |
| 89 | + |
| 90 | + block, err := aes.NewCipher(key) |
| 91 | + if err != nil { |
| 92 | + return "", "", err |
| 93 | + } |
| 94 | + |
| 95 | + gcm, err := cipher.NewGCM(block) |
| 96 | + if err != nil { |
| 97 | + return "", "", err |
| 98 | + } |
| 99 | + |
| 100 | + nonce := make([]byte, gcm.NonceSize()) |
| 101 | + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { |
| 102 | + return "", "", err |
| 103 | + } |
| 104 | + |
| 105 | + ciphertext := gcm.Seal(nil, nonce, []byte(secret), nil) |
| 106 | + |
| 107 | + return base64.StdEncoding.EncodeToString(ciphertext), base64.StdEncoding.EncodeToString(nonce), nil |
| 108 | +} |
| 109 | + |
| 110 | +// decryptSecret uses AES-GCM to decrypt a ciphertext using its key and nonce. |
| 111 | +// It returns the plaintext secret or an error. |
| 112 | +func decryptSecret(b64Ciphertext, b64Nonce string) (string, error) { |
| 113 | + if len(encryptionKey) != 32 { |
| 114 | + return "", fmt.Errorf("invalid encryption key length: must be 32 bytes") |
| 115 | + } |
| 116 | + |
| 117 | + ciphertext, err := base64.StdEncoding.DecodeString(b64Ciphertext) |
| 118 | + if err != nil { |
| 119 | + return "", fmt.Errorf("failed to decode ciphertext: %w", err) |
| 120 | + } |
| 121 | + |
| 122 | + nonce, err := base64.StdEncoding.DecodeString(b64Nonce) |
| 123 | + if err != nil { |
| 124 | + return "", fmt.Errorf("failed to decode nonce: %w", err) |
| 125 | + } |
| 126 | + |
| 127 | + block, err := aes.NewCipher(encryptionKey) |
| 128 | + if err != nil { |
| 129 | + return "", err |
| 130 | + } |
| 131 | + |
| 132 | + gcm, err := cipher.NewGCM(block) |
| 133 | + if err != nil { |
| 134 | + return "", err |
| 135 | + } |
| 136 | + |
| 137 | + plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) |
| 138 | + if err != nil { |
| 139 | + // This error often means the key is wrong or the data is corrupt |
| 140 | + return "", fmt.Errorf("failed to decrypt secret: %w", err) |
| 141 | + } |
| 142 | + |
| 143 | + return string(plaintext), nil |
| 144 | +} |
| 145 | + |
| 146 | +func VerifyTotpCode(user *users.User, code string, userStore *users.Storage) error { |
| 147 | + // get data from cache |
| 148 | + cachedSecret, found := TotpCache.Get(user.Username).(string) |
| 149 | + if !found && user.TOTPSecret == "" { |
| 150 | + return fmt.Errorf("OTP token not found in cache, please generate a new one") |
| 151 | + } |
| 152 | + totpSecret := user.TOTPSecret // The encrypted or plaintext secret |
| 153 | + totpNonce := user.TOTPNonce // The nonce if encrypted, or empty if plaintext |
| 154 | + if found { |
| 155 | + splitSecret := strings.Split(cachedSecret, "||") |
| 156 | + if len(splitSecret) < 2 { |
| 157 | + return fmt.Errorf("invalid cached OTP token format") |
| 158 | + } |
| 159 | + totpSecret = splitSecret[0] |
| 160 | + totpNonce = splitSecret[1] |
| 161 | + } |
| 162 | + secretToValidate := totpSecret |
| 163 | + if settings.Config.Auth.TotpSecret != "" { |
| 164 | + // If an encryption key is configured, we must decrypt the secret first. |
| 165 | + if totpNonce == "" { |
| 166 | + return fmt.Errorf("secret is encrypted but nonce is missing") |
| 167 | + } |
| 168 | + decryptedSecret, err := decryptSecret(totpSecret, totpNonce) |
| 169 | + if err != nil { |
| 170 | + return fmt.Errorf("failed to decrypt TOTP secret: %w", err) |
| 171 | + } |
| 172 | + secretToValidate = decryptedSecret |
| 173 | + } |
| 174 | + // --- END: ADD THIS DECRYPTION LOGIC --- |
| 175 | + |
| 176 | + // Validate the token using the (now plaintext) secret. |
| 177 | + valid, err := totp.ValidateCustom(code, secretToValidate, time.Now().UTC(), totp.ValidateOpts{ |
| 178 | + Period: TOTPPeriod, |
| 179 | + Skew: TOTPSkew, |
| 180 | + Digits: TOTPDigits, |
| 181 | + Algorithm: TOTPAlgorithm, |
| 182 | + }) |
| 183 | + if err != nil { |
| 184 | + logger.Errorf("error during TOTP validation: %v", err) |
| 185 | + } |
| 186 | + if !valid { |
| 187 | + return fmt.Errorf("invalid OTP token") |
| 188 | + } |
| 189 | + if totpSecret != "" { |
| 190 | + user.TOTPSecret = totpSecret // The encrypted or plaintext secret |
| 191 | + user.TOTPNonce = totpNonce // The nonce if encrypted, or empty if plaintext |
| 192 | + user.OtpEnabled = true // Enable OTP for the user |
| 193 | + } |
| 194 | + // save user |
| 195 | + if err := userStore.Update(user, user.Permissions.Admin, "TOTPSecret", "TOTPNonce"); err != nil { |
| 196 | + logger.Debug("error updating user with OTP token:", err) |
| 197 | + return fmt.Errorf("error updating user with OTP token: %w", err) |
| 198 | + } |
| 199 | + return nil |
| 200 | +} |
0 commit comments