Просмотр исходного кода

fix(fever): store the Fever API key as a SHA-256 digest

Anyone who could read the database or a backup could reuse the stored
md5(username:password) value as a Fever API key. Existing Fever clients
keep working after the migration, and lookups now use an index instead
of hashing every row in SQL, which only compared digests to avoid a
timing side channel.
Frédéric Guillot 6 часов назад
Родитель
Сommit
96d5413677

+ 1 - 1
internal/crypto/crypto.go

@@ -28,7 +28,7 @@ func SHA256(value string) string {
 	return hex.EncodeToString(h[:])
 }
 
-// HashToken returns the SHA-256 digest of a random token, to store and look it up without keeping the token itself.
+// HashToken returns the SHA-256 digest of an API token, to store and look it up without keeping the token itself.
 func HashToken(token string) []byte {
 	digest := sha256.Sum256([]byte(token))
 	return digest[:]

+ 13 - 0
internal/database/migrations.go

@@ -1604,4 +1604,17 @@ var migrations = [...]func(tx *sql.Tx) error{
 		`)
 		return err
 	},
+	func(tx *sql.Tx) (err error) {
+		// Keep only the SHA-256 digest of the Fever API key, the
+		// md5(username:password) value that clients send with every
+		// request, so a copy of the database is not enough to call the
+		// Fever API. Existing Fever clients keep working.
+		_, err = tx.Exec(`
+			ALTER TABLE integrations ADD COLUMN fever_token_hash bytea;
+			UPDATE integrations SET fever_token_hash = sha256(convert_to(lower(fever_token), 'UTF8')) WHERE fever_token <> '';
+			ALTER TABLE integrations DROP COLUMN fever_token;
+			CREATE INDEX integrations_fever_token_hash_idx ON integrations (fever_token_hash);
+		`)
+		return err
+	},
 }

+ 3 - 2
internal/fever/integration_server_test.go

@@ -9,6 +9,7 @@ import (
 	"testing"
 
 	miniflux "miniflux.app/v2/client"
+	"miniflux.app/v2/internal/crypto"
 	"miniflux.app/v2/internal/http/server/servertest"
 )
 
@@ -71,7 +72,7 @@ func setFeverIntegration(t *testing.T, userID int64, enabled bool, password stri
 	apiKey := feverAPIKey(user.Username, password)
 	integration.FeverEnabled = enabled
 	integration.FeverUsername = user.Username
-	integration.FeverToken = apiKey
+	integration.FeverTokenHash = crypto.HashToken(apiKey)
 	if err := server.Store.UpdateIntegration(integration); err != nil {
 		t.Fatal(err)
 	}
@@ -79,7 +80,7 @@ func setFeverIntegration(t *testing.T, userID int64, enabled bool, password stri
 }
 
 // feverAPIKey returns the API key that Fever clients send: the MD5 hash of "username:password",
-// which is also the token that the integrations page stores.
+// whose SHA-256 digest the integrations page stores.
 func feverAPIKey(username, password string) string {
 	sum := md5.Sum([]byte(username + ":" + password))
 	return hex.EncodeToString(sum[:])

+ 1 - 1
internal/model/integration.go

@@ -18,7 +18,7 @@ type Integration struct {
 	InstapaperPassword               string
 	FeverEnabled                     bool
 	FeverUsername                    string
-	FeverToken                       string
+	FeverTokenHash                   []byte
 	GoogleReaderEnabled              bool
 	GoogleReaderUsername             string
 	GoogleReaderPassword             string

+ 4 - 4
internal/storage/api_key_integration_test.go

@@ -16,7 +16,7 @@ import (
 func TestCreateAPIKeyStoresOnlyTheTokenHash(t *testing.T) {
 	db := openTestDatabase(t)
 	store := NewStorage(db)
-	userID := createAPIKeyTestUser(t, db)
+	userID := createTestUser(t, db)
 
 	apiKey, err := store.CreateAPIKey(userID, "Test")
 	if err != nil {
@@ -63,7 +63,7 @@ func TestCreateAPIKeyStoresOnlyTheTokenHash(t *testing.T) {
 func TestUserByAPIKeyFindsKeysHashedByTheMigration(t *testing.T) {
 	db := openTestDatabase(t)
 	store := NewStorage(db)
-	userID := createAPIKeyTestUser(t, db)
+	userID := createTestUser(t, db)
 
 	// The migration hashes existing tokens in SQL; the digest must match the one computed in Go.
 	legacyToken := crypto.GenerateRandomStringHex(32)
@@ -94,11 +94,11 @@ func TestUserByAPIKeyFindsKeysHashedByTheMigration(t *testing.T) {
 	}
 }
 
-func createAPIKeyTestUser(t *testing.T, db *sql.DB) int64 {
+func createTestUser(t *testing.T, db *sql.DB) int64 {
 	t.Helper()
 
 	var userID int64
-	username := "api_key_test_user_" + crypto.GenerateRandomStringHex(10)
+	username := "storage_test_user_" + crypto.GenerateRandomStringHex(10)
 	if err := db.QueryRow(`INSERT INTO users (username) VALUES ($1) RETURNING id`, username).Scan(&userID); err != nil {
 		t.Fatal(err)
 	}

+ 68 - 0
internal/storage/fever_integration_test.go

@@ -0,0 +1,68 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package storage
+
+import (
+	"bytes"
+	"encoding/hex"
+	"strings"
+	"testing"
+
+	"miniflux.app/v2/internal/crypto"
+)
+
+func TestUserByFeverTokenFindsTokensHashedByTheMigration(t *testing.T) {
+	db := openTestDatabase(t)
+	store := NewStorage(db)
+	userID := createTestUser(t, db)
+
+	// The migration hashes existing tokens in SQL after lowercasing them; the digest must match the one computed in Go.
+	feverToken := crypto.GenerateRandomStringHex(16)
+	if _, err := db.Exec(
+		`INSERT INTO integrations (user_id, fever_enabled, fever_username, fever_token_hash) VALUES ($1, 't', $2, sha256(convert_to(lower($3), 'UTF8')))`,
+		userID, "fever_"+feverToken, strings.ToUpper(feverToken),
+	); err != nil {
+		t.Fatal(err)
+	}
+
+	for _, candidate := range []string{feverToken, strings.ToUpper(feverToken)} {
+		user, err := store.UserByFeverToken(candidate)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if user == nil || user.ID != userID {
+			t.Fatalf(`Expected the Fever token %q to authenticate user %d, got %+v`, candidate, userID, user)
+		}
+	}
+
+	// The stored digest must not be usable as a Fever API key.
+	integration, err := store.Integration(userID)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !bytes.Equal(integration.FeverTokenHash, crypto.HashToken(feverToken)) {
+		t.Fatalf(`Expected the SHA-256 digest of the lowercase token to be stored`)
+	}
+	if user, err := store.UserByFeverToken(hex.EncodeToString(integration.FeverTokenHash)); err != nil || user != nil {
+		t.Errorf(`Expected no user for the stored digest, got %+v (error: %v)`, user, err)
+	}
+
+	// Saving the integration keeps the digest.
+	if err := store.UpdateIntegration(integration); err != nil {
+		t.Fatal(err)
+	}
+	if user, err := store.UserByFeverToken(feverToken); err != nil || user == nil {
+		t.Fatalf(`Expected the Fever token to still authenticate the user after saving the integration, got %+v (error: %v)`, user, err)
+	}
+
+	// Disabling Fever clears the digest, as the integrations page does.
+	integration.FeverEnabled = false
+	integration.FeverTokenHash = nil
+	if err := store.UpdateIntegration(integration); err != nil {
+		t.Fatal(err)
+	}
+	if user, err := store.UserByFeverToken(feverToken); err != nil || user != nil {
+		t.Errorf(`Expected no user once Fever is disabled, got %+v (error: %v)`, user, err)
+	}
+}

+ 9 - 7
internal/storage/integration.go

@@ -7,8 +7,10 @@ import (
 	"database/sql"
 	"errors"
 	"fmt"
+	"strings"
 
 	"golang.org/x/crypto/bcrypt"
+	"miniflux.app/v2/internal/crypto"
 	"miniflux.app/v2/internal/model"
 )
 
@@ -28,7 +30,7 @@ func (s *Storage) HasDuplicateGoogleReaderUsername(userID int64, googleReaderUse
 	return result
 }
 
-// UserByFeverToken returns a user by using the Fever API token.
+// UserByFeverToken returns the user whose Fever API token, compared case-insensitively, matches the given one.
 func (s *Storage) UserByFeverToken(token string) (*model.User, error) {
 	query := `
 		SELECT
@@ -39,11 +41,11 @@ func (s *Storage) UserByFeverToken(token string) (*model.User, error) {
 			integrations ON integrations.user_id=users.id
 		WHERE
 			integrations.fever_enabled='t' AND
-			sha256(convert_to(lower(integrations.fever_token), 'UTF8')) = sha256(convert_to(lower($1), 'UTF8'))
+			integrations.fever_token_hash=$1
 	`
 
 	var user model.User
-	err := s.db.QueryRow(query, token).Scan(&user.ID, &user.Username, &user.IsAdmin, &user.Timezone)
+	err := s.db.QueryRow(query, crypto.HashToken(strings.ToLower(token))).Scan(&user.ID, &user.Username, &user.IsAdmin, &user.Timezone)
 	switch {
 	case errors.Is(err, sql.ErrNoRows):
 		return nil, nil
@@ -123,7 +125,7 @@ func (s *Storage) Integration(userID int64) (*model.Integration, error) {
 			instapaper_password,
 			fever_enabled,
 			fever_username,
-			fever_token,
+			fever_token_hash,
 			googlereader_enabled,
 			googlereader_username,
 			googlereader_password,
@@ -256,7 +258,7 @@ func (s *Storage) Integration(userID int64) (*model.Integration, error) {
 		&integration.InstapaperPassword,
 		&integration.FeverEnabled,
 		&integration.FeverUsername,
-		&integration.FeverToken,
+		&integration.FeverTokenHash,
 		&integration.GoogleReaderEnabled,
 		&integration.GoogleReaderUsername,
 		&integration.GoogleReaderPassword,
@@ -398,7 +400,7 @@ func (s *Storage) UpdateIntegration(integration *model.Integration) error {
 			instapaper_password=$7,
 			fever_enabled=$8,
 			fever_username=$9,
-			fever_token=$10,
+			fever_token_hash=$10,
 			wallabag_enabled=$11,
 			wallabag_only_url=$12,
 			wallabag_url=$13,
@@ -528,7 +530,7 @@ func (s *Storage) UpdateIntegration(integration *model.Integration) error {
 		integration.InstapaperPassword,
 		integration.FeverEnabled,
 		integration.FeverUsername,
-		integration.FeverToken,
+		integration.FeverTokenHash,
 		integration.WallabagEnabled,
 		integration.WallabagOnlyURL,
 		integration.WallabagURL,

+ 4 - 2
internal/ui/integration_update.go

@@ -37,10 +37,12 @@ func (h *handler) updateIntegration(w http.ResponseWriter, r *http.Request) {
 
 	if integration.FeverEnabled {
 		if integrationForm.FeverPassword != "" {
-			integration.FeverToken = fmt.Sprintf("%x", md5.Sum([]byte(integration.FeverUsername+":"+integrationForm.FeverPassword)))
+			// Fever clients send this MD5 value without a username on every request, so a salted, slow hash could not be looked up.
+			feverToken := fmt.Sprintf("%x", md5.Sum([]byte(integration.FeverUsername+":"+integrationForm.FeverPassword)))
+			integration.FeverTokenHash = crypto.HashToken(feverToken)
 		}
 	} else {
-		integration.FeverToken = ""
+		integration.FeverTokenHash = nil
 	}
 
 	if validationErr := integrationForm.ValidateGoogleReader(integration.GoogleReaderPassword); validationErr != nil {