From ebd90c3a459bf45fea14e44b6cd2455fe230758f Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sat, 21 Nov 2026 10:38:38 -0800 Subject: [PATCH] fips140=only: SHA-256 in place of MD5 and SHA-1 so the server starts and serves S3 (#12855) * util: SHA-256 stands in for MD5 and SHA-1 under fips140=only GODEBUG=fips140=only panics on MD5 and SHA-1. NewMd5 and NewSha1 return those hashes as before, and under fips140=only SHA-256 cut to the same size, so digests keep their length. Md5, HashStringToLong and HashToInt32 use NewMd5. Co-Authored-By: Claude Opus 5.5 * filer stores: hash directory keys with NewMd5 and NewSha1 leveldb2, leveldb3, rocksdb and arangodb hash directory keys with MD5, tikv with SHA-1, which GODEBUG=fips140=only refuses, so the filer panicked at startup. They now use util.NewMd5 and util.NewSha1. Keys made under fips140=only differ from MD5 keys, so leveldb2 and leveldb3 mark an empty database opened under fips140=only and refuse a database whose keys are of the other kind instead of showing it empty. Co-Authored-By: Claude Opus 5.5 * operation, volume: no Content-MD5 checks under fips140=only Under GODEBUG=fips140=only the uploader's digest is not an MD5, so it is no longer sent as Content-MD5, which volume servers outside that mode would reject; the digest still becomes the chunk ETag. A Go volume server in that mode keeps a client's Content-MD5 unchecked instead of panicking. Co-Authored-By: Claude Opus 5.5 * s3api, filer: ETags and content digests with util.NewMd5 ETags, entry Md5 attributes and chunk digests now use util.Md5 and util.NewMd5, so under GODEBUG=fips140=only they are SHA-256 cut to 16 bytes instead of panicking. That digest cannot check a client's Content-MD5, so in that mode Content-MD5 is accepted unchecked, and the filer stops returning Content-MD5. Co-Authored-By: Claude Opus 5.5 * s3api, iam, master: SHA-1 names with util.NewSha1 Multipart upload ids, IAM policy ids, the OIDC provider, audit and session revocation file names, and the master's read-only copy dir hash names with SHA-1. They now use util.NewSha1, which GODEBUG=fips140=only turns into truncated SHA-256. Co-Authored-By: Claude Opus 5.5 * postgres, oidc, update: refuse MD5 and SHA-1 checks under fips140=only PostgreSQL md5 authentication, OIDC TLS thumbprints (SHA-1 by definition) and weed update's MD5 check of the download cannot run under GODEBUG=fips140=only. They now fail with an error saying so instead of panicking. Co-Authored-By: Claude Opus 5.5 * s3api: no empty-body MD5 when Content-MD5 is not checked Under fips140=only a bodyless signed request still reached md5.Sum(nil) before the nil check and panicked. Co-Authored-By: Claude Opus 5.5 * s3api: empty copy part ETag from the digest it stores Co-Authored-By: Claude Opus 5.5 * util: skip the native MD5 test under fips140=only Co-Authored-By: Claude Opus 5.5 * s3sink: no Content-MD5 under fips140=only The entry's Md5 attribute is truncated SHA-256 there, which an S3 destination checking Content-MD5 would reject. Co-Authored-By: Claude Opus 5.5 * iam: move OIDC provider and revocation records to this mode's name The record names hash the ARN or JTI with util.NewSha1, which differs under GODEBUG=fips140=only. On the first use of a filer, each store renames records whose name does not match the one derived from their content, so lookups, revocation checks and deletes find records written in the other mode. Co-Authored-By: Claude Opus 5.5 * iam: test the rename with the names each fips140 mode derives Co-Authored-By: Claude Opus 5.5 * iam: rename a record only if it is unchanged, under its new name's lock Two processes renaming after a mode switch could both list a record; if one renamed it and the provider was then deleted, the other wrote it back. The rename is now one filer transaction locked on the new name, like the stores' conditional writes, that requires the old entry to be unchanged. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/command/master.go | 6 +- weed/command/update.go | 4 + .../filer_etc/filer_etc_identity.go | 6 +- weed/filer/arangodb/helpers.go | 3 +- weed/filer/filer_conf.go | 7 +- weed/filer/leveldb2/leveldb2_store.go | 7 +- weed/filer/leveldb3/leveldb3_store.go | 7 +- weed/filer/leveldb_handle/key_hash.go | 54 ++++ weed/filer/leveldb_handle/key_hash_test.go | 65 +++++ weed/filer/read_write.go | 10 +- weed/filer/rocksdb/rocksdb_store.go | 2 +- weed/filer/tikv/tikv_store.go | 2 +- weed/iam/helpers.go | 4 +- .../integration/filer_refused_create_test.go | 12 +- weed/iam/integration/oidc_provider_audit.go | 17 +- weed/iam/integration/oidc_provider_store.go | 38 ++- weed/iam/integration/session_revocation.go | 34 ++- weed/iam/integration/stored_name_rekey.go | 159 ++++++++++++ .../iam/integration/stored_name_rekey_test.go | 233 ++++++++++++++++++ weed/iam/oidc/oidc_provider.go | 4 + weed/mount/peer_fetcher.go | 4 +- weed/operation/upload_chunked.go | 6 +- weed/operation/upload_content.go | 21 +- weed/replication/sink/s3sink/s3_sink.go | 3 +- weed/s3api/filer_multipart.go | 3 +- weed/s3api/fips140_only.go | 11 +- weed/s3api/request_body.go | 10 +- weed/s3api/request_body_test.go | 8 + weed/s3api/s3api_object_handlers_copy.go | 8 +- .../s3api_object_handlers_copy_etag_test.go | 3 +- .../s3api_object_handlers_copy_part_sse.go | 11 +- weed/s3api/s3api_object_handlers_extract.go | 2 +- weed/s3api/s3api_object_handlers_multipart.go | 4 +- weed/s3api/s3api_object_handlers_put.go | 14 +- weed/s3api/s3api_sosapi.go | 8 +- .../filer_server_handlers_write_autochunk.go | 22 +- .../filer_server_handlers_write_upload.go | 9 +- weed/server/postgres/server.go | 4 + weed/server/volume_server_handlers_write.go | 4 + weed/sftpd/sftp_filer.go | 3 +- weed/storage/needle/needle_parse_upload.go | 6 +- weed/util/bytes.go | 7 +- weed/util/fips140_hash.go | 44 ++++ weed/util/fips140_hash_test.go | 59 +++++ 44 files changed, 835 insertions(+), 113 deletions(-) create mode 100644 weed/filer/leveldb_handle/key_hash.go create mode 100644 weed/filer/leveldb_handle/key_hash_test.go create mode 100644 weed/iam/integration/stored_name_rekey.go create mode 100644 weed/iam/integration/stored_name_rekey_test.go create mode 100644 weed/util/fips140_hash.go create mode 100644 weed/util/fips140_hash_test.go diff --git a/weed/command/master.go b/weed/command/master.go index fdc946ed58..dcb24b2fdb 100644 --- a/weed/command/master.go +++ b/weed/command/master.go @@ -2,7 +2,6 @@ package command import ( "context" - "crypto/sha1" "crypto/tls" "fmt" "io/fs" @@ -449,8 +448,9 @@ func copyDirForReadOnly(src string) (string, error) { if err != nil { abs = src } - sum := sha1.Sum([]byte(abs)) - dst := filepath.Join(os.TempDir(), fmt.Sprintf("weed-master-ro-%x", sum[:8])) + h := util.NewSha1() + h.Write([]byte(abs)) + dst := filepath.Join(os.TempDir(), fmt.Sprintf("weed-master-ro-%x", h.Sum(nil)[:8])) if fi, err := os.Stat(dst); err == nil && fi.IsDir() && fi.Mode().Perm() == 0700 && util.DirOwnedBySelf(fi) { if !newestMtime(dst).Before(newestMtime(src)) { diff --git a/weed/command/update.go b/weed/command/update.go index 53474e69ee..4fffb38760 100644 --- a/weed/command/update.go +++ b/weed/command/update.go @@ -6,6 +6,7 @@ import ( "bytes" "compress/gzip" "context" + "crypto/fips140" "crypto/md5" "encoding/hex" "encoding/json" @@ -152,6 +153,9 @@ func downloadRelease(ctx context.Context, target string, ver string) (version st } suffix := fmt.Sprintf("%s_%s%s%s.%s", runtime.GOOS, runtime.GOARCH, fullSuffix, largeDiskSuffix, ext) + if fips140.Enforced() { + return "", fmt.Errorf("the download is checked with MD5, which GODEBUG=fips140=only refuses") + } md5Filename := fmt.Sprintf("%s.md5", suffix) _, md5Val, err := getGithubDataFile(ctx, rel.Assets, md5Filename) if err != nil { diff --git a/weed/credential/filer_etc/filer_etc_identity.go b/weed/credential/filer_etc/filer_etc_identity.go index f4702b034c..0ce79f6db4 100644 --- a/weed/credential/filer_etc/filer_etc_identity.go +++ b/weed/credential/filer_etc/filer_etc_identity.go @@ -3,7 +3,6 @@ package filer_etc import ( "bytes" "context" - "crypto/md5" "encoding/json" "errors" "fmt" @@ -15,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" + "github.com/seaweedfs/seaweedfs/weed/util" ) const ( @@ -546,7 +546,7 @@ func (store *FilerEtcStore) createIfAbsent(ctx context.Context, subDir, name str if err != nil { return err } - contentMd5 := md5.Sum(data) + contentMd5 := util.Md5(data) return store.withFilerClient(func(client filer_pb.SeaweedFilerClient) error { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ Directory: filer.IamConfigDirectory + "/" + subDir, @@ -558,7 +558,7 @@ func (store *FilerEtcStore) createIfAbsent(ctx context.Context, subDir, name str Crtime: time.Now().Unix(), FileMode: uint32(0644), FileSize: uint64(len(data)), - Md5: contentMd5[:], + Md5: contentMd5, }, }, OExcl: true, diff --git a/weed/filer/arangodb/helpers.go b/weed/filer/arangodb/helpers.go index cf65750055..9209112993 100644 --- a/weed/filer/arangodb/helpers.go +++ b/weed/filer/arangodb/helpers.go @@ -2,7 +2,6 @@ package arangodb import ( "context" - "crypto/md5" "encoding/binary" "encoding/hex" "io" @@ -14,7 +13,7 @@ import ( // convert a string into arango-key safe hex bytes hash func hashString(dir string) string { - h := md5.New() + h := util.NewMd5() io.WriteString(h, dir) b := h.Sum(nil) return hex.EncodeToString(b) diff --git a/weed/filer/filer_conf.go b/weed/filer/filer_conf.go index e38235be41..bfab79b8d6 100644 --- a/weed/filer/filer_conf.go +++ b/weed/filer/filer_conf.go @@ -3,7 +3,6 @@ package filer import ( "bytes" "context" - "crypto/md5" "errors" "fmt" "io" @@ -375,7 +374,7 @@ func saveFilerConfConditionally(ctx context.Context, client filer_pb.SeaweedFile return err } content := buf.Bytes() - contentMd5 := md5.Sum(content) + contentMd5 := util.Md5(content) if snap.entry == nil { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ @@ -388,7 +387,7 @@ func saveFilerConfConditionally(ctx context.Context, client filer_pb.SeaweedFile Crtime: time.Now().Unix(), FileMode: uint32(0644), FileSize: uint64(len(content)), - Md5: contentMd5[:], + Md5: contentMd5, }, Content: content, }, @@ -423,7 +422,7 @@ func saveFilerConfConditionally(ctx context.Context, client filer_pb.SeaweedFile entry.Content = content entry.Attributes.Mtime = time.Now().Unix() entry.Attributes.FileSize = uint64(len(content)) - entry.Attributes.Md5 = contentMd5[:] + entry.Attributes.Md5 = contentMd5 err := filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{ Directory: DirectoryEtcSeaweedFS, Entry: entry, diff --git a/weed/filer/leveldb2/leveldb2_store.go b/weed/filer/leveldb2/leveldb2_store.go index 7e29f8e632..62dc81ade1 100644 --- a/weed/filer/leveldb2/leveldb2_store.go +++ b/weed/filer/leveldb2/leveldb2_store.go @@ -3,6 +3,7 @@ package leveldb import ( "bytes" "context" + "crypto/fips140" "crypto/md5" "fmt" "io" @@ -117,6 +118,10 @@ func (store *LevelDB2Store) initialize(dir string, dbCount int) (err error) { } store.dbCount = dbCount + if err := leveldb_handle.CheckKeyHash(store.dbs, fips140.Enforced(), store.ReadOnly); err != nil { + store.Shutdown() + return err + } return } @@ -319,7 +324,7 @@ func getNameFromKey(key []byte) string { // hash directory, and use last byte for partitioning func hashToBytes(dir string, dbCount int) ([]byte, int) { - h := md5.New() + h := weed_util.NewMd5() io.WriteString(h, dir) b := h.Sum(nil) diff --git a/weed/filer/leveldb3/leveldb3_store.go b/weed/filer/leveldb3/leveldb3_store.go index 634a2878db..a172197058 100644 --- a/weed/filer/leveldb3/leveldb3_store.go +++ b/weed/filer/leveldb3/leveldb3_store.go @@ -3,6 +3,7 @@ package leveldb import ( "bytes" "context" + "crypto/fips140" "crypto/md5" "fmt" "io" @@ -138,6 +139,10 @@ func (store *LevelDB3Store) loadDB(name string) (*leveldb_handle.DB, error) { glog.Errorf("filer store open dir %s: %v", dbFolder, dbErr) return nil, dbErr } + if err := leveldb_handle.CheckKeyHash([]*leveldb_handle.DB{db}, fips140.Enforced(), store.ReadOnly); err != nil { + db.Close() + return nil, err + } return db, nil } @@ -489,7 +494,7 @@ func getNameFromKey(key []byte) string { // hash directory func hashToBytes(dir string) []byte { - h := md5.New() + h := weed_util.NewMd5() io.WriteString(h, dir) b := h.Sum(nil) return b diff --git a/weed/filer/leveldb_handle/key_hash.go b/weed/filer/leveldb_handle/key_hash.go new file mode 100644 index 0000000000..0f1eaa3f8a --- /dev/null +++ b/weed/filer/leveldb_handle/key_hash.go @@ -0,0 +1,54 @@ +package leveldb_handle + +import ( + "errors" + "fmt" + + "github.com/syndtr/goleveldb/leveldb" +) + +var sha256KeyMarker = []byte("\x00seaweedfs.directory_key_hash.sha256") + +// CheckKeyHash refuses databases whose directory keys were hashed differently. +// Under GODEBUG=fips140=only directory keys hash with SHA-256 instead of MD5, +// so an empty database opened that way is marked, and a database holding +// keys of the other kind is refused. +func CheckKeyHash(dbs []*DB, sha256Keys, readOnly bool) error { + var unmarked []*DB + for _, db := range dbs { + marked, empty, err := keyHashState(db) + if err != nil { + return fmt.Errorf("%s: %w", db.name, err) + } + switch { + case marked && !sha256Keys: + return fmt.Errorf("%s was created under GODEBUG=fips140=only and can only be opened with it", db.name) + case !marked && sha256Keys && !empty: + return fmt.Errorf("%s hashes directory keys with MD5, which GODEBUG=fips140=only refuses; copy the metadata with fs.meta.save without fips140=only and fs.meta.load into a new store", db.name) + case !marked && sha256Keys: + unmarked = append(unmarked, db) + } + } + if readOnly { + return nil + } + for _, db := range unmarked { + if err := db.Put(sha256KeyMarker, nil, nil); err != nil { + return fmt.Errorf("%s: %w", db.name, err) + } + } + return nil +} + +func keyHashState(db *DB) (marked, empty bool, err error) { + if _, err = db.Get(sha256KeyMarker, nil); err == nil { + return true, false, nil + } + if !errors.Is(err, leveldb.ErrNotFound) { + return false, false, err + } + iter := db.NewIterator(nil, nil) + defer iter.Release() + empty = !iter.First() + return false, empty, iter.Error() +} diff --git a/weed/filer/leveldb_handle/key_hash_test.go b/weed/filer/leveldb_handle/key_hash_test.go new file mode 100644 index 0000000000..7961aa4fdf --- /dev/null +++ b/weed/filer/leveldb_handle/key_hash_test.go @@ -0,0 +1,65 @@ +package leveldb_handle + +import ( + "strings" + "testing" + + "github.com/syndtr/goleveldb/leveldb/storage" +) + +func openMemDBs(t *testing.T, n int) []*DB { + t.Helper() + var dbs []*DB + for i := 0; i < n; i++ { + db, err := Open(storage.NewMemStorage(), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + dbs = append(dbs, db) + } + return dbs +} + +func TestCheckKeyHashMarksEmptyDatabases(t *testing.T) { + dbs := openMemDBs(t, 2) + if err := CheckKeyHash(dbs, true, false); err != nil { + t.Fatalf("empty databases: %v", err) + } + if err := CheckKeyHash(dbs, true, false); err != nil { + t.Fatalf("marked databases: %v", err) + } + err := CheckKeyHash(dbs, false, false) + if err == nil || !strings.Contains(err.Error(), "fips140=only") { + t.Fatalf("marked databases opened without fips140=only: %v", err) + } +} + +func TestCheckKeyHashRefusesMd5Keys(t *testing.T) { + dbs := openMemDBs(t, 2) + if err := CheckKeyHash(dbs, false, false); err != nil { + t.Fatalf("empty databases without fips140=only: %v", err) + } + if err := dbs[1].Put([]byte("0123456789abcdefname"), []byte("entry"), nil); err != nil { + t.Fatal(err) + } + if err := CheckKeyHash(dbs, false, false); err != nil { + t.Fatalf("md5 keys without fips140=only: %v", err) + } + if err := CheckKeyHash(dbs, true, false); err == nil || !strings.Contains(err.Error(), "MD5") { + t.Fatalf("md5 keys under fips140=only: %v", err) + } + if _, err := dbs[0].Get(sha256KeyMarker, nil); err == nil { + t.Fatalf("a refused check must not mark the empty database") + } +} + +func TestCheckKeyHashReadOnlyLeavesEmptyDatabasesUnmarked(t *testing.T) { + dbs := openMemDBs(t, 1) + if err := CheckKeyHash(dbs, true, true); err != nil { + t.Fatal(err) + } + if err := CheckKeyHash(dbs, false, false); err != nil { + t.Fatalf("read-only check marked the database: %v", err) + } +} diff --git a/weed/filer/read_write.go b/weed/filer/read_write.go index 7fa572fd95..80e04795e0 100644 --- a/weed/filer/read_write.go +++ b/weed/filer/read_write.go @@ -3,10 +3,10 @@ package filer import ( "bytes" "context" - "crypto/md5" "time" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/wdclient" ) @@ -54,7 +54,7 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di Name: name, }) - contentMd5 := md5.Sum(content) + contentMd5 := util.Md5(content) if err == filer_pb.ErrNotFound { err = filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ @@ -67,7 +67,7 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di Crtime: time.Now().Unix(), FileMode: uint32(0644), FileSize: uint64(len(content)), - Md5: contentMd5[:], + Md5: contentMd5, }, Content: content, }, @@ -75,13 +75,13 @@ func SaveInsideFiler(ctx context.Context, client filer_pb.SeaweedFilerClient, di }) } else if err == nil { entry := resp.Entry - if bytes.Equal(entry.Content, content) && bytes.Equal(entry.GetAttributes().GetMd5(), contentMd5[:]) { + if bytes.Equal(entry.Content, content) && bytes.Equal(entry.GetAttributes().GetMd5(), contentMd5) { return nil } entry.Content = content entry.Attributes.Mtime = time.Now().Unix() entry.Attributes.FileSize = uint64(len(content)) - entry.Attributes.Md5 = contentMd5[:] + entry.Attributes.Md5 = contentMd5 err = filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{ Directory: dir, Entry: entry, diff --git a/weed/filer/rocksdb/rocksdb_store.go b/weed/filer/rocksdb/rocksdb_store.go index dd88d73aa3..45bc265c89 100644 --- a/weed/filer/rocksdb/rocksdb_store.go +++ b/weed/filer/rocksdb/rocksdb_store.go @@ -321,7 +321,7 @@ func getNameFromKey(key []byte) string { // hash directory, and use last byte for partitioning func hashToBytes(dir string) []byte { - h := md5.New() + h := weed_util.NewMd5() io.WriteString(h, dir) b := h.Sum(nil) diff --git a/weed/filer/tikv/tikv_store.go b/weed/filer/tikv/tikv_store.go index 9fc2adec91..0cff2d1867 100644 --- a/weed/filer/tikv/tikv_store.go +++ b/weed/filer/tikv/tikv_store.go @@ -466,7 +466,7 @@ func runOwnTxn(ctx context.Context, run func() (inContext bool, err error)) erro // Encoding Functions func hashToBytes(dir string) []byte { - h := sha1.New() + h := util.NewSha1() io.WriteString(h, dir) b := h.Sum(nil) return b diff --git a/weed/iam/helpers.go b/weed/iam/helpers.go index ee34e2d5e1..0b4d78e4bc 100644 --- a/weed/iam/helpers.go +++ b/weed/iam/helpers.go @@ -2,18 +2,18 @@ package iam import ( "crypto/rand" - "crypto/sha1" "fmt" "math/big" "sort" "github.com/aws/aws-sdk-go/service/iam" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" ) // Hash computes a SHA1 hash of the input string. func Hash(s *string) string { - h := sha1.New() + h := util.NewSha1() h.Write([]byte(*s)) return fmt.Sprintf("%x", h.Sum(nil)) } diff --git a/weed/iam/integration/filer_refused_create_test.go b/weed/iam/integration/filer_refused_create_test.go index 2e934a0a36..d5d13948b1 100644 --- a/weed/iam/integration/filer_refused_create_test.go +++ b/weed/iam/integration/filer_refused_create_test.go @@ -29,11 +29,19 @@ func (f *refusingFiler) CreateEntry(context.Context, *filer_pb.CreateEntryReques }, nil } +func (f *refusingFiler) ListEntries(*filer_pb.ListEntriesRequest, filer_pb.SeaweedFiler_ListEntriesServer) error { + return nil +} + func startRefusingFiler(t *testing.T) (*refusingFiler, func() string) { + filer := &refusingFiler{} + return filer, startTestFiler(t, filer) +} + +func startTestFiler(t *testing.T, filer filer_pb.SeaweedFilerServer) func() string { t.Helper() lis, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) - filer := &refusingFiler{} server := pb.NewGrpcServer() filer_pb.RegisterSeaweedFilerServer(server, filer) go func() { _ = server.Serve(lis) }() @@ -46,7 +54,7 @@ func startRefusingFiler(t *testing.T) (*refusingFiler, func() string) { grpcPort, err := strconv.Atoi(port) require.NoError(t, err) address := string(pb.NewServerAddress(host, 1, grpcPort)) - return filer, func() string { return address } + return func() string { return address } } // The IAM stores must not take a refused create for a stored record. A session diff --git a/weed/iam/integration/oidc_provider_audit.go b/weed/iam/integration/oidc_provider_audit.go index bae84ffcbc..80efe0a904 100644 --- a/weed/iam/integration/oidc_provider_audit.go +++ b/weed/iam/integration/oidc_provider_audit.go @@ -2,7 +2,6 @@ package integration import ( "context" - "crypto/sha1" "encoding/hex" "encoding/json" "fmt" @@ -13,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -35,11 +35,11 @@ const ( // OIDCProviderAuditEvent is the payload emitted for each lifecycle event. type OIDCProviderAuditEvent struct { - Type OIDCProviderAuditEventType `json:"type"` - ARN string `json:"arn"` - URL string `json:"url,omitempty"` - Detail map[string]string `json:"detail,omitempty"` - OccurredAt time.Time `json:"occurredAt"` + Type OIDCProviderAuditEventType `json:"type"` + ARN string `json:"arn"` + URL string `json:"url,omitempty"` + Detail map[string]string `json:"detail,omitempty"` + OccurredAt time.Time `json:"occurredAt"` } // OIDCProviderAuditSink consumes lifecycle events. Implementations must be @@ -149,8 +149,9 @@ func (f *FilerAuditSink) Emit(ctx context.Context, event *OIDCProviderAuditEvent // at the same nano against different ARNs are perfectly plausible // (audit-via-batch script). The ARN hash gives us an effectively- // collision-free name without leaking the ARN into the filer path. - arnSum := sha1.Sum([]byte(event.ARN)) - name := fmt.Sprintf("%d-%s-%s.json", event.OccurredAt.UnixNano(), event.Type, hex.EncodeToString(arnSum[:8])) + arnHash := util.NewSha1() + arnHash.Write([]byte(event.ARN)) + name := fmt.Sprintf("%d-%s-%s.json", event.OccurredAt.UnixNano(), event.Type, hex.EncodeToString(arnHash.Sum(nil)[:8])) occurredAt := event.OccurredAt.Unix() return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(addr), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ diff --git a/weed/iam/integration/oidc_provider_store.go b/weed/iam/integration/oidc_provider_store.go index c5ece91662..bd27e99dd2 100644 --- a/weed/iam/integration/oidc_provider_store.go +++ b/weed/iam/integration/oidc_provider_store.go @@ -2,7 +2,6 @@ package integration import ( "context" - "crypto/sha1" "encoding/hex" "encoding/json" "errors" @@ -19,6 +18,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -234,6 +234,7 @@ type FilerOIDCProviderStore struct { grpcDialOption grpc.DialOption basePath string filerAddressProvider func() string + names *storedNameRekey } // NewFilerOIDCProviderStore returns a filer-backed store. Default path @@ -248,6 +249,17 @@ func NewFilerOIDCProviderStore(config map[string]interface{}, filerAddressProvid store.basePath = strings.TrimSuffix(bp, "/") } } + store.names = &storedNameRekey{ + dir: store.basePath, + name: store.fileName, + keyOf: func(content []byte) string { + var record OIDCProviderRecord + if json.Unmarshal(content, &record) != nil { + return "" + } + return record.ARN + }, + } glog.V(2).Infof("Initialized FilerOIDCProviderStore with basePath %s", store.basePath) return store } @@ -265,8 +277,9 @@ func (f *FilerOIDCProviderStore) resolveFilerAddress(filerAddress string) string func (f *FilerOIDCProviderStore) fileName(arn string) string { // Hash the ARN to a fixed-width filename so we can store any character set // (including the URL fragments AWS lets through) without filer-path issues. - h := sha1.Sum([]byte(arn)) - return hex.EncodeToString(h[:]) + ".json" + h := util.NewSha1() + h.Write([]byte(arn)) + return hex.EncodeToString(h.Sum(nil)) + ".json" } // StoreProvider persists `record` as JSON. @@ -284,7 +297,7 @@ func (f *FilerOIDCProviderStore) StoreProvider(ctx context.Context, filerAddress return fmt.Errorf("marshal OIDC provider: %v", err) } - return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + return f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ Directory: f.basePath, Entry: &filer_pb.Entry{ @@ -313,7 +326,7 @@ func (f *FilerOIDCProviderStore) GetProviderByARN(ctx context.Context, filerAddr } var data []byte - err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + err := f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{ Directory: f.basePath, Name: f.fileName(arn), @@ -386,7 +399,7 @@ func (f *FilerOIDCProviderStore) ListProviders(ctx context.Context, filerAddress } var out []*OIDCProviderRecord - err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + err := f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { // Stream-paginate via StartFromFileName so deployments with more // than 1000 providers don't get a silently truncated list. const pageSize = 1000 @@ -446,7 +459,7 @@ func (f *FilerOIDCProviderStore) DeleteProvider(ctx context.Context, filerAddres if filerAddress == "" { return fmt.Errorf("filer address is required") } - return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + return f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{ Directory: f.basePath, Name: f.fileName(arn), @@ -479,7 +492,7 @@ func (f *FilerOIDCProviderStore) UpdateProvider(ctx context.Context, filerAddres if arn == "" { return fmt.Errorf("ARN is required") } - return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + return f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { for attempt := 0; attempt < maxProviderUpdateAttempts; attempt++ { var entry *filer_pb.Entry var current *OIDCProviderRecord @@ -589,8 +602,13 @@ func (f *FilerOIDCProviderStore) deleteProviderEntryIfUnchanged(ctx context.Cont return true, nil } -func (f *FilerOIDCProviderStore) withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, fn) +func (f *FilerOIDCProviderStore) withFilerClient(ctx context.Context, filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if err := f.names.ensure(ctx, filerAddress, client); err != nil { + return err + } + return fn(client) + }) } // DeriveOIDCProviderARN turns an issuer URL into the canonical IAM ARN AWS uses. diff --git a/weed/iam/integration/session_revocation.go b/weed/iam/integration/session_revocation.go index 6adfaa6866..8ad7147c44 100644 --- a/weed/iam/integration/session_revocation.go +++ b/weed/iam/integration/session_revocation.go @@ -2,7 +2,6 @@ package integration import ( "context" - "crypto/sha1" "encoding/hex" "encoding/json" "errors" @@ -15,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/grpc" ) @@ -92,6 +92,7 @@ type FilerSessionRevocationStore struct { grpcDialOption grpc.DialOption basePath string filerAddressProvider func() string + names *storedNameRekey } // NewFilerSessionRevocationStore returns a filer-backed blocklist store. @@ -107,6 +108,17 @@ func NewFilerSessionRevocationStore(config map[string]interface{}, filerAddressP store.basePath = strings.TrimSuffix(bp, "/") } } + store.names = &storedNameRekey{ + dir: store.basePath, + name: store.fileName, + keyOf: func(content []byte) string { + var record RevocationEntry + if json.Unmarshal(content, &record) != nil { + return "" + } + return record.JTI + }, + } glog.V(2).Infof("Initialized FilerSessionRevocationStore with basePath %s", store.basePath) return store } @@ -128,8 +140,9 @@ func (f *FilerSessionRevocationStore) resolveFilerAddress(filerAddress string) s // hex name that's both filesystem-safe and stable, so the lookup-on-revoke // path still finds the right entry. func (f *FilerSessionRevocationStore) fileName(jti string) string { - sum := sha1.Sum([]byte(jti)) - return hex.EncodeToString(sum[:]) + ".json" + h := util.NewSha1() + h.Write([]byte(jti)) + return hex.EncodeToString(h.Sum(nil)) + ".json" } func (f *FilerSessionRevocationStore) Revoke(ctx context.Context, filerAddress string, entry *RevocationEntry) error { @@ -147,7 +160,7 @@ func (f *FilerSessionRevocationStore) Revoke(ctx context.Context, filerAddress s if err != nil { return fmt.Errorf("marshal revocation entry: %v", err) } - return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + return f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { err := filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ Directory: f.basePath, Entry: &filer_pb.Entry{ @@ -174,7 +187,7 @@ func (f *FilerSessionRevocationStore) IsRevoked(ctx context.Context, filerAddres return false, fmt.Errorf("filer address is required") } revoked := false - err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + err := f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{ Directory: f.basePath, Name: f.fileName(jti), @@ -197,7 +210,7 @@ func (f *FilerSessionRevocationStore) Purge(ctx context.Context, filerAddress st return 0, fmt.Errorf("filer address is required") } count := 0 - err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error { + err := f.withFilerClient(ctx, filerAddress, func(client filer_pb.SeaweedFilerClient) error { // Stream-paginate the directory: ListEntriesRequest has no built-in // "page until done" semantics, so we use StartFromFileName to walk // the directory in chunks and avoid the previous hardcoded 10k cap. @@ -248,6 +261,11 @@ func (f *FilerSessionRevocationStore) Purge(ctx context.Context, filerAddress st return count, err } -func (f *FilerSessionRevocationStore) withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, fn) +func (f *FilerSessionRevocationStore) withFilerClient(ctx context.Context, filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error { + return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddress), f.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + if err := f.names.ensure(ctx, filerAddress, client); err != nil { + return err + } + return fn(client) + }) } diff --git a/weed/iam/integration/stored_name_rekey.go b/weed/iam/integration/stored_name_rekey.go new file mode 100644 index 0000000000..6ae8dc9fc5 --- /dev/null +++ b/weed/iam/integration/stored_name_rekey.go @@ -0,0 +1,159 @@ +package integration + +import ( + "context" + "errors" + "fmt" + "io" + "sync" + + "github.com/google/uuid" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// storedNameRekey moves records to the name this process derives for their +// key. The names hash the key with util.NewSha1, which changes under +// GODEBUG=fips140=only, so records written in the other mode are otherwise +// missed by lookups and deletes. It runs once per filer address. +type storedNameRekey struct { + dir string + keyOf func(content []byte) string + name func(key string) string + + mu sync.Mutex + done sync.Map +} + +func (r *storedNameRekey) ensure(ctx context.Context, filerAddress string, client filer_pb.SeaweedFilerClient) error { + if _, ok := r.done.Load(filerAddress); ok { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.done.Load(filerAddress); ok { + return nil + } + if err := r.run(ctx, client); err != nil { + return fmt.Errorf("rename records in %s: %w", r.dir, err) + } + r.done.Store(filerAddress, true) + return nil +} + +func (r *storedNameRekey) run(ctx context.Context, client filer_pb.SeaweedFilerClient) error { + var misnamed []*filer_pb.Entry + err := listStoredEntries(ctx, client, r.dir, func(entry *filer_pb.Entry) { + key := r.keyOf(entry.Content) + if key != "" && entry.Name != r.name(key) { + misnamed = append(misnamed, entry) + } + }) + if err != nil { + return err + } + for _, entry := range misnamed { + if err := r.move(ctx, client, entry); err != nil { + return err + } + } + return nil +} + +// move renames entry if it is unchanged, under the lock the stores' conditional +// writes of the new name take, so a record another process already moved and +// then deleted is not written back. A record already under the new name wins. +func (r *storedNameRekey) move(ctx context.Context, client filer_pb.SeaweedFilerClient, listed *filer_pb.Entry) error { + found, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: r.dir, Name: listed.Name}) + if errors.Is(err, filer_pb.ErrNotFound) { + return nil + } + if err != nil { + return fmt.Errorf("lookup %s: %w", listed.Name, err) + } + entry := found.Entry + name := r.name(r.keyOf(entry.Content)) + if name == entry.Name { + return nil + } + remove := &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_DELETE, Directory: r.dir, Name: entry.Name, IsDeleteData: true} + put := &filer_pb.ObjectMutation{ + Type: filer_pb.ObjectMutation_PUT, + Directory: r.dir, + Entry: &filer_pb.Entry{Name: name, Attributes: entry.Attributes, Content: entry.Content}, + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}}}, + } + resp, err := r.transact(ctx, client, name, entry, put, remove) + if err == nil && resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && resp.FailedMutation != nil && *resp.FailedMutation == 0 { + resp, err = r.transact(ctx, client, name, entry, remove) + } + if err != nil { + return fmt.Errorf("rename %s to %s: %w", entry.Name, name, err) + } + switch { + case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED: + glog.V(1).Infof("%s/%s changed before its rename to %s; leaving it", r.dir, entry.Name, name) + case resp.Error != "": + return fmt.Errorf("rename %s to %s: %s", entry.Name, name, resp.Error) + default: + glog.V(0).Infof("renamed %s/%s to %s", r.dir, entry.Name, name) + } + return nil +} + +func (r *storedNameRekey) transact(ctx context.Context, client filer_pb.SeaweedFilerClient, name string, source *filer_pb.Entry, mutations ...*filer_pb.ObjectMutation) (*filer_pb.ObjectTransactionResponse, error) { + target := r.dir + "/" + name + resp, err := client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{ + LockKey: target, + RequestId: uuid.NewString(), + RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + target, + ConditionKey: r.dir + "/" + source.Name, + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{ + Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: source, + }}}, + Mutations: mutations, + }) + if status.Code(err) == codes.FailedPrecondition { + return &filer_pb.ObjectTransactionResponse{ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil + } + return resp, err +} + +func listStoredEntries(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, fn func(*filer_pb.Entry)) error { + const pageSize = 1000 + startFrom := "" + for { + stream, err := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{ + Directory: dir, + Limit: pageSize, + StartFromFileName: startFrom, + }) + if err != nil { + return fmt.Errorf("list %s: %w", dir, err) + } + pageCount := 0 + for { + resp, err := stream.Recv() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return fmt.Errorf("list %s: %w", dir, err) + } + if resp.Entry == nil { + continue + } + pageCount++ + startFrom = resp.Entry.Name + if !resp.Entry.IsDirectory { + fn(resp.Entry) + } + } + if pageCount < pageSize { + return nil + } + } +} diff --git a/weed/iam/integration/stored_name_rekey_test.go b/weed/iam/integration/stored_name_rekey_test.go new file mode 100644 index 0000000000..3c3966b6fc --- /dev/null +++ b/weed/iam/integration/stored_name_rekey_test.go @@ -0,0 +1,233 @@ +package integration + +import ( + "context" + "crypto/fips140" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "sort" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// memFiler holds one directory level of entries in memory. +type memFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + mu sync.Mutex + entries map[string]*filer_pb.Entry // keyed by directory + "/" + name + // afterList runs once a listing is sent, as another process would act. + afterList func() +} + +func newMemFiler() *memFiler { return &memFiler{entries: map[string]*filer_pb.Entry{}} } + +func (f *memFiler) put(dir string, entry *filer_pb.Entry) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[dir+"/"+entry.Name] = entry +} + +func (f *memFiler) names(dir string) []string { + f.mu.Lock() + defer f.mu.Unlock() + var names []string + for key, e := range f.entries { + if key == dir+"/"+e.Name { + names = append(names, e.Name) + } + } + sort.Strings(names) + return names +} + +func (f *memFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if e, ok := f.entries[req.Directory+"/"+req.Name]; ok { + return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil + } + return nil, status.Error(codes.NotFound, "not found") +} + +func (f *memFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + key := req.Directory + "/" + req.Entry.Name + for _, c := range req.GetCondition().GetClauses() { + if _, exists := f.entries[key]; exists && c.Kind == filer_pb.WriteCondition_IF_NOT_EXISTS { + return &filer_pb.CreateEntryResponse{Error: "exists", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil + } + } + f.entries[key] = req.Entry + return &filer_pb.CreateEntryResponse{}, nil +} + +func (f *memFiler) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.entries, req.Directory+"/"+req.Name) + return &filer_pb.DeleteEntryResponse{}, nil +} + +func (f *memFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + for _, name := range f.names(req.Directory) { + if name <= req.StartFromFileName { + continue + } + f.mu.Lock() + e := f.entries[req.Directory+"/"+name] + f.mu.Unlock() + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: e}); err != nil { + return err + } + } + if f.afterList != nil { + f.afterList() + } + return nil +} + +func (f *memFiler) satisfied(cond *filer_pb.WriteCondition, key string) bool { + current, exists := f.entries[key] + for _, c := range cond.GetClauses() { + switch c.Kind { + case filer_pb.WriteCondition_IF_NOT_EXISTS: + if exists { + return false + } + case filer_pb.WriteCondition_IF_ENTRY_EQUAL: + if !exists || !proto.Equal(current, c.ExpectedEntry) { + return false + } + } + } + return true +} + +func (f *memFiler) ObjectTransaction(_ context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + conditionKey := req.LockKey + if req.ConditionKey != "" { + conditionKey = req.ConditionKey + } + if !f.satisfied(req.Condition, conditionKey) { + return &filer_pb.ObjectTransactionResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil + } + for i, m := range req.Mutations { + key := m.Directory + "/" + m.Name + if m.Type == filer_pb.ObjectMutation_PUT { + key = m.Directory + "/" + m.Entry.Name + } + if !f.satisfied(m.Condition, key) { + failed := int32(i) + return &filer_pb.ObjectTransactionResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED, FailedMutation: &failed}, nil + } + if m.Type == filer_pb.ObjectMutation_PUT { + f.entries[key] = m.Entry + } else { + delete(f.entries, key) + } + } + return &filer_pb.ObjectTransactionResponse{}, nil +} + +// sha1Names holds the SHA-1 names, which fips140=only cannot compute. +var sha1Names = map[string]string{ + "session-1": "96c71081c21826a93aad95a48dad46723ef67a06.json", + "arn:aws:iam::123456789012:oidc-provider/issuer.example.com": "a34a5d627a0d07f6793272fe8fae86d3957de95f.json", +} + +// otherModeName is the name the other fips140 mode derives for key. +func otherModeName(key string) string { + if fips140.Enforced() { + return sha1Names[key] + } + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:20]) + ".json" +} + +func storeAs(t *testing.T, filer *memFiler, dir, name string, record any) { + data, err := json.Marshal(record) + require.NoError(t, err) + filer.put(dir, &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileMode: 0o600}, Content: data}) +} + +func TestRevocationWrittenInTheOtherModeStillRevokes(t *testing.T) { + ctx := context.Background() + filer := newMemFiler() + store := NewFilerSessionRevocationStore(nil, startTestFiler(t, filer)) + store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + storeAs(t, filer, store.basePath, otherModeName("session-1"), &RevocationEntry{JTI: "session-1", ExpiresAt: time.Now().Add(time.Hour)}) + + revoked, err := store.IsRevoked(ctx, "", "session-1") + require.NoError(t, err) + require.True(t, revoked) + require.Equal(t, []string{store.fileName("session-1")}, filer.names(store.basePath)) +} + +func TestProviderStoredInTheOtherModeCanBeDeleted(t *testing.T) { + ctx := context.Background() + filer := newMemFiler() + store := NewFilerOIDCProviderStore(nil, startTestFiler(t, filer)) + store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + const arn = "arn:aws:iam::123456789012:oidc-provider/issuer.example.com" + const issuer = "https://issuer.example.com" + storeAs(t, filer, store.basePath, otherModeName(arn), newRecord(arn, issuer)) + + got, err := store.GetProviderByARN(ctx, "", arn) + require.NoError(t, err) + require.Equal(t, issuer, got.URL) + + require.NoError(t, store.DeleteProvider(ctx, "", arn)) + _, err = store.GetProviderByIssuer(ctx, "", issuer) + require.Error(t, err, "a deleted provider must not stay trusted") + require.Empty(t, filer.names(store.basePath)) +} + +// A record already under this mode's name is newer than its other-mode copy. +func TestRenameKeepsTheRecordUnderThisModesName(t *testing.T) { + ctx := context.Background() + filer := newMemFiler() + store := NewFilerOIDCProviderStore(nil, startTestFiler(t, filer)) + store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + const arn = "arn:aws:iam::123456789012:oidc-provider/issuer.example.com" + storeAs(t, filer, store.basePath, otherModeName(arn), newRecord(arn, "https://old.example.com")) + storeAs(t, filer, store.basePath, store.fileName(arn), newRecord(arn, "https://new.example.com")) + + records, err := store.ListProviders(ctx, "") + require.NoError(t, err) + require.Len(t, records, 1) + require.Equal(t, "https://new.example.com", records[0].URL) +} + +// Another process renamed the record and deleted the provider after this one +// listed the directory: the stale listing must not bring the provider back. +func TestRenameDoesNotRestoreARecordMovedAndDeletedMeanwhile(t *testing.T) { + ctx := context.Background() + filer := newMemFiler() + store := NewFilerOIDCProviderStore(nil, startTestFiler(t, filer)) + store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + const arn = "arn:aws:iam::123456789012:oidc-provider/issuer.example.com" + storeAs(t, filer, store.basePath, otherModeName(arn), newRecord(arn, "https://issuer.example.com")) + filer.afterList = func() { + filer.afterList = nil + filer.mu.Lock() + delete(filer.entries, store.basePath+"/"+otherModeName(arn)) + filer.mu.Unlock() + } + + _, err := store.GetProviderByARN(ctx, "", arn) + require.ErrorIs(t, err, ErrOIDCProviderNotFound) + require.Empty(t, filer.names(store.basePath)) +} diff --git a/weed/iam/oidc/oidc_provider.go b/weed/iam/oidc/oidc_provider.go index eba00d3559..d2e29efc0a 100644 --- a/weed/iam/oidc/oidc_provider.go +++ b/weed/iam/oidc/oidc_provider.go @@ -4,6 +4,7 @@ import ( "context" "crypto/ecdsa" "crypto/elliptic" + "crypto/fips140" "crypto/rsa" "crypto/sha1" "crypto/tls" @@ -258,6 +259,9 @@ func normalizeThumbprints(in []string) map[string]struct{} { // self-signed deployments and skip-verify test setups. When the chain has not // been built (InsecureSkipVerify), we fall back to PeerCertificates. func verifyThumbprintMatch(cs tls.ConnectionState, expected map[string]struct{}) error { + if fips140.Enforced() { + return fmt.Errorf("OIDC TLS thumbprints are SHA-1, which GODEBUG=fips140=only refuses") + } candidates := collectThumbprintCandidates(cs) for _, c := range candidates { sum := sha1.Sum(c.Raw) diff --git a/weed/mount/peer_fetcher.go b/weed/mount/peer_fetcher.go index ad95e42fa1..292fe8505b 100644 --- a/weed/mount/peer_fetcher.go +++ b/weed/mount/peer_fetcher.go @@ -301,8 +301,8 @@ func fetchChunkFromPeer(ctx context.Context, dial MountPeerDialer, peerAddr, fid // Compare raw digests so we don't reject every valid peer response // because of an encoding mismatch. if expectedETag != "" { - got := md5.Sum(buf) - if !etagMatchesMD5(expectedETag, got[:]) { + got := util.Md5(buf) + if !etagMatchesMD5(expectedETag, got) { return nil, fmt.Errorf("etag mismatch: peer=%s got=%x want=%s", peerAddr, got, expectedETag) } } diff --git a/weed/operation/upload_chunked.go b/weed/operation/upload_chunked.go index 235c8457f1..e59e5cfa53 100644 --- a/weed/operation/upload_chunked.go +++ b/weed/operation/upload_chunked.go @@ -3,7 +3,6 @@ package operation import ( "bytes" "context" - "crypto/md5" "encoding/base64" "errors" "fmt" @@ -17,6 +16,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" ) @@ -64,7 +64,7 @@ func UploadReaderInChunks(ctx context.Context, reader io.Reader, opt *ChunkedUpl func uploadReaderInChunks(ctx context.Context, reader io.Reader, opt *ChunkedUploadOption, prepare func([]byte, *UploadOption) (*preparedUpload, error)) (*ChunkedUploadResult, error) { - md5Hash := md5.New() + md5Hash := util.NewMd5() var partReader = io.TeeReader(reader, md5Hash) var fileChunks []*filer_pb.FileChunk @@ -183,7 +183,7 @@ uploadLoop: }() // Hash and prepare only this bounded chunk before minting its volume JWT. - chunkMd5 := md5.Sum(buf.Bytes()) + chunkMd5 := util.Md5(buf.Bytes()) chunkMd5B64 := base64.StdEncoding.EncodeToString(chunkMd5[:]) var prepared *preparedUpload if opt.UploadFunc == nil { diff --git a/weed/operation/upload_content.go b/weed/operation/upload_content.go index a5c264d125..c4212f211b 100644 --- a/weed/operation/upload_content.go +++ b/weed/operation/upload_content.go @@ -3,7 +3,7 @@ package operation import ( "bytes" "context" - "crypto/md5" + "crypto/fips140" "encoding/base64" "encoding/json" "errors" @@ -316,8 +316,7 @@ func (uploader *Uploader) UploadWithRetry(filerClient filer_pb.FilerClient, assi // verifies). Under cipher the server never sees the header, but the digest // still becomes the chunk ETag. if uploadOption.WantMd5 && uploadOption.Md5 == "" { - digest := md5.Sum(data) - uploadOption.Md5 = base64.StdEncoding.EncodeToString(digest[:]) + uploadOption.Md5 = base64.StdEncoding.EncodeToString(util.Md5(data)) } fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error) { @@ -616,7 +615,7 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction if option.IsInputCompressed { h.Set("Content-Encoding", "gzip") } - if option.Md5 != "" { + if option.Md5 != "" && !fips140.Enforced() { h.Set("Content-MD5", option.Md5) } @@ -756,7 +755,7 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction uploader.fastUploadHosts.Store(req.URL.Host, fastHostMark{at: time.Now().UnixNano(), bps: bps}) } ret.ETag = etag - ret.ContentMd5 = resp.Header.Get("Content-MD5") + ret.ContentMd5 = uploadedContentMd5(resp, option) return &ret, nil } @@ -793,7 +792,7 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction uploader.fastUploadHosts.Store(req.URL.Host, fastHostMark{at: time.Now().UnixNano(), bps: bps}) } ret.ETag = etag - ret.ContentMd5 = resp.Header.Get("Content-MD5") + ret.ContentMd5 = uploadedContentMd5(resp, option) return &ret, nil } @@ -869,3 +868,13 @@ func (b *watchdogBody) Close() error { b.sentAt.Store(time.Now().UnixNano()) return b.ReadCloser.Close() } + +// uploadedContentMd5 is the Content-MD5 the volume server checked and echoed. +// Under fips140=only the digest is not an MD5 and is never sent, so the +// caller's own digest stands. +func uploadedContentMd5(resp *http.Response, option *UploadOption) string { + if fips140.Enforced() { + return option.Md5 + } + return resp.Header.Get("Content-MD5") +} diff --git a/weed/replication/sink/s3sink/s3_sink.go b/weed/replication/sink/s3sink/s3_sink.go index 0ffc2aaa2a..893f185e53 100644 --- a/weed/replication/sink/s3sink/s3_sink.go +++ b/weed/replication/sink/s3sink/s3_sink.go @@ -1,6 +1,7 @@ package S3Sink import ( + "crypto/fips140" "encoding/base64" "fmt" "mime" @@ -221,7 +222,7 @@ func (s3sink *S3Sink) CreateEntry(key string, entry *filer_pb.Entry, signatures if entry.Attributes.Mime != "" { uploadInput.ContentType = aws.String(entry.Attributes.Mime) } - if len(entry.Attributes.Md5) > 0 { + if len(entry.Attributes.Md5) > 0 && !fips140.Enforced() { uploadInput.ContentMD5 = aws.String(base64.StdEncoding.EncodeToString([]byte(entry.Attributes.Md5))) } _, err = uploader.Upload(&uploadInput) diff --git a/weed/s3api/filer_multipart.go b/weed/s3api/filer_multipart.go index 107beb333d..6979af4a36 100644 --- a/weed/s3api/filer_multipart.go +++ b/weed/s3api/filer_multipart.go @@ -4,7 +4,6 @@ import ( "cmp" "container/heap" "context" - "crypto/md5" "crypto/rand" "encoding/base64" "encoding/hex" @@ -1965,7 +1964,7 @@ func calculateMultipartETag(partEntries map[int][]*filer_pb.Entry, completedPart glog.Warningf("calculateMultipartETag: failed to decode etag '%s' for part %d: %v", etag, partNumber, err) } } - return fmt.Sprintf("%x-%d", md5.Sum(etags), len(completedPartNumbers)) + return fmt.Sprintf("%x-%d", util.Md5(etags), len(completedPartNumbers)) } func decodePartChecksum(partNumber int, entries []*filer_pb.Entry, checksumHeaderName string) ([]byte, *filer_pb.Entry, error) { diff --git a/weed/s3api/fips140_only.go b/weed/s3api/fips140_only.go index d112dad26c..91e7e3b459 100644 --- a/weed/s3api/fips140_only.go +++ b/weed/s3api/fips140_only.go @@ -1,6 +1,9 @@ package s3api -import "crypto/fips140" +import ( + "bytes" + "crypto/fips140" +) // fips140Enforced reports whether the process runs with GODEBUG=fips140=only. // In that mode MD5, SHA-1 and HMAC-SHA1 panic, so SigV2, SSE-C and the SHA-1 @@ -8,3 +11,9 @@ import "crypto/fips140" // It is a variable so tests can enable the refusals without running the whole // test binary under fips140=only. var fips140Enforced = fips140.Enforced + +// contentMd5Matches compares a body digest with the client's Content-MD5. +// Under fips140=only the digest is not an MD5, so Content-MD5 goes unchecked. +func contentMd5Matches(digest, contentMd5 []byte) bool { + return fips140Enforced() || bytes.Equal(digest, contentMd5) +} diff --git a/weed/s3api/request_body.go b/weed/s3api/request_body.go index 462a218e5b..25ca50a457 100644 --- a/weed/s3api/request_body.go +++ b/weed/s3api/request_body.go @@ -131,7 +131,9 @@ func bindSignedPayload(r *http.Request, hashedPayload string) s3err.ErrorCode { if err != nil || len(decoded) != md5.Size { return s3err.ErrInvalidDigest } - contentMd5 = decoded + if !fips140Enforced() { + contentMd5 = decoded + } } if expected == nil && contentMd5 == nil { return s3err.ErrNone @@ -140,8 +142,10 @@ func bindSignedPayload(r *http.Request, hashedPayload string) s3err.ErrorCode { if emptySum := sha256.Sum256(nil); expected != nil && !bytes.Equal(expected, emptySum[:]) { return s3err.ErrContentSHA256Mismatch } - if emptySum := md5.Sum(nil); contentMd5 != nil && !bytes.Equal(contentMd5, emptySum[:]) { - return s3err.ErrBadDigest + if contentMd5 != nil { + if emptySum := md5.Sum(nil); !bytes.Equal(contentMd5, emptySum[:]) { + return s3err.ErrBadDigest + } } return s3err.ErrNone } diff --git a/weed/s3api/request_body_test.go b/weed/s3api/request_body_test.go index c4c092ce24..673fdc3bc9 100644 --- a/weed/s3api/request_body_test.go +++ b/weed/s3api/request_body_test.go @@ -263,3 +263,11 @@ func TestPrebufferedSignedBodyChecksContentMd5(t *testing.T) { _, err = io.ReadAll(req.Body) assert.ErrorIs(t, err, errContentMd5Mismatch) } + +func TestBodylessSignedRequestSkipsContentMd5UnderFIPS140Only(t *testing.T) { + setFIPS140Enforced(t, true) + emptySha256 := sha256.Sum256(nil) + req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:9000/bucket/key", nil) + req.Header.Set("Content-Md5", "AAAAAAAAAAAAAAAAAAAAAA==") + assert.Equal(t, s3err.ErrNone, bindSignedPayload(req, hex.EncodeToString(emptySha256[:]))) +} diff --git a/weed/s3api/s3api_object_handlers_copy.go b/weed/s3api/s3api_object_handlers_copy.go index 1b67c7bfd6..554c32f433 100644 --- a/weed/s3api/s3api_object_handlers_copy.go +++ b/weed/s3api/s3api_object_handlers_copy.go @@ -1263,7 +1263,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req // For zero-size files or invalid ranges, create an empty part with size 0 dstEntry.Attributes.FileSize = 0 dstEntry.Chunks = nil - dstEntry.Attributes.Md5 = md5.New().Sum(nil) + dstEntry.Attributes.Md5 = util.Md5(nil) } else { // Copy chunks that overlap with the range dstChunks, partMd5, err := s3a.copyChunksForRange(entry, startOffset, endOffset, dstAssignPath) @@ -1630,7 +1630,7 @@ func (s3a *S3ApiServer) copySingleChunkForRange(originalChunk, rangeChunk *filer // its ETag has to be recomputed; a whole-chunk copy reuses it. var digest hash.Hash if !isFullChunk { - digest = md5.New() + digest = util.NewMd5() } if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult, digest); err != nil { return nil, fmt.Errorf("stream chunk range: %w", err) @@ -1856,7 +1856,7 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e // md5Zeros hashes size zero bytes without a volume read — a copied range // that overlaps no source chunk assembles to all zeros. func md5Zeros(size int64) []byte { - h := md5.New() + h := util.NewMd5() var zeros [1 << 16]byte for size > 0 { n := min(size, int64(len(zeros))) @@ -1878,7 +1878,7 @@ func (s3a *S3ApiServer) copiedRangeMd5(ctx context.Context, entry *filer_pb.Entr return nil, err } defer reader.Close() - h := md5.New() + h := util.NewMd5() if _, err := io.Copy(h, reader); err != nil { return nil, err } diff --git a/weed/s3api/s3api_object_handlers_copy_etag_test.go b/weed/s3api/s3api_object_handlers_copy_etag_test.go index bdc557adab..fdf525fbd1 100644 --- a/weed/s3api/s3api_object_handlers_copy_etag_test.go +++ b/weed/s3api/s3api_object_handlers_copy_etag_test.go @@ -15,6 +15,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" ) @@ -446,7 +447,7 @@ func TestWriteEmptyCopyPartStoresMd5(t *testing.T) { if code != s3err.ErrNone { t.Fatalf("writeEmptyCopyPart: %v", code) } - const emptyMD5Hex = "d41d8cd98f00b204e9800998ecf8427e" + emptyMD5Hex := fmt.Sprintf("%x", util.Md5(nil)) if etag != emptyMD5Hex { t.Fatalf("writeEmptyCopyPart etag = %q, want %q", etag, emptyMD5Hex) } diff --git a/weed/s3api/s3api_object_handlers_copy_part_sse.go b/weed/s3api/s3api_object_handlers_copy_part_sse.go index 1fda5dd40e..92db85df57 100644 --- a/weed/s3api/s3api_object_handlers_copy_part_sse.go +++ b/weed/s3api/s3api_object_handlers_copy_part_sse.go @@ -2,7 +2,6 @@ package s3api import ( "context" - "crypto/md5" "encoding/base64" "encoding/json" "errors" @@ -20,6 +19,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" ) // errCopySourceSSEUnsupported is returned by openSourcePlaintextReader when @@ -421,19 +421,20 @@ func (s3a *S3ApiServer) writeEmptyCopyPart(dstBucket, dstObject, uploadID string return "", s3err.ErrInternalError } } - const emptyMD5Hex = "d41d8cd98f00b204e9800998ecf8427e" + emptyMd5 := util.Md5(nil) + emptyETag := fmt.Sprintf("%x", emptyMd5) if err := upload.mkFile(uploadDir, partName, nil, func(e *filer_pb.Entry) { if e.Attributes == nil { e.Attributes = &filer_pb.FuseAttributes{} } e.Attributes.FileSize = 0 - e.Attributes.Md5 = md5.New().Sum(nil) + e.Attributes.Md5 = emptyMd5 if e.Extended == nil { e.Extended = map[string][]byte{} } - e.Extended[s3_constants.ExtETagKey] = []byte(emptyMD5Hex) + e.Extended[s3_constants.ExtETagKey] = []byte(emptyETag) }); err != nil { return "", s3err.ErrInternalError } - return emptyMD5Hex, s3err.ErrNone + return emptyETag, s3err.ErrNone } diff --git a/weed/s3api/s3api_object_handlers_extract.go b/weed/s3api/s3api_object_handlers_extract.go index 04d1fe0c00..74d5c0b752 100644 --- a/weed/s3api/s3api_object_handlers_extract.go +++ b/weed/s3api/s3api_object_handlers_extract.go @@ -102,7 +102,7 @@ func (s3a *S3ApiServer) extractZipObject(w http.ResponseWriter, r *http.Request, requestQuery := parseRequestQuery(r) archiveMd5 := r.Header.Get("Content-Md5") var archiveMd5Hash hash.Hash - if archiveMd5 != "" { + if archiveMd5 != "" && !fips140Enforced() { archiveMd5Hash = md5.New() dataReader = io.TeeReader(dataReader, archiveMd5Hash) } diff --git a/weed/s3api/s3api_object_handlers_multipart.go b/weed/s3api/s3api_object_handlers_multipart.go index 6a9458a4f6..23486d1afc 100644 --- a/weed/s3api/s3api_object_handlers_multipart.go +++ b/weed/s3api/s3api_object_handlers_multipart.go @@ -1,7 +1,6 @@ package s3api import ( - "crypto/sha1" "encoding/base64" "encoding/json" "encoding/xml" @@ -23,6 +22,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" + "github.com/seaweedfs/seaweedfs/weed/util" ) const ( @@ -605,7 +605,7 @@ func (s3a *S3ApiServer) genPartUploadPath(bucket, uploadID string, partID int) s func (s3a *S3ApiServer) generateUploadID(object string) string { object = strings.TrimPrefix(object, "/") - h := sha1.New() + h := util.NewSha1() h.Write([]byte(object)) return fmt.Sprintf("%x", h.Sum(nil)) } diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index 54333504fc..f4e8bac6e5 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -3,7 +3,6 @@ package s3api import ( "bytes" "context" - "crypto/md5" "encoding/base64" "encoding/json" "errors" @@ -31,6 +30,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/security" weed_server "github.com/seaweedfs/seaweedfs/weed/server" stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" + "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/constants" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" "google.golang.org/grpc/codes" @@ -234,9 +234,9 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) } } - // Compute MD5 for ETag (md5.Sum of nil/empty = MD5 of empty content) - dirMd5 := md5.Sum(dirContent) - if expectedMd5, _ := validateContentMd5(r.Header); len(expectedMd5) > 0 && !bytes.Equal(dirMd5[:], expectedMd5) { + // ETag of the marker content, empty or not + dirMd5 := util.Md5(dirContent) + if expectedMd5, _ := validateContentMd5(r.Header); len(expectedMd5) > 0 && !contentMd5Matches(dirMd5, expectedMd5) { s3err.WriteErrorResponse(w, r, s3err.ErrBadDigest) return } @@ -287,7 +287,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) entry.Content = dirContent } entry.Attributes.Mime = objectContentType - entry.Attributes.Md5 = dirMd5[:] + entry.Attributes.Md5 = dirMd5 // Store ETag in extended attributes for consistency with regular objects if entry.Extended == nil { @@ -611,7 +611,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader // Each part is encrypted independently, then decrypted using metadata during GET partOffset := int64(0) - plaintextHash := md5.New() + plaintextHash := util.NewMd5() dataReader = io.TeeReader(dataReader, plaintextHash) // Parse the request's query string once. AWS SDK presigners hoist signed @@ -800,7 +800,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader s3a.deleteOrphanedChunks(chunkResult.FileChunks) return "", s3err.ErrInvalidDigest, SSEResponseMetadata{} } - if !bytes.Equal(md5Sum, expectedMd5) { + if !contentMd5Matches(md5Sum, expectedMd5) { glog.Warningf("putToFiler: Checksum verification failed, attempting to cleanup %d orphaned chunks", len(chunkResult.FileChunks)) s3a.deleteOrphanedChunks(chunkResult.FileChunks) return "", s3err.ErrBadDigest, SSEResponseMetadata{} diff --git a/weed/s3api/s3api_sosapi.go b/weed/s3api/s3api_sosapi.go index 67d1eac813..f67d7cb144 100644 --- a/weed/s3api/s3api_sosapi.go +++ b/weed/s3api/s3api_sosapi.go @@ -7,7 +7,6 @@ package s3api import ( "bytes" "context" - "crypto/md5" "encoding/hex" "encoding/xml" "errors" @@ -21,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/version" ) @@ -259,8 +259,7 @@ func (s3a *S3ApiServer) handleSOSAPIGetObject(w http.ResponseWriter, r *http.Req } // Calculate ETag from content - hash := md5.Sum(xmlData) - etag := hex.EncodeToString(hash[:]) + etag := hex.EncodeToString(util.Md5(xmlData)) // Set ETag header manually as ServeContent doesn't calculate it automatically w.Header().Set("ETag", "\""+etag+"\"") @@ -291,8 +290,7 @@ func (s3a *S3ApiServer) handleSOSAPIHeadObject(w http.ResponseWriter, r *http.Re } // Calculate ETag from content - hash := md5.Sum(xmlData) - etag := hex.EncodeToString(hash[:]) + etag := hex.EncodeToString(util.Md5(xmlData)) // Set response headers (no body for HEAD) w.Header().Set("Content-Type", "application/xml") diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index b4d9923cf7..f74dda7f22 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -3,6 +3,7 @@ package weed_server import ( "bytes" "context" + "crypto/fips140" "errors" "fmt" "io" @@ -64,7 +65,7 @@ func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r * writeJsonError(w, r, http.StatusInternalServerError, err) } } else if reply != nil { - if len(md5bytes) > 0 { + if len(md5bytes) > 0 && !fips140.Enforced() { md5InBase64 := util.Base64Encode(md5bytes) w.Header().Set("Content-MD5", md5InBase64) } @@ -104,8 +105,7 @@ func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWrite return nil, nil, fmt.Errorf("read input: %w", err) } md5bytes = util.Md5(buf.Bytes()) - headerMd5 := r.Header.Get("Content-Md5") - if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) { + if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { bufPool.Put(buf) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -120,8 +120,7 @@ func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWrite } md5bytes = md5Hash.Sum(nil) - headerMd5 := r.Header.Get("Content-Md5") - if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) { + if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { fs.filer.DeleteUncommittedChunks(ctx, fileChunks) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -153,8 +152,7 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter } md5bytes = md5Hash.Sum(nil) - headerMd5 := r.Header.Get("Content-Md5") - if headerMd5 != "" && !(util.Base64Encode(md5bytes) == headerMd5 || fmt.Sprintf("%x", md5bytes) == headerMd5) { + if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { fs.filer.DeleteUncommittedChunks(ctx, fileChunks) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -715,3 +713,13 @@ func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http } return filerResult, replyerr } + +// contentMd5Mismatch compares the body digest with the client's Content-MD5, +// base64 or hex. Under fips140=only the digest is not an MD5, so Content-MD5 +// goes unchecked. +func contentMd5Mismatch(md5bytes []byte, headerMd5 string) bool { + if headerMd5 == "" || fips140.Enforced() { + return false + } + return util.Base64Encode(md5bytes) != headerMd5 && fmt.Sprintf("%x", md5bytes) != headerMd5 +} diff --git a/weed/server/filer_server_handlers_write_upload.go b/weed/server/filer_server_handlers_write_upload.go index 5631e3e554..bc103f6742 100644 --- a/weed/server/filer_server_handlers_write_upload.go +++ b/weed/server/filer_server_handlers_write_upload.go @@ -3,7 +3,6 @@ package weed_server import ( "bytes" "context" - "crypto/md5" "encoding/base64" "errors" "fmt" @@ -69,7 +68,7 @@ func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.Respons } if int64(len(prefix)) < remainingInlineBudget { inlineAppend := append([]byte{}, prefix...) - md5Hash = md5.New() + md5Hash = util.NewMd5() _, _ = md5Hash.Write(inlineAppend) if len(inlineAppend) > 0 { stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc() @@ -88,7 +87,7 @@ func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.Respons return nil, nil, 0, fmt.Errorf("read input: %w", readErr), nil } if len(prefix) == 0 { - return nil, md5.New(), 0, nil, []byte{} + return nil, util.NewMd5(), 0, nil, []byte{} } if chunkSize <= 0 { return nil, nil, 0, fmt.Errorf("invalid chunk size %d for inline append promotion", chunkSize), nil @@ -103,7 +102,7 @@ func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.Respons func (fs *FilerServer) uploadReaderToChunks(ctx context.Context, r *http.Request, reader io.Reader, startOffset int64, chunkSize int32, fileName, contentType string, isAppend bool, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) { - md5Hash = md5.New() + md5Hash = util.NewMd5() chunkOffset = startOffset var partReader = io.NopCloser(io.TeeReader(reader, md5Hash)) @@ -272,7 +271,7 @@ func (fs *FilerServer) dataToChunkWithSSE(ctx context.Context, r *http.Request, stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc() return uploadErr } - chunkMd5 := md5.Sum(data) + chunkMd5 := util.Md5(data) chunkMd5B64 := base64.StdEncoding.EncodeToString(chunkMd5[:]) // upload the chunk to the volume server uploadResult, uploadErr, _ = fs.doUpload(ctx, urlLocation, dataReader, fileName, contentType, nil, auth, chunkMd5B64) diff --git a/weed/server/postgres/server.go b/weed/server/postgres/server.go index 16f99a83f4..27ef853e49 100644 --- a/weed/server/postgres/server.go +++ b/weed/server/postgres/server.go @@ -2,6 +2,7 @@ package postgres import ( "bufio" + "crypto/fips140" "crypto/md5" "crypto/rand" "crypto/tls" @@ -162,6 +163,9 @@ type FieldDescription struct { // NewPostgreSQLServer creates a new PostgreSQL protocol server func NewPostgreSQLServer(config *PostgreSQLServerConfig, masterAddr string) (*PostgreSQLServer, error) { + if config.AuthMethod == AuthMD5 && fips140.Enforced() { + return nil, fmt.Errorf("md5 authentication uses MD5, which GODEBUG=fips140=only refuses") + } if config.Port <= 0 { config.Port = DEFAULT_POSTGRES_PORT } diff --git a/weed/server/volume_server_handlers_write.go b/weed/server/volume_server_handlers_write.go index c4cc50a25b..ebdfe6d42a 100644 --- a/weed/server/volume_server_handlers_write.go +++ b/weed/server/volume_server_handlers_write.go @@ -3,6 +3,7 @@ package weed_server import ( "bytes" "context" + "crypto/fips140" "crypto/md5" "encoding/base64" "errors" @@ -32,6 +33,9 @@ func (vs *VolumeServer) replicaContentMd5(n *needle.Needle, contentMd5 string) s if !vs.FixJpgOrientation || contentMd5 == "" || !bytes.HasPrefix(n.Data, jpegStart) { return contentMd5 } + if fips140.Enforced() { + return "" + } if sum := md5.Sum(n.Data); base64.StdEncoding.EncodeToString(sum[:]) != contentMd5 { return "" } diff --git a/weed/sftpd/sftp_filer.go b/weed/sftpd/sftp_filer.go index 2f2a2b59ba..c934789bcc 100644 --- a/weed/sftpd/sftp_filer.go +++ b/weed/sftpd/sftp_filer.go @@ -3,7 +3,6 @@ package sftpd import ( "context" - "crypto/md5" "encoding/json" "errors" "fmt" @@ -603,7 +602,7 @@ func (fs *SftpServer) putFile(filepath string, reader io.Reader, user *user.User uploadUrl = normalizedUrl // Compute MD5 while uploading - hash := md5.New() + hash := util.NewMd5() body := io.TeeReader(reader, hash) // We can skip ContentLength if unknown (chunked transfer encoding) diff --git a/weed/storage/needle/needle_parse_upload.go b/weed/storage/needle/needle_parse_upload.go index f0b07e21db..d2fd47e70e 100644 --- a/weed/storage/needle/needle_parse_upload.go +++ b/weed/storage/needle/needle_parse_upload.go @@ -2,6 +2,7 @@ package needle import ( "bytes" + "crypto/fips140" "crypto/md5" "encoding/base64" "fmt" @@ -122,7 +123,10 @@ func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (p if expectedChecksum == "" { expectedChecksum = pu.ContentMd5 } - if expectedChecksum != "" { + if expectedChecksum != "" && fips140.Enforced() { + // fips140=only refuses MD5: keep the client's digest unchecked. + pu.ContentMd5 = expectedChecksum + } else if expectedChecksum != "" { h := md5.New() h.Write(pu.UncompressedData) pu.ContentMd5 = base64.StdEncoding.EncodeToString(h.Sum(nil)) diff --git a/weed/util/bytes.go b/weed/util/bytes.go index b3217a1955..6a6309157f 100644 --- a/weed/util/bytes.go +++ b/weed/util/bytes.go @@ -2,7 +2,6 @@ package util import ( "bytes" - "crypto/md5" "crypto/rand" "encoding/base64" "fmt" @@ -89,7 +88,7 @@ func Uint8toBytes(b []byte, v uint8) { // returns a 64 bit big int func HashStringToLong(dir string) (v int64) { - h := md5.New() + h := NewMd5() io.WriteString(h, dir) b := h.Sum(nil) @@ -114,7 +113,7 @@ func HashStringToLong(dir string) (v int64) { } func HashToInt32(data []byte) (v int32) { - h := md5.New() + h := NewMd5() h.Write(data) b := h.Sum(nil) @@ -135,7 +134,7 @@ func Base64Encode(data []byte) string { } func Md5(data []byte) []byte { - hash := md5.New() + hash := NewMd5() hash.Write(data) return hash.Sum(nil) } diff --git a/weed/util/fips140_hash.go b/weed/util/fips140_hash.go new file mode 100644 index 0000000000..3fed109bc1 --- /dev/null +++ b/weed/util/fips140_hash.go @@ -0,0 +1,44 @@ +package util + +import ( + "crypto/fips140" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "hash" +) + +var fips140Enforced = fips140.Enforced + +// NewMd5 returns an MD5 hash. GODEBUG=fips140=only refuses MD5, so there it +// returns SHA-256 cut to MD5's size: digests keep their length but differ. +func NewMd5() hash.Hash { + if fips140Enforced() { + return NewTruncatedSha256(md5.Size) + } + return md5.New() +} + +// NewSha1 is NewMd5 for SHA-1. +func NewSha1() hash.Hash { + if fips140Enforced() { + return NewTruncatedSha256(sha1.Size) + } + return sha1.New() +} + +// NewTruncatedSha256 returns SHA-256 keeping the first size bytes of the digest. +func NewTruncatedSha256(size int) hash.Hash { + return &truncatedHash{Hash: sha256.New(), size: size} +} + +type truncatedHash struct { + hash.Hash + size int +} + +func (h *truncatedHash) Size() int { return h.size } + +func (h *truncatedHash) Sum(b []byte) []byte { + return append(b, h.Hash.Sum(nil)[:h.size]...) +} diff --git a/weed/util/fips140_hash_test.go b/weed/util/fips140_hash_test.go new file mode 100644 index 0000000000..7375ce1a4b --- /dev/null +++ b/weed/util/fips140_hash_test.go @@ -0,0 +1,59 @@ +package util + +import ( + "bytes" + "crypto/fips140" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "testing" +) + +func setFIPS140Enforced(t *testing.T, enforced bool) { + t.Helper() + saved := fips140Enforced + fips140Enforced = func() bool { return enforced } + t.Cleanup(func() { fips140Enforced = saved }) +} + +func TestNewMd5KeepsMd5WhenNotEnforced(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses MD5 and SHA-1") + } + setFIPS140Enforced(t, false) + data := []byte("hello") + want := md5.Sum(data) + if got := Md5(data); !bytes.Equal(got, want[:]) { + t.Fatalf("Md5 = %x, want %x", got, want) + } + h := NewSha1() + h.Write(data) + wantSha1 := sha1.Sum(data) + if got := h.Sum(nil); !bytes.Equal(got, wantSha1[:]) { + t.Fatalf("NewSha1 = %x, want %x", got, wantSha1) + } +} + +func TestNewMd5UsesTruncatedSha256WhenEnforced(t *testing.T) { + setFIPS140Enforced(t, true) + data := []byte("hello") + full := sha256.Sum256(data) + + got := Md5(data) + if !bytes.Equal(got, full[:md5.Size]) { + t.Fatalf("Md5 = %x, want %x", got, full[:md5.Size]) + } + + h := NewSha1() + if h.Size() != sha1.Size { + t.Fatalf("NewSha1 size = %d, want %d", h.Size(), sha1.Size) + } + h.Write(data) + if got := h.Sum([]byte{0xff}); !bytes.Equal(got, append([]byte{0xff}, full[:sha1.Size]...)) { + t.Fatalf("NewSha1 Sum = %x", got) + } + + if HashStringToLong("/a/b") == 0 || HashToInt32([]byte("k")) == 0 { + t.Fatalf("hashes should be non-zero") + } +}