From 9ffb5fe18532cb1a023ef1c75b5bfde9026faf38 Mon Sep 17 00:00:00 2001 From: Martijn Hoekstra Date: Wed, 25 Nov 2026 05:17:26 +0100 Subject: [PATCH] filer, s3, filer.sync: one digest per cluster, set by the filer's -digest and followed by its clients (#12913) * util, filer: choose the digest at filer startup with -digest NewMd5 and NewSha1 returned SHA-256 cut to size whenever the process ran under GODEBUG=fips140=only, so the kind of digest a cluster stores followed each process's own environment. They now follow a digest mode set once at startup: util.SetDigest("md5"|"sha256"), or "" to keep following fips140.Enforced(). The default is unchanged. weed filer -digest, weed server -filer.digest and weed mini -filer.digest set it; fips140=only refuses md5 at startup. The leveldb2/leveldb3 directory-key marker follows the mode, as do the places that compare a NewMd5 digest with Content-MD5 or pass it on as one: S3 PutObject, filer HTTP uploads, the Content-MD5 the filer returns, and the uploader's Content-MD5 to volume servers. Places that verify Content-MD5 with a real MD5 (volume servers, S3 request bodies and archive uploads) keep keying on fips140.Enforced(), since they can check it whenever MD5 is available. Co-Authored-By: Claude Opus 5.5 * filer, command: report the filer's digest and make its clients use it GetFilerConfigurationResponse carries the filer's digest mode in a new field 16, digest. weed s3, mount, webdav, sftp, iam and filer.copy adopt it before they serve or write, so a gateway started with a different GODEBUG writes the same kind of ETag and chunk digest as the rest of the cluster. A process under fips140=only refuses a filer that reports md5. A filer that reports no digest predates the field; the client then keeps its own mode and logs a warning. Co-Authored-By: Claude Opus 5.5 * filer.sync, s3 sink: keep digests within one kind filer.sync copies entry digests and ETags as they are, so syncing a filer with digest sha256 into one with md5 left SHA-256 ETags in the md5 cluster. It now reads both filers' digests and refuses to start when they differ, with a warning when either filer does not report one. The S3 sink sent the entry digest as Content-MD5 unless its own process ran under fips140=only. From a sha256 source into a target that checks Content-MD5 every single-part upload failed with BadDigest and the backup retried it forever. It now asks the source filer for its digest once and forwards the entry digest only when that is md5. Co-Authored-By: Claude Opus 5.5 * filer.meta.backup, filer.backup, filer.replicate: keep digests within one kind filer.meta.backup opened its backup store in its own digest mode, so a copy of a sha256 filer made by a process outside fips140=only got MD5 directory keys and could not be opened as that filer's store. It now adopts the source filer's digest before the store opens. filer.backup and filer.replicate with a filer sink copied entry digests into the target filer without comparing digests, as filer.sync did before. Both now refuse, and exit, when the source and target filers report different digests. replication.CheckDigestsMatch is the shared check; filer.sync uses it too. weed server and weed mini apply -filer.digest before they start the master and volume server, so every part of the process hashes with one digest. Co-Authored-By: Claude Opus 5.5 * filer, filer.sync: refuse a peer filer with another digest; exit on mismatch Filers peering through the meta aggregator now compare digests. A peer with a store of its own would replay entries holding the other kind of digest into this filer's store, so its changes are refused and the reason logged on every reconnect. A fresh filer bootstrapping from such a peer refuses the copy, so a new filer whose digest differs from the existing filers' exits at startup. A peer on the same store writes into it directly, and refusing its stream would only starve this filer's subscribers, so that mismatch is logged as an error and the stream kept. filer.sync exits with status 1 when the two filers use different digests, as filer.backup and filer.replicate do: it is a configuration error a restart cannot fix. Co-Authored-By: Claude Opus 5.5 * filer: -digest help says a store keeps the digest it was created with The help text said existing data keeps the digest it was written with, which reads as if the flag could be changed on a store with data. Stores that hash keys stop finding existing entries under another digest, so the text now says to set it when the store is created, and that switching means copying the metadata into a new store with fs.meta.save and fs.meta.load. Co-Authored-By: Claude Opus 5.5 * filer, s3, replication, admin, iceberg: address review of the digest checks - A filer checks its peers' digests on every start, not only at the fresh-store bootstrap: the store signature is written when the store opens, so a fresh filer refused at bootstrap restarted as an initialized store and served without its peers' files. - Under digest sha256 with MD5 available (not fips140=only), a client's Content-MD5 is checked against a separate real MD5 of the body, in S3 object, part and directory-marker uploads and in filer HTTP uploads. It goes unchecked only when no MD5 can be computed. - filer.backup and filer.replicate exit only on a DigestMismatchError; a filer that cannot be reached is retried, so a backup started before its target is up resumes once the target answers. - The admin file browser and Iceberg compaction write chunks into a filer they do not follow at process level. They read that filer's digest and pass it to the chunk upload (ChunkedUploadOption.Digest), so their content and chunk digests match the filer's. Co-Authored-By: Claude Opus 5.5 * filer, s3 sink: retire digest-refused peers; no Content-MD5 for an unknown digest - A peer refused for its digest counts as unreachable: the check now runs before notePeerReachable and its error wraps errPeerUnreachable, so the subscribe loop retires the peer from the low watermarks after the usual grace instead of keeping its zero watermark, which held every aggregated subscriber at the settled horizon. - When the source filer's digest cannot be read, the S3 sink no longer sends the entry digest as Content-MD5: it may be a SHA-256 digest the target would reject. - TestCheckPeerDigest skips the cases that need MD5 locally under GODEBUG=fips140=only. Co-Authored-By: Claude Opus 5.5 * iceberg, util: tests for the per-filer digest The Iceberg tests' fake filer serves GetFilerConfiguration, which uploads now call to read the target filer's digest; it reports none, as a filer that predates the setting does. TestNewContentMd5 computes a real MD5, so it skips under GODEBUG=fips140=only. Co-Authored-By: Claude Opus 5.5 * filer: bound each startup peer digest read with a timeout CheckPeerDigests read each peer's configuration with the caller's context, which at startup has no deadline, so a peer that accepted the connection but never answered held the filer's startup. Each read now has its own peerDigestReadTimeout (10s, inside the one-minute announce cap), after which the peer is logged and skipped like an unreachable one. setDigestForTest restores the previous digest setting instead of the default. Co-Authored-By: Claude Opus 5.5 * util, s3, filer: one-shot digests for data held in memory Md5For hashes with md5.Sum or sha256.Sum256 instead of writing into a hash.Hash, and the Content-MD5 checks of S3 directory markers and of filer uploads saved inside the filer use BodyMd5Of on the bytes they already hold. Streaming uploads keep their io.TeeReader. Co-Authored-By: Claude Opus 5.5 * filer: hash Content-MD5 on the upload's digest hash, not on its body teeContentMd5 wrapped the request body in a TeeReader before uploadRequestToChunks. CodeQL's go/reflected-xss query follows the body from r.Body through the chunk upload to upload_content.go's w.Write(prepared.data), which it resolves to the response-writer wrappers in s3vectors, s3tables, webdav and server/common.go. Those flows exist on master from other sources (extract, tagging, the multipart POST); the wrapped body put them through lines this PR changed, so CodeQL reported six of them as new. newUploadHash now builds the digest hash that uploadReaderToChunks and the inline-append paths already tee the body into, and adds the separate MD5 there; uploadBodyMd5 reads it back for the check. The body reaches uploadRequestToChunks as on master. Behaviour is unchanged: under digest sha256 with MD5 available, Content-MD5 is checked against the body's MD5, including empty and inline appends. Checked with CodeQL 2.27.6 (go-queries 1.6.16, ReflectedXss.ql) on this tree: no flow of the nine reflected-XSS results passes a changed line. Co-Authored-By: Claude Opus 5.5 * replication: keep the ReadFilerSignature name and return the digest with it Renaming it to ReadFilerSignatureAndDigest left its other callers with an undefined function. Keep the name and add the digest to what it returns. Co-Authored-By: Claude Opus 5.5 * util: keep HashToInt32 off the digest mode HashToInt32 names things that processes derive on their own, such as a mount's local socket path and MQ partition key hashes. weed mount adopts a -digest=sha256 filer's digest before it names its socket, while weed shell mount.configure keeps md5 and dialed a different socket. Follow GODEBUG only, as before the digest setting. Co-Authored-By: Claude Opus 5.5 * filer.meta.backup: wait for the source filer's digest instead of exiting A backup with a saved offset used to start its stream loop and retry until the source filer answered. Reading the digest first made it exit when started before the filer. Retry the read; exit only when the digest is refused. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- other/java/client/src/main/proto/filer.proto | 1 + weed/admin/handlers/file_browser_grpc.go | 14 ++ weed/command/digest.go | 25 +++ weed/command/filer.go | 6 + weed/command/filer_backup.go | 7 + weed/command/filer_copy.go | 9 +- weed/command/filer_meta_backup.go | 23 +++ weed/command/filer_replication.go | 12 ++ weed/command/filer_sync.go | 7 +- weed/command/iam.go | 3 + weed/command/mini.go | 3 + weed/command/mount_common.go | 8 +- weed/command/s3.go | 3 + weed/command/server.go | 2 + weed/command/sftp.go | 3 + weed/command/webdav.go | 3 + weed/filer/filer.go | 53 ++++++ weed/filer/leveldb2/leveldb2_store.go | 3 +- weed/filer/leveldb3/leveldb3_store.go | 3 +- weed/filer/leveldb_handle/key_hash.go | 10 +- weed/filer/leveldb_handle/key_hash_test.go | 10 +- weed/filer/meta_aggregator.go | 30 +++- weed/filer/meta_aggregator_digest_test.go | 155 +++++++++++++++++ weed/operation/upload_chunked.go | 10 +- weed/operation/upload_chunked_digest_test.go | 60 +++++++ weed/operation/upload_content.go | 14 +- weed/pb/filer.proto | 1 + weed/pb/filer_pb/filer.pb.go | 13 +- weed/pb/filer_pb/filer_digest.go | 15 ++ weed/pb/filer_pb/filer_vtproto.pb.go | 45 +++++ weed/replication/digest.go | 68 ++++++++ weed/replication/digest_test.go | 68 ++++++++ weed/replication/replicator.go | 15 +- weed/replication/sink/filersink/filer_sink.go | 19 ++ weed/replication/sink/s3sink/s3_sink.go | 5 +- weed/replication/sink/s3sink/s3_sink_test.go | 21 +++ weed/replication/source/filer_source.go | 50 ++++++ weed/s3api/fips140_only.go | 9 +- weed/s3api/fips140_only_test.go | 34 ++++ weed/s3api/s3api_object_handlers_put.go | 10 +- weed/server/filer_grpc_server_admin.go | 2 + weed/server/filer_server.go | 3 + .../filer_server_handlers_write_autochunk.go | 67 ++++++-- ...er_handlers_write_autochunk_digest_test.go | 49 ++++++ .../filer_server_handlers_write_upload.go | 6 +- weed/util/bytes.go | 15 +- weed/util/fips140_hash.go | 162 +++++++++++++++++- weed/util/fips140_hash_test.go | 138 +++++++++++++++ weed/worker/tasks/iceberg/exec_test.go | 6 + weed/worker/tasks/iceberg/filer_io.go | 9 + 50 files changed, 1242 insertions(+), 65 deletions(-) create mode 100644 weed/command/digest.go create mode 100644 weed/filer/meta_aggregator_digest_test.go create mode 100644 weed/operation/upload_chunked_digest_test.go create mode 100644 weed/pb/filer_pb/filer_digest.go create mode 100644 weed/replication/digest.go create mode 100644 weed/replication/digest_test.go create mode 100644 weed/server/filer_server_handlers_write_autochunk_digest_test.go diff --git a/other/java/client/src/main/proto/filer.proto b/other/java/client/src/main/proto/filer.proto index 23e4848e9a..816092a205 100644 --- a/other/java/client/src/main/proto/filer.proto +++ b/other/java/client/src/main/proto/filer.proto @@ -681,6 +681,7 @@ message GetFilerConfigurationResponse { string filer_group = 13; int32 major_version = 14; int32 minor_version = 15; + string digest = 16; // "md5" or "sha256": the hash behind ETags and chunk digests } message SubscribeMetadataRequest { diff --git a/weed/admin/handlers/file_browser_grpc.go b/weed/admin/handlers/file_browser_grpc.go index e31a14bf43..f0eea20beb 100644 --- a/weed/admin/handlers/file_browser_grpc.go +++ b/weed/admin/handlers/file_browser_grpc.go @@ -18,6 +18,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" ) // Admin upload chunk size, matching s3api so files split into the same fid-sized pieces. @@ -149,10 +150,23 @@ func (h *FileBrowserHandlers) uploadFileGrpc(ctx context.Context, filePath strin }, nil } + var digest string + if err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error { + var readErr error + digest, readErr = filer_pb.ReadFilerDigest(ctx, client) + return readErr + }); err != nil { + return fmt.Errorf("read filer digest: %w", err) + } + if err := util.CheckDigest(digest); err != nil { + return fmt.Errorf("filer digest: %w", err) + } + chunkResult, err := operation.UploadReaderInChunks(ctx, reader, &operation.ChunkedUploadOption{ ChunkSize: adminUploadChunkSize, MimeType: mimeType, AssignFunc: assignFunc, + Digest: digest, LookupJwtFunc: func(lookupCtx context.Context, fileId string) security.EncodedJwt { return operation.LookupJwt(lookupCtx, h.adminServer.GetMasterClient().GetMaster(lookupCtx), h.adminServer.GetGrpcDialOption(), fileId) }, diff --git a/weed/command/digest.go b/weed/command/digest.go new file mode 100644 index 0000000000..11517d94df --- /dev/null +++ b/weed/command/digest.go @@ -0,0 +1,25 @@ +package command + +import ( + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// adoptFilerDigest makes this process write the kind of digest its filer +// uses, and exits when it cannot: a gateway writing the other kind would mix +// digest kinds in one bucket. +func adoptFilerDigest(filer string, digest string) { + if err := util.AdoptFilerDigest(filer, digest); err != nil { + glog.Fatalf("%v", err) + } +} + +// applyFilerDigest sets this process's digest mode from the filer's -digest +// flag, and exits when that setting is refused. weed server and weed mini call +// it before they start their master and volume server, so every part of the +// process hashes with one digest from the start. +func applyFilerDigest(digest string) { + if err := util.SetDigest(digest); err != nil { + glog.Fatalf("filer -digest: %v", err) + } +} diff --git a/weed/command/filer.go b/weed/command/filer.go index 43769fed98..26801e5c07 100644 --- a/weed/command/filer.go +++ b/weed/command/filer.go @@ -51,6 +51,9 @@ var ( // S3 gateway, whose remote-mount read paths dial the mounted endpoint directly. const allowUntrustedRemoteEndpointsUsage = "if true, a read of a remote-only entry accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints." +// filerDigestUsage documents -digest, shared by weed filer, server and mini. +const filerDigestUsage = "[md5|sha256] hash behind ETags, chunk digests and hashed store keys; S3, mount, WebDAV, SFTP and the other clients of this filer use it too. Empty follows GODEBUG: sha256 under fips140=only, md5 otherwise; fips140=only refuses md5. Set it when the store is created and keep it: a store holds one kind of digest, and switching means copying the metadata into a new store with fs.meta.save and fs.meta.load." + // iamSelfServiceRequiresGrantUsage documents the flag shared by every command // that runs the embedded IAM API. const iamSelfServiceRequiresGrantUsage = "if true, an identity needs an explicit iam: grant to manage its own access keys (CreateAccessKey, DeleteAccessKey, UpdateAccessKey, ListAccessKeys, GetUser), as on AWS. Default allows it to every authenticated identity." @@ -117,6 +120,7 @@ type FilerOptions struct { tusMaxSizeMB *int tusSessionExpiry *time.Duration s3ConfigFile *string // optional path to static S3 identity config + digest *string allowUntrustedRemoteEndpoints *bool remoteCacheEvictThreshold *float64 @@ -177,6 +181,7 @@ func init() { f.tusSessionExpiry = cmdFiler.Flag.Duration("tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"") f.allowUntrustedRemoteEndpoints = cmdFiler.Flag.Bool("allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) f.remoteCacheEvictThreshold = cmdFiler.Flag.Float64("remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables") + f.digest = cmdFiler.Flag.String("digest", "", filerDigestUsage) // start s3 on filer filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway") @@ -394,6 +399,7 @@ func runFiler(cmd *Command, args []string) bool { } func (fo *FilerOptions) startFiler() { + applyFilerDigest(*fo.digest) defaultMux := http.NewServeMux() publicVolumeMux := defaultMux diff --git a/weed/command/filer_backup.go b/weed/command/filer_backup.go index 38820e856d..4991a32163 100644 --- a/weed/command/filer_backup.go +++ b/weed/command/filer_backup.go @@ -15,6 +15,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/replication" "github.com/seaweedfs/seaweedfs/weed/replication/repl_util" "github.com/seaweedfs/seaweedfs/weed/replication/sink" "github.com/seaweedfs/seaweedfs/weed/replication/sink/filersink" @@ -185,6 +186,12 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err) } dataSink.SetSourceFiler(filerSource) + if err := replication.CheckSinkDigest(filerSource.GrpcAddress(), filerSource.Digest, dataSink); err != nil { + if replication.IsDigestMismatch(err) { + glog.Exitf("%v", err) + } + return resumeTsNs, err + } var flattener *s3VersionFlattener if *backupOption.s3FlattenVersions { diff --git a/weed/command/filer_copy.go b/weed/command/filer_copy.go index 748a3fcc36..e0df946786 100644 --- a/weed/command/filer_copy.go +++ b/weed/command/filer_copy.go @@ -103,11 +103,15 @@ func runCopy(cmd *Command, args []string) bool { copyOptions.grpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client") - masters, collection, replication, dirBuckets, maxMB, cipher, err := readFilerConfiguration(copyOptions.grpcDialOption, filerAddress) + masters, collection, replication, dirBuckets, maxMB, cipher, digest, err := readFilerConfiguration(copyOptions.grpcDialOption, filerAddress) if err != nil { fmt.Printf("read from filer %s: %v\n", filerAddress, err) return false } + if err := util.AdoptFilerDigest(string(filerAddress), digest); err != nil { + fmt.Printf("%v\n", err) + return false + } if strings.HasPrefix(urlPath, dirBuckets+"/") { restPath := urlPath[len(dirBuckets)+1:] if strings.Index(restPath, "/") > 0 { @@ -181,7 +185,7 @@ func runCopy(cmd *Command, args []string) bool { return true } -func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, err error) { +func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, digest string, err error) { err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { @@ -190,6 +194,7 @@ func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb. masters, collection, replication, maxMB = resp.Masters, resp.Collection, resp.Replication, resp.MaxMb dirBuckets = resp.DirBuckets cipher = resp.Cipher + digest = resp.Digest return nil }) return diff --git a/weed/command/filer_meta_backup.go b/weed/command/filer_meta_backup.go index 1d00b9ac4b..1ef2b6747a 100644 --- a/weed/command/filer_meta_backup.go +++ b/weed/command/filer_meta_backup.go @@ -88,6 +88,9 @@ func runFilerMetaBackup(cmd *Command, args []string) bool { *metaBackup.backupFilerConfig, err, "backup_filer", "filer") } + if err := metaBackup.adoptSourceDigest(); err != nil { + glog.Exitf("%v", err) + } if err := metaBackup.initStore(v); err != nil { glog.V(0).Infof("init backup filer store: %v", err) return true @@ -135,6 +138,26 @@ func runFilerMetaBackup(cmd *Command, args []string) bool { } } +// adoptSourceDigest makes this process hash with the source filer's digest +// before the backup store opens: the store's directory keys and its digest +// marker must match the filer's, or the copy cannot be opened as that filer's +// store. +func (metaBackup *FilerMetaBackupOptions) adoptSourceDigest() error { + var digest string + for { + err := metaBackup.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) (err error) { + digest, err = filer_pb.ReadFilerDigest(context.Background(), client) + return err + }) + if err == nil { + break + } + glog.Warningf("read digest of filer %s: %v; retrying", *metaBackup.filerAddress, err) + time.Sleep(1747 * time.Millisecond) + } + return util.AdoptFilerDigest(*metaBackup.filerAddress, digest) +} + func (metaBackup *FilerMetaBackupOptions) initStore(v *viper.Viper) error { // load configuration for default filer store hasDefaultStoreConfigured := false diff --git a/weed/command/filer_replication.go b/weed/command/filer_replication.go index f53fdfb488..3c4de16519 100644 --- a/weed/command/filer_replication.go +++ b/weed/command/filer_replication.go @@ -3,6 +3,7 @@ package command import ( "context" "strings" + "time" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/replication" @@ -79,6 +80,17 @@ func runFilerReplicate(cmd *Command, args []string) bool { } replicator := replication.NewReplicator(config, "source.filer.", dataSink) + for { + err := replicator.CheckSinkDigest() + if err == nil { + break + } + if replication.IsDigestMismatch(err) { + glog.Exitf("%v", err) + } + glog.Warningf("%v; retrying", err) + time.Sleep(2 * time.Second) + } for { key, m, onSuccessFn, onFailureFn, err := notificationInput.ReceiveMessage() diff --git a/weed/command/filer_sync.go b/weed/command/filer_sync.go index cf7d210668..2f10c1eb88 100644 --- a/weed/command/filer_sync.go +++ b/weed/command/filer_sync.go @@ -205,17 +205,20 @@ func runFilerSynchronize(cmd *Command, args []string) bool { go statsCollect.StartMetricsServer(*syncOptions.metricsHttpIp, *syncOptions.metricsHttpPort) // read a filer signature - aFilerSignature, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA) + aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA) if aFilerErr != nil { glog.Errorf("get filer 'a' signature %d error from %s to %s: %v", aFilerSignature, *syncOptions.filerA, *syncOptions.filerB, aFilerErr) return true } // read b filer signature - bFilerSignature, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB) + bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB) if bFilerErr != nil { glog.Errorf("get filer 'b' signature %d error from %s to %s: %v", bFilerSignature, *syncOptions.filerA, *syncOptions.filerB, bFilerErr) return true } + if err := replication.CheckDigestsMatch(*syncOptions.filerA, aFilerDigest, *syncOptions.filerB, bFilerDigest); err != nil { + glog.Exitf("%v", err) + } // register graceful shutdown hook to save checkpoints grace.OnInterrupt(func() { diff --git a/weed/command/iam.go b/weed/command/iam.go index 713421c10e..2ccc2bc9a9 100644 --- a/weed/command/iam.go +++ b/weed/command/iam.go @@ -87,6 +87,7 @@ func (iamopt *IamOptions) startIamServer() bool { util.LoadSecurityConfiguration() grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") + var digest string for { err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) @@ -94,6 +95,7 @@ func (iamopt *IamOptions) startIamServer() bool { return fmt.Errorf("get filer configuration: %v", err) } glog.V(0).Infof("IAM read filer configuration: %s", resp) + digest = resp.Digest return nil }) if err != nil { @@ -104,6 +106,7 @@ func (iamopt *IamOptions) startIamServer() bool { break } } + adoptFilerDigest(*iamopt.filer, digest) masters := pb.ServerAddresses(*iamopt.masters).ToAddressMap() router := mux.NewRouter().SkipClean(true) diff --git a/weed/command/mini.go b/weed/command/mini.go index 62aae6fd1d..4d08d98780 100644 --- a/weed/command/mini.go +++ b/weed/command/mini.go @@ -496,6 +496,7 @@ func initMiniFilerFlags() { miniFilerOptions.tusMaxSizeMB = cmdMini.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB") miniFilerOptions.tusSessionExpiry = cmdMini.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration") miniFilerOptions.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) + miniFilerOptions.digest = cmdMini.Flag.String("filer.digest", "", filerDigestUsage) miniFilerOptions.remoteCacheEvictThreshold = cmdMini.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables") miniFilerOptions.idleTimeout = cmdMini.Flag.Int("filer.idleTimeout", 10, "connection idle seconds") } @@ -1762,6 +1763,8 @@ func runMini(cmd *Command, args []string) bool { // startMiniServices starts all mini services with proper dependency coordination func startMiniServices(miniWhiteList []string, allServicesReady chan struct{}) { + applyFilerDigest(*miniFilerOptions.digest) + // Determine bind IP for health checks bindIp := getBindIp() diff --git a/weed/command/mount_common.go b/weed/command/mount_common.go index 5b64ad06b8..5979f863fd 100644 --- a/weed/command/mount_common.go +++ b/weed/command/mount_common.go @@ -140,13 +140,14 @@ func peerStringOrEmpty(p *string) string { } // connectToFiler retries the filer handshake, returning the cluster's cipher -// setting and bucket root. +// setting and bucket root, and adopts the filer's digest. func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialOption, cipher bool, bucketRootPath string, ok bool) { // try to connect to filer filerAddresses = pb.ServerAddresses(*option.filer).ToAddresses() util.LoadSecurityConfiguration() grpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client") var err error + var digest string for i := 0; i < 10; i++ { err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) @@ -155,6 +156,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr } cipher = resp.Cipher bucketRootPath = resp.DirBuckets + digest = resp.Digest return nil }) if err == nil { @@ -168,6 +170,10 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr glog.Errorf("failed to talk to filer %v: %v", filerAddresses, err) return nil, nil, false, "", false } + if err = util.AdoptFilerDigest(*option.filer, digest); err != nil { + glog.Errorf("%v", err) + return nil, nil, false, "", false + } if bucketRootPath == "" { bucketRootPath = "/buckets" } diff --git a/weed/command/s3.go b/weed/command/s3.go index 36de7fc104..25164458f3 100644 --- a/weed/command/s3.go +++ b/weed/command/s3.go @@ -325,6 +325,7 @@ func (s3opt *S3Options) startS3Server() bool { var filerMaxMB int32 // the filer's -encryptVolumeData, which turns on chunk encryption here too var filerCipher bool + var filerDigest string for { err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { @@ -339,6 +340,7 @@ func (s3opt *S3Options) startS3Server() bool { metricsAddress, metricsIntervalSec = resp.MetricsAddress, int(resp.MetricsIntervalSec) filerMaxMB = int32(resp.MaxMb) filerCipher = resp.Cipher + filerDigest = resp.Digest glog.V(0).Infof("S3 read filer buckets dir: %s", filerBucketsPath) glog.V(0).Infof("S3 read filer maxMB: %d", filerMaxMB) if len(masterAddresses) > 0 { @@ -354,6 +356,7 @@ func (s3opt *S3Options) startS3Server() bool { break } } + adoptFilerDigest(*s3opt.filer, filerDigest) go stats_collect.LoopPushingMetric("s3", stats_collect.SourceName(uint32(*s3opt.port)), metricsAddress, metricsIntervalSec) diff --git a/weed/command/server.go b/weed/command/server.go index ec29f5e0b6..86b543baaf 100644 --- a/weed/command/server.go +++ b/weed/command/server.go @@ -142,6 +142,7 @@ func init() { filerOptions.tusMaxSizeMB = cmdServer.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB") filerOptions.tusSessionExpiry = cmdServer.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"") filerOptions.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) + filerOptions.digest = cmdServer.Flag.String("filer.digest", "", filerDigestUsage) filerOptions.remoteCacheEvictThreshold = cmdServer.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables") filerOptions.idleTimeout = cmdServer.Flag.Int("filer.idleTimeout", 10, "connection idle seconds") @@ -482,6 +483,7 @@ func runServer(cmd *Command, args []string) bool { return ms != nil && ms.Topo.FreshMinted() } } + applyFilerDigest(*filerOptions.digest) go func() { time.Sleep(1 * time.Second) filerOptions.startFiler() diff --git a/weed/command/sftp.go b/weed/command/sftp.go index 1366579cdb..373d94587e 100644 --- a/weed/command/sftp.go +++ b/weed/command/sftp.go @@ -132,6 +132,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool { var metricsAddress string var metricsIntervalSec int var filerGroup string + var digest string // Connect to the filer service and try to retrieve basic configuration. for { @@ -142,6 +143,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool { } metricsAddress, metricsIntervalSec = resp.MetricsAddress, int(resp.MetricsIntervalSec) filerGroup = resp.FilerGroup + digest = resp.Digest glog.V(0).Infof("SFTP read filer configuration, using filer at: %s", filerAddress) return nil }) @@ -153,6 +155,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool { break } } + adoptFilerDigest(*sftpOpt.filer, digest) go stats_collect.LoopPushingMetric("sftp", stats_collect.SourceName(uint32(*sftpOpt.port)), metricsAddress, metricsIntervalSec) diff --git a/weed/command/webdav.go b/weed/command/webdav.go index 66ca2de7d1..cd1d0626b8 100644 --- a/weed/command/webdav.go +++ b/weed/command/webdav.go @@ -115,6 +115,7 @@ func (wo *WebDavOption) startWebDav() bool { grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client") var cipher bool + var digest string // connect to filer for { err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { @@ -123,6 +124,7 @@ func (wo *WebDavOption) startWebDav() bool { return fmt.Errorf("get filer %s configuration: %v", filerAddress, err) } cipher = resp.Cipher + digest = resp.Digest return nil }) if err != nil { @@ -133,6 +135,7 @@ func (wo *WebDavOption) startWebDav() bool { break } } + adoptFilerDigest(*wo.filer, digest) ws, webdavServer_err := weed_server.NewWebDavServer(&weed_server.WebDavOption{ Filer: filerAddress, diff --git a/weed/filer/filer.go b/weed/filer/filer.go index 35b7ee55cf..2b5d86e5e2 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -245,6 +245,52 @@ func (f *Filer) buildRemoteStorageClient(ctx context.Context, remoteConf *remote return remote_storage.GetRemoteStorage(remoteConf) } +// CheckPeerDigests compares the digests of the cluster's other filers with +// this filer's, on every start and before the fresh-store bootstrap. Checking +// only at bootstrap is not enough: the store signature is written when the +// store opens, so a fresh filer refused at bootstrap would restart as an +// initialized store, skip the bootstrap and serve without its peers' files. +// A peer that cannot be reached, or does not answer within +// peerDigestReadTimeout, is skipped; checkPeerDigest decides the rest. +func (f *Filer) CheckPeerDigests(ctx context.Context, self pb.ServerAddress, nodes []*master_pb.ClusterNodeUpdate) error { + for _, node := range nodes { + peer := pb.ServerAddress(node.Address) + if peer.Equals(self) { + continue + } + signature, digest, err := f.readPeerDigest(ctx, peer) + if err != nil { + glog.Warningf("check digest of peer filer %s: %v", peer, err) + continue + } + if err := checkPeerDigest(peer, digest, signature == f.Signature); err != nil { + return err + } + } + return nil +} + +// peerDigestReadTimeout bounds each peer's configuration read at startup, so a +// peer that accepts the connection but never answers is skipped rather than +// holding the filer's startup. A variable so tests can shorten it. +var peerDigestReadTimeout = 10 * time.Second + +// readPeerDigest reads a peer filer's store signature and digest within +// peerDigestReadTimeout. +func (f *Filer) readPeerDigest(ctx context.Context, peer pb.ServerAddress) (signature int32, digest string, err error) { + ctx, cancel := context.WithTimeout(ctx, peerDigestReadTimeout) + defer cancel() + err = pb.WithFilerClient(false, f.UniqueFilerId, peer, f.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return err + } + signature, digest = resp.Signature, resp.Digest + return nil + }) + return +} + func (f *Filer) MaybeBootstrapFromOnePeer(ctx context.Context, self pb.ServerAddress, existingNodes []*master_pb.ClusterNodeUpdate, snapshotTime time.Time) (err error) { if len(existingNodes) == 0 { return @@ -260,6 +306,13 @@ func (f *Filer) MaybeBootstrapFromOnePeer(ctx context.Context, self pb.ServerAdd glog.V(0).Infof("bootstrap from %v clientId:%d", earliestNode.Address, f.UniqueFilerId) return pb.WithFilerClient(false, f.UniqueFilerId, pb.ServerAddress(earliestNode.Address), f.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return fmt.Errorf("read configuration of %s: %w", earliestNode.Address, err) + } + if err := checkPeerDigest(pb.ServerAddress(earliestNode.Address), resp.Digest, false); err != nil { + return err + } return filer_pb.StreamBfs(ctx, client, "/", snapshotTime.UnixNano(), func(parentPath util.FullPath, pbEntry *filer_pb.Entry, entryTsNs int64) error { entry := FromPbEntry(string(parentPath), pbEntry) peerTsNs := entryTsNs diff --git a/weed/filer/leveldb2/leveldb2_store.go b/weed/filer/leveldb2/leveldb2_store.go index 62dc81ade1..709d8a5cad 100644 --- a/weed/filer/leveldb2/leveldb2_store.go +++ b/weed/filer/leveldb2/leveldb2_store.go @@ -3,7 +3,6 @@ package leveldb import ( "bytes" "context" - "crypto/fips140" "crypto/md5" "fmt" "io" @@ -118,7 +117,7 @@ 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 { + if err := leveldb_handle.CheckKeyHash(store.dbs, weed_util.DigestIsSha256(), store.ReadOnly); err != nil { store.Shutdown() return err } diff --git a/weed/filer/leveldb3/leveldb3_store.go b/weed/filer/leveldb3/leveldb3_store.go index a172197058..d1c7124d3b 100644 --- a/weed/filer/leveldb3/leveldb3_store.go +++ b/weed/filer/leveldb3/leveldb3_store.go @@ -3,7 +3,6 @@ package leveldb import ( "bytes" "context" - "crypto/fips140" "crypto/md5" "fmt" "io" @@ -139,7 +138,7 @@ 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 { + if err := leveldb_handle.CheckKeyHash([]*leveldb_handle.DB{db}, weed_util.DigestIsSha256(), store.ReadOnly); err != nil { db.Close() return nil, err } diff --git a/weed/filer/leveldb_handle/key_hash.go b/weed/filer/leveldb_handle/key_hash.go index 0f1eaa3f8a..eaa3af2c25 100644 --- a/weed/filer/leveldb_handle/key_hash.go +++ b/weed/filer/leveldb_handle/key_hash.go @@ -10,9 +10,9 @@ import ( 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. +// Under digest sha256 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 { @@ -22,9 +22,9 @@ func CheckKeyHash(dbs []*DB, sha256Keys, readOnly bool) error { } switch { case marked && !sha256Keys: - return fmt.Errorf("%s was created under GODEBUG=fips140=only and can only be opened with it", db.name) + return fmt.Errorf("%s was created with digest sha256 and can only be opened with it (-digest=sha256 or GODEBUG=fips140=only)", 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) + return fmt.Errorf("%s hashes directory keys with MD5, which digest sha256 does not; copy the metadata with fs.meta.save from a filer with -digest=md5 and fs.meta.load into a new store", db.name) case !marked && sha256Keys: unmarked = append(unmarked, db) } diff --git a/weed/filer/leveldb_handle/key_hash_test.go b/weed/filer/leveldb_handle/key_hash_test.go index 7961aa4fdf..5e230ef0b4 100644 --- a/weed/filer/leveldb_handle/key_hash_test.go +++ b/weed/filer/leveldb_handle/key_hash_test.go @@ -30,24 +30,24 @@ func TestCheckKeyHashMarksEmptyDatabases(t *testing.T) { 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) + if err == nil || !strings.Contains(err.Error(), "digest sha256") { + t.Fatalf("marked databases opened with digest md5: %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) + t.Fatalf("empty databases with digest md5: %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) + t.Fatalf("md5 keys with digest md5: %v", err) } if err := CheckKeyHash(dbs, true, false); err == nil || !strings.Contains(err.Error(), "MD5") { - t.Fatalf("md5 keys under fips140=only: %v", err) + t.Fatalf("md5 keys with digest sha256: %v", err) } if _, err := dbs[0].Get(sha256KeyMarker, nil); err == nil { t.Fatalf("a refused check must not mark the empty database") diff --git a/weed/filer/meta_aggregator.go b/weed/filer/meta_aggregator.go index 061f7ed21f..81be3153b3 100644 --- a/weed/filer/meta_aggregator.go +++ b/weed/filer/meta_aggregator.go @@ -635,10 +635,16 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress, } }() - peerSignature, err := ma.readFilerStoreSignature(ctx, peer) + peerSignature, peerDigest, err := ma.readFilerStoreSignature(ctx, peer) if err != nil { return lastTsNs, fmt.Errorf("%w %s: %v", errPeerUnreachable, peer, err) } + if err := checkPeerDigest(peer, peerDigest, peerSignature == f.Signature); err != nil { + glog.Errorf("%v", err) + // A refused peer counts as unreachable, so the loop retires it from the + // low watermarks instead of letting its zero hold every subscriber. + return lastTsNs, fmt.Errorf("%w %s: %v", errPeerUnreachable, peer, err) + } ma.notePeerReachable(peer, stopChan) ma.notePeerStore(peer, stopChan, peerSignature == f.Signature) @@ -1003,18 +1009,38 @@ func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs return nil } -func (ma *MetaAggregator) readFilerStoreSignature(ctx context.Context, peer pb.ServerAddress) (sig int32, err error) { +// readFilerStoreSignature returns a peer filer's store signature and the +// digest it reports, empty for a filer that predates the setting. +func (ma *MetaAggregator) readFilerStoreSignature(ctx context.Context, peer pb.ServerAddress) (sig int32, digest string, err error) { err = pb.WithFilerClient(false, 0, peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return err } sig = resp.Signature + digest = resp.Digest return nil }) return } +// checkPeerDigest compares a peer filer's digest with this filer's. A peer +// with a store of its own would replay entries holding the other kind of +// digest into this filer's store, so its changes are refused. A peer on the +// same store writes into it directly; refusing its stream would only starve +// this filer's subscribers of its changes, so the mismatch is logged and the +// stream kept. A peer that reports no digest predates the setting. +func checkPeerDigest(peer pb.ServerAddress, peerDigest string, sharedStore bool) error { + if peerDigest == "" || peerDigest == util.Digest() { + return nil + } + if sharedStore { + glog.Errorf("peer filer %s on this filer's store uses digest %s and this filer uses digest %s; the store holds digests of both kinds", peer, peerDigest, util.Digest()) + return nil + } + return fmt.Errorf("peer filer %s uses digest %s and this filer uses digest %s; not replaying its metadata, which would put digests of both kinds into this filer's store", peer, peerDigest, util.Digest()) +} + const ( MetaOffsetPrefix = "Meta" ) diff --git a/weed/filer/meta_aggregator_digest_test.go b/weed/filer/meta_aggregator_digest_test.go new file mode 100644 index 0000000000..d4f8db1531 --- /dev/null +++ b/weed/filer/meta_aggregator_digest_test.go @@ -0,0 +1,155 @@ +package filer + +import ( + "context" + "crypto/fips140" + "fmt" + "net" + "strconv" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +func TestCheckPeerDigest(t *testing.T) { + defer util.SetDigest("") + cases := []struct { + own, peer string + shared bool + refuse bool + }{ + {util.DigestMd5, util.DigestMd5, false, false}, + {util.DigestSha256, util.DigestSha256, false, false}, + {util.DigestMd5, "", false, false}, + {util.DigestMd5, util.DigestSha256, false, true}, + {util.DigestSha256, util.DigestMd5, false, true}, + {util.DigestMd5, util.DigestSha256, true, false}, + } + for _, c := range cases { + if c.own == util.DigestMd5 && fips140.Enforced() { + continue + } + if err := util.SetDigest(c.own); err != nil { + t.Fatal(err) + } + err := checkPeerDigest("peer:8888", c.peer, c.shared) + if (err != nil) != c.refuse { + t.Errorf("own %s, peer %q, shared store %v: checkPeerDigest = %v, want refused %v", c.own, c.peer, c.shared, err, c.refuse) + } + } +} + +// otherDigestFiler is a peer filer with a store of its own that reports a +// digest of the other kind. +type otherDigestFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + digest string +} + +func (f *otherDigestFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + return &filer_pb.GetFilerConfigurationResponse{Signature: 7, Digest: f.digest}, nil +} + +// TestRefusedPeerIsRetiredLikeAnUnreachableOne checks that a peer refused for +// its digest starts the unreachable clock, so the subscribe loop retires it +// from the low watermarks rather than keeping it at zero for every +// aggregated subscriber. +func TestRefusedPeerIsRetiredLikeAnUnreachableOne(t *testing.T) { + t.Cleanup(func() { util.SetDigest("") }) + if err := util.SetDigest(util.DigestSha256); err != nil { + t.Fatal(err) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, &otherDigestFiler{digest: util.DigestMd5}) + go server.Serve(ln) + defer server.Stop() + _, portStr, err := net.SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portStr) + if err != nil || grpcPort <= 10000 { + t.Skipf("listener port %q cannot carry the filer's gRPC offset", portStr) + } + peer := pb.ServerAddress(fmt.Sprintf("127.0.0.1:%d", grpcPort-10000)) + ma := NewMetaAggregator(&Filer{Signature: 1}, pb.ServerAddress("127.0.0.1:2"), grpc.WithTransportCredentials(insecure.NewCredentials())) + defer ma.Shutdown() + + ma.OnPeerUpdate(&master_pb.ClusterNodeUpdate{Address: string(peer), IsAdd: true}, time.Now()) + deadline := time.Now().Add(10 * time.Second) + for { + ma.peerChansLock.Lock() + _, noted := ma.peerUnreachableSinceNs[peer] + ma.peerChansLock.Unlock() + if noted { + return + } + if time.Now().After(deadline) { + t.Fatal("a peer refused for its digest never started the unreachable clock") + } + time.Sleep(50 * time.Millisecond) + } +} + +// silentFiler is a peer filer that accepts the connection but never answers +// GetFilerConfiguration. +type silentFiler struct { + filer_pb.UnimplementedSeaweedFilerServer +} + +func (silentFiler) GetFilerConfiguration(ctx context.Context, _ *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + <-ctx.Done() + return nil, ctx.Err() +} + +// TestCheckPeerDigestsSkipsASilentPeer checks that a peer that never answers +// its configuration read is skipped after peerDigestReadTimeout, so it cannot +// hold the filer's startup. +func TestCheckPeerDigestsSkipsASilentPeer(t *testing.T) { + saved := peerDigestReadTimeout + t.Cleanup(func() { peerDigestReadTimeout = saved }) + peerDigestReadTimeout = 300 * time.Millisecond + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, silentFiler{}) + go server.Serve(ln) + defer server.Stop() + _, portStr, err := net.SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + grpcPort, err := strconv.Atoi(portStr) + if err != nil || grpcPort <= 10000 { + t.Skipf("listener port %q cannot carry the filer's gRPC offset", portStr) + } + peer := pb.ServerAddress(fmt.Sprintf("127.0.0.1:%d", grpcPort-10000)) + f := &Filer{Signature: 1, GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())} + + done := make(chan error, 1) + go func() { + done <- f.CheckPeerDigests(context.Background(), "127.0.0.1:2", []*master_pb.ClusterNodeUpdate{{Address: string(peer)}}) + }() + select { + case err := <-done: + if err != nil { + t.Fatalf("a silent peer should be skipped, got %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("CheckPeerDigests waited on a peer that never answers") + } +} diff --git a/weed/operation/upload_chunked.go b/weed/operation/upload_chunked.go index e59e5cfa53..67f8c32f33 100644 --- a/weed/operation/upload_chunked.go +++ b/weed/operation/upload_chunked.go @@ -47,6 +47,10 @@ type ChunkedUploadOption struct { AssignFunc func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) UploadFunc func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) // Optional: for testing LookupJwtFunc func(ctx context.Context, fileId string) security.EncodedJwt // Optional: renews the volume JWT for a cleanup delete + + // Digest names the target filer's digest, so the content and chunk + // digests match what that filer holds; empty uses this process's mode. + Digest string } var chunkBufferPool = sync.Pool{ @@ -64,7 +68,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 := util.NewMd5() + md5Hash := util.NewMd5For(opt.Digest) var partReader = io.TeeReader(reader, md5Hash) var fileChunks []*filer_pb.FileChunk @@ -183,7 +187,7 @@ uploadLoop: }() // Hash and prepare only this bounded chunk before minting its volume JWT. - chunkMd5 := util.Md5(buf.Bytes()) + chunkMd5 := util.Md5For(opt.Digest, buf.Bytes()) chunkMd5B64 := base64.StdEncoding.EncodeToString(chunkMd5[:]) var prepared *preparedUpload if opt.UploadFunc == nil { @@ -356,7 +360,7 @@ func uploadChunk(ctx context.Context, assignResult *AssignResult, data []byte, p // chunkUploadOption holds the settings that shape a chunk's bytes, shared by // its preparation and every upload of it. func chunkUploadOption(opt *ChunkedUploadOption) *UploadOption { - return &UploadOption{Cipher: opt.Cipher, MimeType: opt.MimeType} + return &UploadOption{Cipher: opt.Cipher, MimeType: opt.MimeType, Digest: opt.Digest} } // chunkHolders returns the assigned volume plus its replica holders. diff --git a/weed/operation/upload_chunked_digest_test.go b/weed/operation/upload_chunked_digest_test.go new file mode 100644 index 0000000000..6533982b02 --- /dev/null +++ b/weed/operation/upload_chunked_digest_test.go @@ -0,0 +1,60 @@ +package operation + +import ( + "bytes" + "context" + "crypto/fips140" + "crypto/md5" + "crypto/sha256" + "encoding/base64" + "testing" +) + +// TestUploadChunksUseTargetDigest checks that ChunkedUploadOption.Digest, not +// this process's digest mode, decides the content and chunk digests: a writer +// into a sha256 filer computes truncated SHA-256 even in an md5 process, and +// the chunk upload carries the digest name so no MD5 Content-MD5 is sent. +func TestUploadChunksUseTargetDigest(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses digest md5") + } + payload := []byte("chunk written into a filer of another digest") + sha := sha256.Sum256(payload) + md := md5.Sum(payload) + for _, c := range []struct { + digest string + want []byte + }{ + {"sha256", sha[:md5.Size]}, + {"md5", md[:]}, + } { + var uploadedDigest, uploadedMd5 string + result, err := uploadReaderInChunks(context.Background(), bytes.NewReader(payload), &ChunkedUploadOption{ + ChunkSize: 65536, + Digest: c.digest, + AssignFunc: func(context.Context, int, uint64) (*VolumeAssignRequest, *AssignResult, error) { + return nil, &AssignResult{Fid: "3,01637037d6", Url: "unused"}, nil + }, + UploadFunc: func(_ context.Context, data []byte, opt *UploadOption) (*UploadResult, error) { + uploadedDigest, uploadedMd5 = opt.Digest, opt.Md5 + return &UploadResult{Size: uint32(len(data)), ContentMd5: opt.Md5}, nil + }, + }, func([]byte, *UploadOption) (*preparedUpload, error) { + t.Fatal("custom uploader must receive original bytes") + return nil, nil + }) + if err != nil { + t.Fatal(err) + } + wantB64 := base64.StdEncoding.EncodeToString(c.want) + if uploadedDigest != c.digest || uploadedMd5 != wantB64 { + t.Errorf("digest %s: chunk upload carried digest %q and Md5 %s, want %q and %s", c.digest, uploadedDigest, uploadedMd5, c.digest, wantB64) + } + if got := result.Md5Hash.Sum(nil); !bytes.Equal(got, c.want) { + t.Errorf("digest %s: content digest %x, want %x", c.digest, got, c.want) + } + if len(result.FileChunks) != 1 || result.FileChunks[0].ETag != wantB64 { + t.Errorf("digest %s: chunk ETag %v, want %s", c.digest, result.FileChunks, wantB64) + } + } +} diff --git a/weed/operation/upload_content.go b/weed/operation/upload_content.go index c4212f211b..3051464cde 100644 --- a/weed/operation/upload_content.go +++ b/weed/operation/upload_content.go @@ -3,7 +3,6 @@ package operation import ( "bytes" "context" - "crypto/fips140" "encoding/base64" "encoding/json" "errors" @@ -58,7 +57,8 @@ type UploadOption struct { Jwt security.EncodedJwt RetryForever bool Md5 string - WantMd5 bool // compute Content-MD5 from the data when Md5 is unset and the upload is not ciphered + WantMd5 bool // compute Content-MD5 from the data when Md5 is unset and the upload is not ciphered + Digest string // the target filer's digest, which Md5 is in; empty means this process's mode BytesBuffer *bytes.Buffer SourceUrl string // optional: for logging when reading from a remote source MaxAttempts int // <=0 uses the default @@ -316,7 +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 == "" { - uploadOption.Md5 = base64.StdEncoding.EncodeToString(util.Md5(data)) + uploadOption.Md5 = base64.StdEncoding.EncodeToString(util.Md5For(uploadOption.Digest, data)) } fileId, uploadResult, err = uploader.uploadWithRetryData(func() (fileId string, host string, auth security.EncodedJwt, fsync bool, err error) { @@ -543,6 +543,7 @@ func (uploader *Uploader) doUploadData(ctx context.Context, prepared *preparedUp MimeType: "", PairMap: nil, Jwt: option.Jwt, + Digest: option.Digest, BytesBuffer: option.BytesBuffer, stallWatchdogDisarmed: option.stallWatchdogDisarmed, }) @@ -574,6 +575,7 @@ func (uploader *Uploader) doUploadData(ctx context.Context, prepared *preparedUp PairMap: option.PairMap, Jwt: option.Jwt, Md5: option.Md5, + Digest: option.Digest, BytesBuffer: option.BytesBuffer, stallWatchdogDisarmed: option.stallWatchdogDisarmed, }) @@ -615,7 +617,7 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction if option.IsInputCompressed { h.Set("Content-Encoding", "gzip") } - if option.Md5 != "" && !fips140.Enforced() { + if option.Md5 != "" && !util.DigestIsSha256For(option.Digest) { h.Set("Content-MD5", option.Md5) } @@ -870,10 +872,10 @@ func (b *watchdogBody) Close() error { } // 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 +// Under digest sha256 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() { + if util.DigestIsSha256For(option.Digest) { return option.Md5 } return resp.Header.Get("Content-MD5") diff --git a/weed/pb/filer.proto b/weed/pb/filer.proto index 028091de01..112b2e1ee2 100644 --- a/weed/pb/filer.proto +++ b/weed/pb/filer.proto @@ -694,6 +694,7 @@ message GetFilerConfigurationResponse { string filer_group = 13; int32 major_version = 14; int32 minor_version = 15; + string digest = 16; // "md5" or "sha256": the hash behind ETags and chunk digests } message SubscribeMetadataRequest { diff --git a/weed/pb/filer_pb/filer.pb.go b/weed/pb/filer_pb/filer.pb.go index 5f093ea95d..5bbaaf3907 100644 --- a/weed/pb/filer_pb/filer.pb.go +++ b/weed/pb/filer_pb/filer.pb.go @@ -4282,6 +4282,7 @@ type GetFilerConfigurationResponse struct { FilerGroup string `protobuf:"bytes,13,opt,name=filer_group,json=filerGroup,proto3" json:"filer_group,omitempty"` MajorVersion int32 `protobuf:"varint,14,opt,name=major_version,json=majorVersion,proto3" json:"major_version,omitempty"` MinorVersion int32 `protobuf:"varint,15,opt,name=minor_version,json=minorVersion,proto3" json:"minor_version,omitempty"` + Digest string `protobuf:"bytes,16,opt,name=digest,proto3" json:"digest,omitempty"` // "md5" or "sha256": the hash behind ETags and chunk digests unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -4414,6 +4415,13 @@ func (x *GetFilerConfigurationResponse) GetMinorVersion() int32 { return 0 } +func (x *GetFilerConfigurationResponse) GetDigest() string { + if x != nil { + return x.Digest + } + return "" +} + type SubscribeMetadataRequest struct { state protoimpl.MessageState `protogen:"open.v1"` ClientName string `protobuf:"bytes,1,opt,name=client_name,json=clientName,proto3" json:"client_name,omitempty"` @@ -7861,7 +7869,7 @@ const file_filer_proto_rawDesc = "" + "\x0eremote_time_ns\x18\x02 \x01(\x03R\fremoteTimeNs\x12 \n" + "\fstop_time_ns\x18\x03 \x01(\x03R\n" + "stopTimeNs\"\x1e\n" + - "\x1cGetFilerConfigurationRequest\"\xe8\x03\n" + + "\x1cGetFilerConfigurationRequest\"\x80\x04\n" + "\x1dGetFilerConfigurationResponse\x12\x18\n" + "\amasters\x18\x01 \x03(\tR\amasters\x12 \n" + "\vreplication\x18\x02 \x01(\tR\vreplication\x12\x1e\n" + @@ -7882,7 +7890,8 @@ const file_filer_proto_rawDesc = "" + "\vfiler_group\x18\r \x01(\tR\n" + "filerGroup\x12#\n" + "\rmajor_version\x18\x0e \x01(\x05R\fmajorVersion\x12#\n" + - "\rminor_version\x18\x0f \x01(\x05R\fminorVersion\"\xfd\x03\n" + + "\rminor_version\x18\x0f \x01(\x05R\fminorVersion\x12\x16\n" + + "\x06digest\x18\x10 \x01(\tR\x06digest\"\xfd\x03\n" + "\x18SubscribeMetadataRequest\x12\x1f\n" + "\vclient_name\x18\x01 \x01(\tR\n" + "clientName\x12\x1f\n" + diff --git a/weed/pb/filer_pb/filer_digest.go b/weed/pb/filer_pb/filer_digest.go new file mode 100644 index 0000000000..4a94ec61e5 --- /dev/null +++ b/weed/pb/filer_pb/filer_digest.go @@ -0,0 +1,15 @@ +package filer_pb + +import "context" + +// ReadFilerDigest returns the digest a filer reports, empty for a filer that +// predates the setting. Writers that put chunks into a filer other than the +// one their process follows pass it to the chunk upload, so the digests they +// write match the filer's. +func ReadFilerDigest(ctx context.Context, client SeaweedFilerClient) (string, error) { + resp, err := client.GetFilerConfiguration(ctx, &GetFilerConfigurationRequest{}) + if err != nil { + return "", err + } + return resp.Digest, nil +} diff --git a/weed/pb/filer_pb/filer_vtproto.pb.go b/weed/pb/filer_pb/filer_vtproto.pb.go index e746edab7c..e8084935fb 100644 --- a/weed/pb/filer_pb/filer_vtproto.pb.go +++ b/weed/pb/filer_pb/filer_vtproto.pb.go @@ -3951,6 +3951,15 @@ func (m *GetFilerConfigurationResponse) MarshalToSizedBufferVT(dAtA []byte) (int i -= len(m.unknownFields) copy(dAtA[i:], m.unknownFields) } + if len(m.Digest) > 0 { + i -= len(m.Digest) + copy(dAtA[i:], m.Digest) + i = protohelpers.EncodeVarint(dAtA, i, uint64(len(m.Digest))) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0x82 + } if m.MinorVersion != 0 { i = protohelpers.EncodeVarint(dAtA, i, uint64(m.MinorVersion)) i-- @@ -8330,6 +8339,10 @@ func (m *GetFilerConfigurationResponse) SizeVT() (n int) { if m.MinorVersion != 0 { n += 1 + protohelpers.SizeOfVarint(uint64(m.MinorVersion)) } + l = len(m.Digest) + if l > 0 { + n += 2 + l + protohelpers.SizeOfVarint(uint64(l)) + } n += len(m.unknownFields) return n } @@ -20645,6 +20658,38 @@ func (m *GetFilerConfigurationResponse) UnmarshalVT(dAtA []byte) error { break } } + case 16: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Digest", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protohelpers.ErrIntOverflow + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return protohelpers.ErrInvalidLength + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return protohelpers.ErrInvalidLength + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Digest = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := protohelpers.Skip(dAtA[iNdEx:]) diff --git a/weed/replication/digest.go b/weed/replication/digest.go new file mode 100644 index 0000000000..ead75588c4 --- /dev/null +++ b/weed/replication/digest.go @@ -0,0 +1,68 @@ +package replication + +import ( + "errors" + "fmt" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/replication/sink" +) + +// DigestMismatchError reports two filers that use different digests. It is a +// configuration error a restart cannot fix, unlike a filer that cannot be +// reached. +type DigestMismatchError struct { + FilerA, DigestA, FilerB, DigestB string +} + +func (e *DigestMismatchError) Error() string { + return fmt.Sprintf("filer %s uses digest %s and filer %s uses digest %s; replication would copy digests of one kind into the other", e.FilerA, e.DigestA, e.FilerB, e.DigestB) +} + +// IsDigestMismatch reports whether err is or wraps a DigestMismatchError. +func IsDigestMismatch(err error) bool { + var mismatch *DigestMismatchError + return errors.As(err, &mismatch) +} + +// CheckDigestsMatch refuses replication between filers that use different +// digests, with a DigestMismatchError: replication copies entry digests and +// ETags as they are, so one side would hold digests of the other kind. A +// filer that reports none predates the setting and cannot be checked. +func CheckDigestsMatch(filerA, digestA, filerB, digestB string) error { + switch { + case digestA == "" || digestB == "": + glog.Warningf("cannot check that filers %s and %s use the same digest: one of them does not report it", filerA, filerB) + case digestA != digestB: + return &DigestMismatchError{FilerA: filerA, DigestA: digestA, FilerB: filerB, DigestB: digestB} + } + return nil +} + +// digestTarget is a sink that writes into a filer and can say which digest +// that filer uses. +type digestTarget interface { + TargetFiler() string + TargetDigest() (string, error) +} + +// CheckSinkDigest refuses a sink that writes into a filer whose digest differs +// from the source filer's, with a DigestMismatchError; a filer that cannot be +// reached gives an ordinary error the caller can retry. Sinks that do not +// write into a filer (S3, cloud storage, local files) are not checked: they +// hold no filer digests. +func CheckSinkDigest(sourceFiler string, sourceDigest func() (string, error), dataSink sink.ReplicationSink) error { + target, ok := dataSink.(digestTarget) + if !ok { + return nil + } + digestA, err := sourceDigest() + if err != nil { + return fmt.Errorf("read digest of source filer %s: %w", sourceFiler, err) + } + digestB, err := target.TargetDigest() + if err != nil { + return fmt.Errorf("read digest of target filer %s: %w", target.TargetFiler(), err) + } + return CheckDigestsMatch(sourceFiler, digestA, target.TargetFiler(), digestB) +} diff --git a/weed/replication/digest_test.go b/weed/replication/digest_test.go new file mode 100644 index 0000000000..48282ff4e4 --- /dev/null +++ b/weed/replication/digest_test.go @@ -0,0 +1,68 @@ +package replication + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/replication/sink" +) + +func TestCheckDigestsMatch(t *testing.T) { + cases := []struct { + a, b string + refuse bool + }{ + {"md5", "md5", false}, + {"sha256", "sha256", false}, + {"sha256", "md5", true}, + {"md5", "sha256", true}, + {"", "sha256", false}, + {"md5", "", false}, + } + for _, c := range cases { + err := CheckDigestsMatch("a:8888", c.a, "b:8888", c.b) + if (err != nil) != c.refuse || IsDigestMismatch(err) != c.refuse { + t.Errorf("CheckDigestsMatch(%q, %q) = %v, want refused as a mismatch %v", c.a, c.b, err, c.refuse) + } + } +} + +// fakeSink is a ReplicationSink that writes nowhere. +type fakeSink struct{ sink.ReplicationSink } + +// fakeFilerSink is a sink writing into a filer that reports digest. +type fakeFilerSink struct { + fakeSink + digest string + err error +} + +func (f fakeFilerSink) TargetFiler() string { return "target:8888" } + +func (f fakeFilerSink) TargetDigest() (string, error) { return f.digest, f.err } + +func TestCheckSinkDigest(t *testing.T) { + source := func(digest string, err error) func() (string, error) { + return func() (string, error) { return digest, err } + } + cases := []struct { + name string + source func() (string, error) + sink sink.ReplicationSink + refuse bool + mismatch bool + }{ + {"non-filer sink is not checked", source("", errors.New("unreachable")), fakeSink{}, false, false}, + {"same digest", source("sha256", nil), fakeFilerSink{digest: "sha256"}, false, false}, + {"different digests", source("sha256", nil), fakeFilerSink{digest: "md5"}, true, true}, + {"target predates the setting", source("md5", nil), fakeFilerSink{digest: ""}, false, false}, + {"source unreachable", source("", errors.New("unreachable")), fakeFilerSink{digest: "md5"}, true, false}, + {"target unreachable", source("md5", nil), fakeFilerSink{err: errors.New("unreachable")}, true, false}, + } + for _, c := range cases { + err := CheckSinkDigest("source:8888", c.source, c.sink) + if (err != nil) != c.refuse || IsDigestMismatch(err) != c.mismatch { + t.Errorf("%s: CheckSinkDigest = %v, want refused %v, as a mismatch %v", c.name, err, c.refuse, c.mismatch) + } + } +} diff --git a/weed/replication/replicator.go b/weed/replication/replicator.go index fbdc320a8d..190e39a630 100644 --- a/weed/replication/replicator.go +++ b/weed/replication/replicator.go @@ -40,6 +40,12 @@ func NewReplicator(sourceConfig util.Configuration, configPrefix string, dataSin } } +// CheckSinkDigest refuses a filer sink whose filer uses a different digest +// from the source filer's; see CheckSinkDigest. +func (r *Replicator) CheckSinkDigest() error { + return CheckSinkDigest(r.source.GrpcAddress(), r.source.Digest, r.sink) +} + func (r *Replicator) Replicate(ctx context.Context, key string, message *filer_pb.EventNotification) error { if message.IsFromOtherCluster && r.sink.GetName() == "filer" { return nil @@ -172,16 +178,19 @@ func metadataEventTarget(key string, newEntry *filer_pb.Entry, newParentPath str return util.Join(targetParent, newEntry.Name), targetParent } -func ReadFilerSignature(grpcDialOption grpc.DialOption, filer pb.ServerAddress) (filerSignature int32, readErr error) { +// ReadFilerSignature returns the filer's signature and the digest it reports, +// empty for a filer that predates the setting. +func ReadFilerSignature(grpcDialOption grpc.DialOption, filer pb.ServerAddress) (filerSignature int32, digest string, readErr error) { if readErr = pb.WithFilerClient(false, 0, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { if resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}); err != nil { return fmt.Errorf("GetFilerConfiguration %s: %v", filer, err) } else { filerSignature = resp.Signature + digest = resp.Digest } return nil }); readErr != nil { - return 0, readErr + return 0, "", readErr } - return filerSignature, nil + return filerSignature, digest, nil } diff --git a/weed/replication/sink/filersink/filer_sink.go b/weed/replication/sink/filersink/filer_sink.go index 7773c4bcca..87be78e02b 100644 --- a/weed/replication/sink/filersink/filer_sink.go +++ b/weed/replication/sink/filersink/filer_sink.go @@ -116,6 +116,25 @@ func (fs *FilerSink) SetSourceFiler(s *source.FilerSource) { fs.filerSource = s } +// TargetFiler names the filer this sink writes into. +func (fs *FilerSink) TargetFiler() string { + return fs.grpcAddress +} + +// TargetDigest returns the digest the target filer reports, empty for a +// filer that predates the setting. +func (fs *FilerSink) TargetDigest() (digest string, err error) { + err = fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return err + } + digest = resp.Digest + return nil + }) + return +} + // SetUploader sets a custom uploader for this sink, used when the target // cluster requires different TLS certificates than the global config. // Must be called during initialization, before any replication goroutines diff --git a/weed/replication/sink/s3sink/s3_sink.go b/weed/replication/sink/s3sink/s3_sink.go index 893f185e53..4b6d9e7d03 100644 --- a/weed/replication/sink/s3sink/s3_sink.go +++ b/weed/replication/sink/s3sink/s3_sink.go @@ -1,7 +1,6 @@ package S3Sink import ( - "crypto/fips140" "encoding/base64" "fmt" "mime" @@ -33,6 +32,7 @@ const maxMetadataSize = 2 * 1024 type S3Sink struct { conn s3iface.S3API filerSource *source.FilerSource + sourceDigestIsMd5 func() bool isIncremental bool keepPartSize bool s3DisableContentMD5Validation bool @@ -116,6 +116,7 @@ func (s3sink *S3Sink) Initialize(configuration util.Configuration, prefix string func (s3sink *S3Sink) SetSourceFiler(s *source.FilerSource) { s3sink.filerSource = s + s3sink.sourceDigestIsMd5 = s.DigestIsMd5 } func (s3sink *S3Sink) initialize(awsAccessKeyId, awsSecretAccessKey string) error { @@ -222,7 +223,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 && !fips140.Enforced() { + if len(entry.Attributes.Md5) > 0 && s3sink.sourceDigestIsMd5() { uploadInput.ContentMD5 = aws.String(base64.StdEncoding.EncodeToString([]byte(entry.Attributes.Md5))) } _, err = uploader.Upload(&uploadInput) diff --git a/weed/replication/sink/s3sink/s3_sink_test.go b/weed/replication/sink/s3sink/s3_sink_test.go index 5d62e08ac8..6b64bced8f 100644 --- a/weed/replication/sink/s3sink/s3_sink_test.go +++ b/weed/replication/sink/s3sink/s3_sink_test.go @@ -1,6 +1,7 @@ package S3Sink import ( + "encoding/base64" "io" "net/http" "net/url" @@ -237,3 +238,23 @@ func TestToMetadataPrefersCanonicalKeyOnCaseCollision(t *testing.T) { require.Equal(t, "canonical", *metadata["project"]) } } + +func TestS3SinkCreateEntryForwardsOnlyMd5DigestsAsContentMd5(t *testing.T) { + digest := []byte("0123456789abcdef") + forwarded := base64.StdEncoding.EncodeToString(digest) + for _, sourceIsMd5 := range []bool{true, false} { + sink, rt := newCapturingS3Sink(t) + sink.sourceDigestIsMd5 = func() bool { return sourceIsMd5 } + entry := &filer_pb.Entry{ + Attributes: &filer_pb.FuseAttributes{Md5: digest}, + Content: []byte("data"), + } + require.NoError(t, sink.CreateEntry("/dir/test.bin", entry, nil)) + require.NotNil(t, rt.uploadReq, "uploader should have issued a PUT") + if sourceIsMd5 { + require.Equal(t, forwarded, rt.uploadReq.Header.Get("Content-Md5")) + } else { + require.NotEqual(t, forwarded, rt.uploadReq.Header.Get("Content-Md5"), "a sha256 digest must not go out as Content-MD5") + } + } +} diff --git a/weed/replication/source/filer_source.go b/weed/replication/source/filer_source.go index 256ab443d0..2fb4dce206 100644 --- a/weed/replication/source/filer_source.go +++ b/weed/replication/source/filer_source.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strings" + "sync" "google.golang.org/grpc" @@ -39,6 +40,10 @@ type FilerSource struct { signature int32 httpClient *util_http_client.HTTPClient jwtForFiler security.FilerJwtProvider + + digestMu sync.Mutex + digestKnown bool + digest string } func (fs *FilerSource) Initialize(configuration util.Configuration, prefix string) error { @@ -81,6 +86,11 @@ func (fs *FilerSource) SetFilerJwtProvider(provider security.FilerJwtProvider) { // ProxyByFiler reports whether chunk reads are proxied through the source // filer. A proxied 404 can also mean the filer found no volume locations, so it // does not isolate a missing needle the way a direct volume read's 404 does. +// GrpcAddress names the source filer. +func (fs *FilerSource) GrpcAddress() string { + return fs.grpcAddress +} + func (fs *FilerSource) ProxyByFiler() bool { return fs.proxyByFiler } @@ -89,6 +99,46 @@ func (fs *FilerSource) FilerJwt() security.FilerJwtProvider { return fs.jwtForFiler } +// Digest returns the digest the source filer reports, empty for a filer that +// predates the setting. It asks the filer once and remembers the answer; a +// failed query is not remembered, so the next call asks again. +func (fs *FilerSource) Digest() (string, error) { + fs.digestMu.Lock() + defer fs.digestMu.Unlock() + if fs.digestKnown { + return fs.digest, nil + } + err := fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return err + } + fs.digest = resp.Digest + return nil + }) + if err != nil { + return "", err + } + fs.digestKnown = true + return fs.digest, nil +} + +// DigestIsMd5 reports whether the source filer's entry digests are MD5s. A +// filer that does not report its digest predates the setting and is taken to +// use this process's digest mode. A filer that cannot be reached is taken not +// to, so its digests are not sent where an MD5 is expected. +func (fs *FilerSource) DigestIsMd5() bool { + digest, err := fs.Digest() + if err != nil { + glog.Warningf("read digest of source filer %s: %v", fs.grpcAddress, err) + return false + } + if digest == "" { + return !util.DigestIsSha256() + } + return digest == util.DigestMd5 +} + func (fs *FilerSource) LookupFileId(ctx context.Context, part string) (fileUrls []string, err error) { vid2Locations := make(map[string]*filer_pb.Locations) diff --git a/weed/s3api/fips140_only.go b/weed/s3api/fips140_only.go index 91e7e3b459..5b07a10a6f 100644 --- a/weed/s3api/fips140_only.go +++ b/weed/s3api/fips140_only.go @@ -12,8 +12,9 @@ import ( // 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) +// contentMd5Matches compares the body's MD5, from util.BodyMd5, with the +// client's Content-MD5. bodyMd5 is nil only under fips140=only with digest +// sha256, where no MD5 can be computed, and Content-MD5 then goes unchecked. +func contentMd5Matches(bodyMd5, contentMd5 []byte) bool { + return bodyMd5 == nil || bytes.Equal(bodyMd5, contentMd5) } diff --git a/weed/s3api/fips140_only_test.go b/weed/s3api/fips140_only_test.go index 3717acef48..74b17e481c 100644 --- a/weed/s3api/fips140_only_test.go +++ b/weed/s3api/fips140_only_test.go @@ -2,6 +2,7 @@ package s3api import ( "bytes" + "crypto/fips140" "crypto/md5" "encoding/base64" "net/http" @@ -12,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" ) // setFIPS140Enforced overrides fips140Enforced for the duration of the test. @@ -199,3 +201,35 @@ func TestFIPS140OnlySHA1ChunkedTrailer(t *testing.T) { }) } } + +// TestContentMd5CheckedInBothDigests checks that a client's Content-MD5 is +// verified against the body's real MD5 under digest md5 and digest sha256, +// and goes unchecked only when no MD5 can be computed. +func TestContentMd5CheckedInBothDigests(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses MD5") + } + t.Cleanup(func() { util.SetDigest("") }) + body := []byte("hello") + right := md5.Sum(body) + wrong := md5.Sum([]byte("other")) + for _, digest := range []string{util.DigestMd5, util.DigestSha256} { + if err := util.SetDigest(digest); err != nil { + t.Fatal(err) + } + contentMd5Hash := util.NewContentMd5() + if contentMd5Hash != nil { + contentMd5Hash.Write(body) + } + bodyMd5 := util.BodyMd5(util.Md5(body), contentMd5Hash) + if !contentMd5Matches(bodyMd5, right[:]) { + t.Errorf("digest %s: the right Content-MD5 was refused", digest) + } + if contentMd5Matches(bodyMd5, wrong[:]) { + t.Errorf("digest %s: a wrong Content-MD5 matched", digest) + } + } + if !contentMd5Matches(nil, wrong[:]) { + t.Error("without a body MD5 Content-MD5 should go unchecked") + } +} diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index 815056f80d..567ad47cac 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -247,7 +247,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) // ETag of the marker content, empty or not dirMd5 := util.Md5(dirContent) - if expectedMd5, _ := validateContentMd5(r.Header); len(expectedMd5) > 0 && !contentMd5Matches(dirMd5, expectedMd5) { + if expectedMd5, _ := validateContentMd5(r.Header); len(expectedMd5) > 0 && !contentMd5Matches(util.BodyMd5Of(dirMd5, dirContent), expectedMd5) { s3err.WriteErrorResponse(w, r, s3err.ErrBadDigest) return } @@ -626,6 +626,12 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader plaintextHash := util.NewMd5() dataReader = io.TeeReader(dataReader, plaintextHash) + var contentMd5Hash hash.Hash + if r.Header.Get("Content-Md5") != "" { + if contentMd5Hash = util.NewContentMd5(); contentMd5Hash != nil { + dataReader = io.TeeReader(dataReader, contentMd5Hash) + } + } // Parse the request's query string once. AWS SDK presigners hoist signed // headers such as x-amz-sdk-checksum-algorithm into the URL's query string, @@ -813,7 +819,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader s3a.deleteOrphanedChunks(chunkResult.FileChunks) return "", s3err.ErrInvalidDigest, SSEResponseMetadata{} } - if !contentMd5Matches(md5Sum, expectedMd5) { + if !contentMd5Matches(util.BodyMd5(md5Sum, contentMd5Hash), 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/server/filer_grpc_server_admin.go b/weed/server/filer_grpc_server_admin.go index 14a73265cf..2722e70ebb 100644 --- a/weed/server/filer_grpc_server_admin.go +++ b/weed/server/filer_grpc_server_admin.go @@ -14,6 +14,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/version" ) @@ -161,6 +162,7 @@ func (fs *FilerServer) GetFilerConfiguration(ctx context.Context, req *filer_pb. FilerGroup: fs.option.FilerGroup, MajorVersion: version.MAJOR_VERSION, MinorVersion: version.MINOR_VERSION, + Digest: util.Digest(), } glog.V(4).InfofCtx(ctx, "GetFilerConfiguration: %v", t) diff --git a/weed/server/filer_server.go b/weed/server/filer_server.go index 8270a30599..21dc03518e 100644 --- a/weed/server/filer_server.go +++ b/weed/server/filer_server.go @@ -414,6 +414,9 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption) glog.Warningf("%s cannot list existing peers: %v; retrying", option.Host, listErr) time.Sleep(2 * time.Second) } + if err := fs.filer.CheckPeerDigests(context.Background(), option.Host, existingNodes); err != nil { + glog.Fatalf("%s: %v", option.Host, err) + } startFromTime := time.Now().Add(-filer.LogFlushInterval) if isFresh { glog.V(0).Infof("%s bootstrap from peers %+v", option.Host, existingNodes) diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index 73124eb86a..b16529924e 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -3,9 +3,9 @@ package weed_server import ( "bytes" "context" - "crypto/fips140" "errors" "fmt" + "hash" "io" "math" "net/http" @@ -67,7 +67,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 && !fips140.Enforced() { + if len(md5bytes) > 0 && !util.DigestIsSha256() { md5InBase64 := util.Base64Encode(md5bytes) w.Header().Set("Content-MD5", md5InBase64) } @@ -107,7 +107,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()) - if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { + if contentMd5Mismatch(util.BodyMd5Of(md5bytes, buf.Bytes()), r.Header.Get("Content-Md5")) { bufPool.Put(buf) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -122,7 +122,7 @@ func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWrite } md5bytes = md5Hash.Sum(nil) - if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { + if contentMd5Mismatch(uploadBodyMd5(md5bytes, md5Hash), r.Header.Get("Content-Md5")) { fs.filer.DeleteUncommittedChunks(ctx, fileChunks) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -154,7 +154,7 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter } md5bytes = md5Hash.Sum(nil) - if contentMd5Mismatch(md5bytes, r.Header.Get("Content-Md5")) { + if contentMd5Mismatch(uploadBodyMd5(md5bytes, md5Hash), r.Header.Get("Content-Md5")) { fs.filer.DeleteUncommittedChunks(ctx, fileChunks) return nil, nil, errors.New(constants.ErrMsgBadDigest) } @@ -706,12 +706,57 @@ 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() { +// contentMd5Mismatch compares the body's MD5, from util.BodyMd5, with the +// client's Content-MD5, base64 or hex. bodyMd5 is nil only under fips140=only +// with digest sha256, where no MD5 can be computed, and Content-MD5 then goes +// unchecked. +func contentMd5Mismatch(bodyMd5 []byte, headerMd5 string) bool { + if headerMd5 == "" || bodyMd5 == nil { return false } - return util.Base64Encode(md5bytes) != headerMd5 && fmt.Sprintf("%x", md5bytes) != headerMd5 + return util.Base64Encode(bodyMd5) != headerMd5 && fmt.Sprintf("%x", bodyMd5) != headerMd5 +} + +// uploadHash is the content digest of an upload, which also feeds a separate +// MD5 of the body for the client's Content-MD5. +type uploadHash struct { + hash.Hash + contentMd5 hash.Hash +} + +// newUploadHash returns the content digest hash for an upload of r's body. It +// is an uploadHash when r carries Content-MD5 and the content digest is not +// itself an MD5 (see util.NewContentMd5), else the plain digest; r may be nil. +// The MD5 rides on the digest hash rather than on the body reader, so the +// body's path through the upload stays as it is in every digest mode. +func newUploadHash(r *http.Request) hash.Hash { + digest := util.NewMd5() + if r == nil || r.Header.Get("Content-Md5") == "" { + return digest + } + contentMd5 := util.NewContentMd5() + if contentMd5 == nil { + return digest + } + return &uploadHash{Hash: digest, contentMd5: contentMd5} +} + +func (h *uploadHash) Write(p []byte) (int, error) { + h.contentMd5.Write(p) + return h.Hash.Write(p) +} + +func (h *uploadHash) Reset() { + h.Hash.Reset() + h.contentMd5.Reset() +} + +// uploadBodyMd5 returns the body's MD5 for a Content-MD5 check, as +// util.BodyMd5 does, given the content digest and the hash from newUploadHash. +func uploadBodyMd5(contentDigest []byte, md5Hash hash.Hash) []byte { + var contentMd5 hash.Hash + if h, ok := md5Hash.(*uploadHash); ok { + contentMd5 = h.contentMd5 + } + return util.BodyMd5(contentDigest, contentMd5) } diff --git a/weed/server/filer_server_handlers_write_autochunk_digest_test.go b/weed/server/filer_server_handlers_write_autochunk_digest_test.go new file mode 100644 index 0000000000..573d8cbd94 --- /dev/null +++ b/weed/server/filer_server_handlers_write_autochunk_digest_test.go @@ -0,0 +1,49 @@ +package weed_server + +import ( + "crypto/fips140" + "crypto/md5" + "io" + "net/http/httptest" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// TestContentMd5CheckedInBothDigests checks that the filer verifies a +// client's Content-MD5 against the body's real MD5 under digest md5 and +// digest sha256, with the body's MD5 from the hash newUploadHash returns. +func TestContentMd5CheckedInBothDigests(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses MD5") + } + t.Cleanup(func() { util.SetDigest("") }) + right := md5.Sum([]byte("hello")) + wrong := md5.Sum([]byte("other")) + for _, digest := range []string{util.DigestMd5, util.DigestSha256} { + if err := util.SetDigest(digest); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + header string + mismatch bool + }{ + {util.Base64Encode(right[:]), false}, + {util.Base64Encode(wrong[:]), true}, + } { + r := httptest.NewRequest("PUT", "/x/hello", nil) + r.Header.Set("Content-Md5", c.header) + md5Hash := newUploadHash(r) + if _, err := io.Copy(md5Hash, strings.NewReader("hello")); err != nil { + t.Fatal(err) + } + if got := contentMd5Mismatch(uploadBodyMd5(md5Hash.Sum(nil), md5Hash), c.header); got != c.mismatch { + t.Errorf("digest %s, Content-MD5 %s: mismatch %v, want %v", digest, c.header, got, c.mismatch) + } + } + if _, ok := newUploadHash(nil).(*uploadHash); ok { + t.Errorf("digest %s: newUploadHash(nil) hashes a separate MD5", digest) + } + } +} diff --git a/weed/server/filer_server_handlers_write_upload.go b/weed/server/filer_server_handlers_write_upload.go index bc103f6742..6330e74330 100644 --- a/weed/server/filer_server_handlers_write_upload.go +++ b/weed/server/filer_server_handlers_write_upload.go @@ -68,7 +68,7 @@ func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.Respons } if int64(len(prefix)) < remainingInlineBudget { inlineAppend := append([]byte{}, prefix...) - md5Hash = util.NewMd5() + md5Hash = newUploadHash(r) _, _ = md5Hash.Write(inlineAppend) if len(inlineAppend) > 0 { stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc() @@ -87,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, util.NewMd5(), 0, nil, []byte{} + return nil, newUploadHash(r), 0, nil, []byte{} } if chunkSize <= 0 { return nil, nil, 0, fmt.Errorf("invalid chunk size %d for inline append promotion", chunkSize), nil @@ -102,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 = util.NewMd5() + md5Hash = newUploadHash(r) chunkOffset = startOffset var partReader = io.NopCloser(io.TeeReader(reader, md5Hash)) diff --git a/weed/util/bytes.go b/weed/util/bytes.go index 6a6309157f..4249d3dc45 100644 --- a/weed/util/bytes.go +++ b/weed/util/bytes.go @@ -2,9 +2,11 @@ package util import ( "bytes" + "crypto/md5" "crypto/rand" "encoding/base64" "fmt" + "hash" "io" "math" "strconv" @@ -112,8 +114,15 @@ func HashStringToLong(dir string) (v int64) { return } +// HashToInt32 follows GODEBUG only, not the digest mode: processes that never +// adopt a filer's digest derive the same names, such as a mount's socket path. func HashToInt32(data []byte) (v int32) { - h := NewMd5() + var h hash.Hash + if fips140Enforced() { + h = NewTruncatedSha256(md5.Size) + } else { + h = md5.New() + } h.Write(data) b := h.Sum(nil) @@ -134,9 +143,7 @@ func Base64Encode(data []byte) string { } func Md5(data []byte) []byte { - hash := NewMd5() - hash.Write(data) - return hash.Sum(nil) + return Md5For("", data) } func Md5String(data []byte) string { diff --git a/weed/util/fips140_hash.go b/weed/util/fips140_hash.go index 3fed109bc1..26d8545488 100644 --- a/weed/util/fips140_hash.go +++ b/weed/util/fips140_hash.go @@ -5,23 +5,177 @@ import ( "crypto/md5" "crypto/sha1" "crypto/sha256" + "fmt" "hash" + "sync/atomic" + + "github.com/seaweedfs/seaweedfs/weed/glog" +) + +// Digest modes. The mode decides what NewMd5 and NewSha1 hash with, and so +// the kind of every ETag, chunk digest and hashed store key a process writes. +const ( + DigestMd5 = "md5" + DigestSha256 = "sha256" ) 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. +const ( + digestFollowGodebug int32 = iota + digestMd5 + digestSha256 +) + +var digestSetting atomic.Int32 + +// SetDigest sets this process's digest mode. An empty name follows GODEBUG: +// sha256 under fips140=only, md5 otherwise. fips140=only refuses md5, since +// MD5 panics there. Call it before serving: digests already written keep the +// mode they were written in. +func SetDigest(name string) error { + if err := CheckDigest(name); err != nil { + return err + } + switch name { + case "": + digestSetting.Store(digestFollowGodebug) + case DigestMd5: + digestSetting.Store(digestMd5) + case DigestSha256: + digestSetting.Store(digestSha256) + } + return nil +} + +// DigestIsSha256 reports whether NewMd5 and NewSha1 return truncated SHA-256. +func DigestIsSha256() bool { + switch digestSetting.Load() { + case digestMd5: + return false + case digestSha256: + return true + } + return fips140Enforced() +} + +// Digest names the digest mode in effect. +func Digest() string { + if DigestIsSha256() { + return DigestSha256 + } + return DigestMd5 +} + +// AdoptFilerDigest sets this process's digest mode to the one filer reports, +// so every process writing into a cluster writes one kind of digest. A filer +// that reports none predates the setting; the process then keeps its own mode. +func AdoptFilerDigest(filer, digest string) error { + if digest == "" { + glog.Warningf("filer %s does not report its digest; writing %s digests as this process's GODEBUG implies", filer, Digest()) + return nil + } + if err := SetDigest(digest); err != nil { + return fmt.Errorf("filer %s uses digest %s: %w", filer, digest, err) + } + return nil +} + +// CheckDigest reports whether this process can hash with the named digest, +// "" meaning its own mode: fips140=only refuses md5, since MD5 panics there. +func CheckDigest(name string) error { + switch name { + case "", DigestSha256: + return nil + case DigestMd5: + if fips140Enforced() { + return fmt.Errorf("digest %s needs MD5, which GODEBUG=fips140=only refuses", DigestMd5) + } + return nil + } + return fmt.Errorf("unknown digest %q, want %s or %s", name, DigestMd5, DigestSha256) +} + +// DigestIsSha256For is DigestIsSha256 for the named digest, "" meaning this +// process's mode. It serves writers that write into a filer other than the +// one whose digest this process adopted. +func DigestIsSha256For(name string) bool { + switch name { + case DigestMd5: + return false + case DigestSha256: + return true + } + return DigestIsSha256() +} + +// NewMd5 returns an MD5 hash, or SHA-256 cut to MD5's size when the digest +// mode is sha256: digests keep their length but differ. func NewMd5() hash.Hash { - if fips140Enforced() { + return NewMd5For("") +} + +// NewMd5For is NewMd5 for the named digest, "" meaning this process's mode. +// Check the name with CheckDigest first: md5 panics under fips140=only. +func NewMd5For(name string) hash.Hash { + if DigestIsSha256For(name) { return NewTruncatedSha256(md5.Size) } return md5.New() } +// Md5For is Md5 for the named digest, "" meaning this process's mode. Check +// the name with CheckDigest first: md5 panics under fips140=only. +func Md5For(name string, data []byte) []byte { + if DigestIsSha256For(name) { + sum := sha256.Sum256(data) + return sum[:md5.Size] + } + sum := md5.Sum(data) + return sum[:] +} + +// BodyMd5Of is BodyMd5 for a body held in memory: the content digest when it +// is the MD5, else the body's MD5 when MD5 is available, else nil. +func BodyMd5Of(contentDigest, data []byte) []byte { + if !DigestIsSha256() { + return contentDigest + } + if fips140Enforced() { + return nil + } + sum := md5.Sum(data) + return sum[:] +} + +// NewContentMd5 returns an MD5 hash for checking a client's Content-MD5 next +// to the content digest, when that digest is not itself an MD5. It returns +// nil when the content digest is the MD5 (digest md5) or MD5 is refused +// (fips140=only); BodyMd5 then gives the MD5 to check against, or none. +func NewContentMd5() hash.Hash { + if !DigestIsSha256() || fips140Enforced() { + return nil + } + return md5.New() +} + +// BodyMd5 returns the body's MD5 for a Content-MD5 check: the hash from +// NewContentMd5 when there is one, else the content digest when that is an +// MD5. It returns nil when neither is an MD5 (fips140=only), and Content-MD5 +// then goes unchecked. +func BodyMd5(contentDigest []byte, contentMd5Hash hash.Hash) []byte { + if contentMd5Hash != nil { + return contentMd5Hash.Sum(nil) + } + if !DigestIsSha256() { + return contentDigest + } + return nil +} + // NewSha1 is NewMd5 for SHA-1. func NewSha1() hash.Hash { - if fips140Enforced() { + if DigestIsSha256() { return NewTruncatedSha256(sha1.Size) } return sha1.New() diff --git a/weed/util/fips140_hash_test.go b/weed/util/fips140_hash_test.go index 7375ce1a4b..f30079b5f8 100644 --- a/weed/util/fips140_hash_test.go +++ b/weed/util/fips140_hash_test.go @@ -6,6 +6,7 @@ import ( "crypto/md5" "crypto/sha1" "crypto/sha256" + "fmt" "testing" ) @@ -57,3 +58,140 @@ func TestNewMd5UsesTruncatedSha256WhenEnforced(t *testing.T) { t.Fatalf("hashes should be non-zero") } } + +// setDigestForTest sets the digest mode and restores the previous setting after the test. +func setDigestForTest(t *testing.T, name string) error { + t.Helper() + previous := digestSetting.Load() + t.Cleanup(func() { digestSetting.Store(previous) }) + return SetDigest(name) +} + +func TestDigestDefaultFollowsFips140Enforced(t *testing.T) { + if err := setDigestForTest(t, ""); err != nil { + t.Fatal(err) + } + setFIPS140Enforced(t, false) + if got := Digest(); got != DigestMd5 { + t.Fatalf("Digest() = %s without fips140=only, want %s", got, DigestMd5) + } + setFIPS140Enforced(t, true) + if got := Digest(); got != DigestSha256 { + t.Fatalf("Digest() = %s under fips140=only, want %s", got, DigestSha256) + } +} + +func TestSetDigestRefusesMd5WhenEnforced(t *testing.T) { + setFIPS140Enforced(t, true) + if err := setDigestForTest(t, DigestMd5); err == nil { + t.Fatal("SetDigest(md5) under fips140=only succeeded") + } + if got := Digest(); got != DigestSha256 { + t.Fatalf("Digest() = %s after a refused md5, want %s", got, DigestSha256) + } + if err := SetDigest("sha1"); err == nil { + t.Fatal("SetDigest(sha1) succeeded") + } +} + +func TestSetDigestSha256WithoutEnforced(t *testing.T) { + setFIPS140Enforced(t, false) + if err := setDigestForTest(t, DigestSha256); err != nil { + t.Fatal(err) + } + data := []byte("hello") + full := sha256.Sum256(data) + if got := Md5(data); !bytes.Equal(got, full[:md5.Size]) { + t.Fatalf("Md5 = %x, want %x", got, full[:md5.Size]) + } + if !DigestIsSha256() { + t.Fatal("DigestIsSha256() = false after SetDigest(sha256)") + } +} + +func TestAdoptFilerDigest(t *testing.T) { + setFIPS140Enforced(t, false) + if err := setDigestForTest(t, ""); err != nil { + t.Fatal(err) + } + if err := AdoptFilerDigest("f:8888", ""); err != nil || Digest() != DigestMd5 { + t.Fatalf("empty report: err %v, digest %s; want own mode %s", err, Digest(), DigestMd5) + } + if err := AdoptFilerDigest("f:8888", DigestSha256); err != nil || Digest() != DigestSha256 { + t.Fatalf("sha256 report: err %v, digest %s", err, Digest()) + } + if err := AdoptFilerDigest("f:8888", "crc32"); err == nil { + t.Fatal("unknown digest adopted") + } + + setFIPS140Enforced(t, true) + if err := AdoptFilerDigest("f:8888", DigestMd5); err == nil { + t.Fatal("md5 filer adopted under fips140=only") + } + if err := AdoptFilerDigest("f:8888", DigestSha256); err != nil || Digest() != DigestSha256 { + t.Fatalf("sha256 report under fips140=only: err %v, digest %s", err, Digest()) + } +} + +// TestNewContentMd5 checks when a separate MD5 for Content-MD5 is computed: +// only under digest sha256 with MD5 available, and BodyMd5 then returns it. +func TestNewContentMd5(t *testing.T) { + if fips140.Enforced() { + t.Skip("computes a real MD5, which GODEBUG=fips140=only refuses") + } + enforced := fips140Enforced + t.Cleanup(func() { fips140Enforced = enforced; SetDigest("") }) + fips140Enforced = func() bool { return false } + + SetDigest(DigestMd5) + if NewContentMd5() != nil { + t.Error("digest md5: the content digest is the MD5, no separate hash wanted") + } + if got := BodyMd5([]byte("digest"), nil); string(got) != "digest" { + t.Errorf("digest md5: BodyMd5 = %q, want the content digest", got) + } + if got := BodyMd5Of([]byte("digest"), []byte("hello")); string(got) != "digest" { + t.Errorf("digest md5: BodyMd5Of = %q, want the content digest", got) + } + + SetDigest(DigestSha256) + h := NewContentMd5() + if h == nil { + t.Fatal("digest sha256 without fips140=only: want a separate MD5") + } + h.Write([]byte("hello")) + if got := BodyMd5([]byte("sha256 digest"), h); fmt.Sprintf("%x", got) != "5d41402abc4b2a76b9719d911017c592" { + t.Errorf("digest sha256: BodyMd5 = %x, want the MD5 of hello", got) + } + + if got := BodyMd5Of([]byte("sha256 digest"), []byte("hello")); fmt.Sprintf("%x", got) != "5d41402abc4b2a76b9719d911017c592" { + t.Errorf("digest sha256: BodyMd5Of = %x, want the MD5 of hello", got) + } + + fips140Enforced = func() bool { return true } + if NewContentMd5() != nil { + t.Error("fips140=only: no MD5 can be computed") + } + if BodyMd5Of([]byte("sha256 digest"), []byte("hello")) != nil { + t.Error("fips140=only: BodyMd5Of must be nil so Content-MD5 goes unchecked") + } + if BodyMd5([]byte("sha256 digest"), nil) != nil { + t.Error("fips140=only: BodyMd5 must be nil so Content-MD5 goes unchecked") + } +} + +func TestHashToInt32IgnoresDigestMode(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses MD5") + } + setFIPS140Enforced(t, false) + t.Cleanup(func() { SetDigest("") }) + data := []byte("/mnt/weed") + want := HashToInt32(data) + if err := SetDigest(DigestSha256); err != nil { + t.Fatal(err) + } + if got := HashToInt32(data); got != want { + t.Fatalf("HashToInt32 = %d under digest sha256, want %d as under md5", got, want) + } +} diff --git a/weed/worker/tasks/iceberg/exec_test.go b/weed/worker/tasks/iceberg/exec_test.go index cacbe1ef49..2c50e5198a 100644 --- a/weed/worker/tasks/iceberg/exec_test.go +++ b/weed/worker/tasks/iceberg/exec_test.go @@ -217,6 +217,12 @@ func (f *fakeFilerServer) AssignVolume(_ context.Context, _ *filer_pb.AssignVolu }, nil } +// GetFilerConfiguration reports no digest, as a filer that predates the +// setting does, so uploads use the test process's digest mode. +func (f *fakeFilerServer) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + return &filer_pb.GetFilerConfigurationResponse{}, nil +} + func (f *fakeFilerServer) Ping(_ context.Context, _ *filer_pb.PingRequest) (*filer_pb.PingResponse, error) { now := time.Now().UnixNano() return &filer_pb.PingResponse{ diff --git a/weed/worker/tasks/iceberg/filer_io.go b/weed/worker/tasks/iceberg/filer_io.go index 2531e1ecb5..761db70d53 100644 --- a/weed/worker/tasks/iceberg/filer_io.go +++ b/weed/worker/tasks/iceberg/filer_io.go @@ -560,10 +560,19 @@ func uploadFilerChunks(ctx context.Context, client filer_pb.SeaweedFilerClient, }, nil } + digest, err := filer_pb.ReadFilerDigest(ctx, client) + if err != nil { + return nil, fmt.Errorf("read filer digest: %w", err) + } + if err := util.CheckDigest(digest); err != nil { + return nil, fmt.Errorf("filer digest: %w", err) + } + initGlobalHTTPClientOnce.Do(util_http.InitGlobalHttpClient) result, err := operation.UploadReaderInChunks(ctx, util.NewBytesReader(content), &operation.ChunkedUploadOption{ ChunkSize: filerFileChunkSize, AssignFunc: assignFn, + Digest: digest, }) if err != nil { // Chunks uploaded before the failure are orphaned: nothing references