Files
seaweedfs/weed/s3api/fips140_only_test.go
T
1815f140b6 fips140=only: refuse JWT signing keys and S3 secrets too short for HMAC (#12912)
* fips140=only: refuse HMAC keys too short for FIPS mode where they are configured

Under GODEBUG=fips140=only, hmac.New panics on keys shorter than 112 bits
(14 bytes). A short JWT signing key starts fine and then kills weed server
on the first write (the master's Assign mints a volume JWT in an
unrecovered gRPC handler), and an S3 secret of 8 or 9 characters (the
SigV4 signing key is HMAC keyed with "AWS4"+secret) makes every request
from that identity panic in its handler.

Only under crypto/fips140.Enforced():

- security.toml: LoadSecurityConfiguration exits with an error naming the
  setting when a jwt.signing / jwt.filer_signing key, read key or
  previous key is under 14 bytes. LoadFilerJwtFromFile (filer.sync
  -a.security/-b.security) returns the same error, and
  Guard.UpdateSigningKeys keeps the keys in effect on a reload that
  brings in a short key.
- S3: SigV4 (header, presigned, streaming seed and POST policy) answers
  InvalidAccessKeyId, as for an inactive key, when the credential's
  secret is under 10 characters, and logs the access key. Loading such a
  credential logs a warning; it stays loaded and stored.
- IAM CreateAccessKey (IAM API, embedded IAM, admin UI) requires a
  caller-supplied SecretAccessKey of at least 10 characters.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: check jwt.filer_signing.subscribe.key and the imgproxy key too

The filer verifies metadata subscription tokens with
jwt.filer_signing.subscribe.key and `weed shell fs.meta.token` signs them
with it, so under GODEBUG=fips140=only a short value panics on first use;
LoadSecurityConfiguration now refuses it with the other JWT keys. `weed
image` signs imgproxy URLs with HMAC keyed with IMGPROXY_KEY;
gateway.New refuses a key under 14 bytes in that mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: warn about JWT keys too short for fips140=only outside that mode

Outside GODEBUG=fips140=only a JWT signing key under 14 bytes works, so
LoadSecurityConfiguration (every weed command but fuse) and
LoadFilerJwtFromFile now log a warning naming the setting instead of saying
nothing: such a key is refused under fips140=only, and a future release may
refuse it in every mode, so the warning asks for a rotation to a longer key
with previous_key while it still works. A short previous_key holds the old
key during that rotation, so its warning only asks to clear it afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse a short secret under fips140=only with AccessDenied, not InvalidAccessKeyId

InvalidAccessKeyId says the access key does not exist, so a client refused
for a secret too short for fips140=only went looking for a missing key. The
new ErrFips140SecretTooShort answers AccessDenied (403) with "This access
key cannot be used while the server runs in FIPS 140 mode. Ask the
administrator for a new secret." The message leaves out the length rule:
the refusal comes before the request's signature is checked, so any caller
that knows the access key ID would learn the secret is short. The embedded
IAM API maps it to AccessDenied as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: log an S3 secret too short for fips140=only at error level

Under GODEBUG=fips140=only every request signed with such a key is refused,
so the identity is unusable; the load-time message is an error, not a
warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util, security: name every JWT key too short for fips140=only in one error

CheckFips140SigningKeys stopped at the first short key, so a cluster with
two short keys failed at startup, was fixed, and failed again on the next
one. CheckFips140HmacKeys checks every setting and names each short key
("jwt.signing.key is 10 bytes, jwt.filer_signing.key is 8 bytes; ..."); with
one short key the message is unchanged. Guard reloads use it as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: say what happened, to what and what to do in the short-key messages

The messages about S3 secrets and JWT keys too short for FIPS 140 now start
from the process's mode, name the key, its owner or file, the limit, and the
fix:

- loading S3 identities: "this process runs with GODEBUG=fips140=only, and
  refuses all S3 requests signed with access key ... (identity ...) because
  its secret is shorter than the 10 characters FIPS 140 needs for SigV4
  secrets; give that access key a new secret of at least 10 characters";
- a refused request logs its request ID, which the client gets back, its
  client IP (as the audit log records it, s3err.RemoteIP) and the identity;
- the startup refusal names security.toml's path and every short key, and
  links the wiki section on replacing them with or without downtime;
- the startup warning outside fips140=only says the server would not start
  in that mode, and links the same section.

A short previous_key no longer gets a warning outside fips140=only: it holds
the old key while switching to a longer one, and under fips140=only the
startup refusal names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: a reload under fips140=only drops short previous keys, not the new keys

UpdateSigningKeys refused the whole key set when a previous key was too short,
so a volume server kept its old keys while the filer's volume signer, which
gets no previous keys, took the new ones; proxied chunk reads then failed with
401. Short current keys still keep the keys in effect. A short previous key is
dropped with an error log instead: nothing under fips140=only can sign with it,
so no token is lost, and every server ends up with the same current keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: check only the filer keys filer.sync uses in its security files

LoadFilerJwtFromFile checked every JWT setting in a -a.security/-b.security
file, so under fips140=only filer.sync refused to start over a short volume or
previous key it never uses. It now checks jwt.filer_signing.key and its read
key, after the fallback to the process-wide configuration, which startup
checks already.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer a short secret under fips140=only with SignatureDoesNotMatch

A distinct answer before the signature is checked told anyone who knows an
access key ID that its secret is short. The refusal now runs where the
signature would be checked, after the permission, expiry and signed-header
checks, and answers the SignatureDoesNotMatch a wrong signature gets. The
server log keeps the cause, the request ID and the client. This drops
ErrFips140SecretTooShort and its IAM mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security, filer: keep Basic Auth on a reload whose JWT keys are refused

When a reload under fips140=only refused the new filer JWT keys, the filer
still removed Basic Auth, so a configuration that switches from Basic Auth to
short JWT keys left the filer with neither. UpdateSigningKeys and
ReloadSigningKeys now report whether the new keys are in effect, and the
filer drops Basic Auth only when they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: do not install a volume read key too short for fips140=only

A reload installed jwt.signing.read.key into the read-signing cache without a
length check, so under fips140=only a short key made later chunk reads panic
signing with it. loadJwtConfig now leaves the key in effect when the new one
is too short.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: keep the volume read key when the volume guard would refuse the reload

Under GODEBUG=fips140=only a volume server's reload keeps its keys when
jwt.signing.key or jwt.signing.read.key is too short. The read-key cache
checked only the read key, so it could sign reads with a key the volume
servers had not taken. It now checks the same two keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: build the short-key list in one append in CheckFips140HmacKeys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep the blank line before the permission check in verifyV4Signature

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: skip TestFIPS140OnlyShortSecret under real fips140=only enforcement

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-25 13:07:15 -08:00

298 lines
12 KiB
Go

package s3api
import (
"bytes"
"crypto/fips140"
"crypto/md5"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strconv"
"testing"
"time"
"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.
func setFIPS140Enforced(t *testing.T, enforced bool) {
t.Helper()
saved := fips140Enforced
fips140Enforced = func() bool { return enforced }
t.Cleanup(func() { fips140Enforced = saved })
}
func signedV2Request(t *testing.T, cred *Credential) *http.Request {
t.Helper()
req, err := http.NewRequest(http.MethodGet, "http://example.com/bucket/object", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
req.Header.Set("Authorization", signatureV2(cred, req.Method, req.URL.EscapedPath(), req.URL.Query().Encode(), req.Header))
return req
}
func presignedV2Request(t *testing.T, cred *Credential) *http.Request {
t.Helper()
req, err := http.NewRequest(http.MethodGet, "http://example.com/bucket/object", nil)
if err != nil {
t.Fatal(err)
}
expires := strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)
query := req.URL.Query()
query.Set("AWSAccessKeyId", cred.AccessKey)
query.Set("Expires", expires)
query.Set("Signature", preSignatureV2(cred, req.Method, req.URL.EscapedPath(), query.Encode(), req.Header, expires))
req.URL.RawQuery = query.Encode()
return req
}
func policyV2Form(cred *Credential) http.Header {
policy := base64.StdEncoding.EncodeToString([]byte(`{"expiration":"2099-01-01T00:00:00Z","conditions":[]}`))
form := http.Header{}
form.Set("AWSAccessKeyId", cred.AccessKey)
form.Set("Policy", policy)
form.Set("Signature", calculateSignatureV2(policy, cred.SecretKey))
return form
}
func TestFIPS140OnlySigV2(t *testing.T) {
iam := setupTestIAMForV2Auth()
cred := &Credential{AccessKey: "AKIAIOSFODNN7EXAMPLE", SecretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"}
signed := signedV2Request(t, cred)
presigned := presignedV2Request(t, cred)
form := policyV2Form(cred)
for _, enforced := range []bool{false, true} {
t.Run("enforced="+strconv.FormatBool(enforced), func(t *testing.T) {
setFIPS140Enforced(t, enforced)
want := s3err.ErrNone
if enforced {
want = s3err.ErrSignatureVersionNotSupported
}
if _, code := iam.isReqAuthenticatedV2(signed); code != want {
t.Errorf("header SigV2: got %v, want %v", code, want)
}
if _, code := iam.isReqAuthenticatedV2(presigned); code != want {
t.Errorf("presigned SigV2: got %v, want %v", code, want)
}
if _, code := iam.doesPolicySignatureV2Match(t.Context(), form); code != want {
t.Errorf("POST policy SigV2: got %v, want %v", code, want)
}
})
}
}
func TestFIPS140OnlySSEC(t *testing.T) {
key := bytes.Repeat([]byte{0x42}, SSECustomerKeySize)
keyMD5 := md5.Sum(key)
keyB64 := base64.StdEncoding.EncodeToString(key)
keyMD5B64 := base64.StdEncoding.EncodeToString(keyMD5[:])
ssecHeaders := http.Header{}
ssecHeaders.Set(s3_constants.AmzServerSideEncryptionCustomerAlgorithm, "AES256")
ssecHeaders.Set(s3_constants.AmzServerSideEncryptionCustomerKey, keyB64)
ssecHeaders.Set(s3_constants.AmzServerSideEncryptionCustomerKeyMD5, keyMD5B64)
copySourceHeaders := http.Header{}
copySourceHeaders.Set(s3_constants.AmzCopySourceServerSideEncryptionCustomerAlgorithm, "AES256")
copySourceHeaders.Set(s3_constants.AmzCopySourceServerSideEncryptionCustomerKey, keyB64)
copySourceHeaders.Set(s3_constants.AmzCopySourceServerSideEncryptionCustomerKeyMD5, keyMD5B64)
sses3Headers := http.Header{}
sses3Headers.Set(s3_constants.AmzServerSideEncryption, s3_constants.SSEAlgorithmAES256)
t.Run("enforced", func(t *testing.T) {
setFIPS140Enforced(t, true)
if _, err := ParseSSECHeaders(&http.Request{Header: ssecHeaders}); MapSSECErrorToS3Error(err) != s3err.ErrNotImplemented {
t.Errorf("ParseSSECHeaders: got %v, want NotImplemented", err)
}
if _, err := ParseSSECCopySourceHeaders(&http.Request{Header: copySourceHeaders}); MapSSECErrorToS3Error(err) != s3err.ErrNotImplemented {
t.Errorf("ParseSSECCopySourceHeaders: got %v, want NotImplemented", err)
}
if k, err := ParseSSECHeaders(&http.Request{Header: http.Header{}}); k != nil || err != nil {
t.Errorf("no SSE-C headers: got %v, %v, want nil, nil", k, err)
}
for name, h := range map[string]http.Header{"SSE-C": ssecHeaders, "copy source SSE-C": copySourceHeaders} {
if code := ValidateRequestEncryption(h); code != s3err.ErrNotImplemented {
t.Errorf("ValidateRequestEncryption(%s): got %v, want NotImplemented", name, code)
}
}
if code := ValidateRequestEncryption(sses3Headers); code != s3err.ErrNone {
t.Errorf("ValidateRequestEncryption(SSE-S3): got %v, want ErrNone", code)
}
})
t.Run("not enforced", func(t *testing.T) {
setFIPS140Enforced(t, false)
k, err := ParseSSECHeaders(&http.Request{Header: ssecHeaders})
if err != nil || k == nil || !bytes.Equal(k.Key, key) {
t.Errorf("ParseSSECHeaders: got %v, %v, want the parsed key", k, err)
}
for name, h := range map[string]http.Header{"SSE-C": ssecHeaders, "copy source SSE-C": copySourceHeaders, "SSE-S3": sses3Headers} {
if code := ValidateRequestEncryption(h); code != s3err.ErrNone {
t.Errorf("ValidateRequestEncryption(%s): got %v, want ErrNone", name, code)
}
}
})
}
func TestFIPS140OnlySHA1Checksum(t *testing.T) {
sha1Requests := map[string]func(r *http.Request){
"value header": func(r *http.Request) { r.Header.Set(s3_constants.AmzChecksumSHA1, "2jmj7l5rSw0yVb/vlWAYkK/YBwk=") },
"sdk algorithm header": func(r *http.Request) { r.Header.Set(s3_constants.AmzSdkChecksumAlgorithm, "SHA1") },
"algorithm header": func(r *http.Request) { r.Header.Set(s3_constants.AmzChecksumAlgorithm, "sha1") },
"trailer": func(r *http.Request) { r.Header.Set(s3_constants.AmzTrailer, "x-amz-checksum-sha1") },
"presigned query": func(r *http.Request) {
r.URL.RawQuery = url.Values{s3_constants.AmzSdkChecksumAlgorithm: {"SHA1"}}.Encode()
},
}
newRequest := func(setup func(r *http.Request)) *http.Request {
r, _ := http.NewRequest(http.MethodPut, "http://example.com/bucket/object", nil)
setup(r)
return r
}
t.Run("enforced", func(t *testing.T) {
setFIPS140Enforced(t, true)
for name, setup := range sha1Requests {
if alg, _, code := detectRequestedChecksumAlgorithm(newRequest(setup)); alg != ChecksumAlgorithmNone || code != s3err.ErrNotImplemented {
t.Errorf("%s: got %v, %v, want None, NotImplemented", name, alg, code)
}
}
sha256 := newRequest(func(r *http.Request) { r.Header.Set(s3_constants.AmzSdkChecksumAlgorithm, "SHA256") })
if alg, _, code := detectRequestedChecksumAlgorithm(sha256); alg != ChecksumAlgorithmSHA256 || code != s3err.ErrNone {
t.Errorf("SHA256: got %v, %v, want SHA256, ErrNone", alg, code)
}
})
t.Run("not enforced", func(t *testing.T) {
setFIPS140Enforced(t, false)
for name, setup := range sha1Requests {
if alg, header, code := detectRequestedChecksumAlgorithm(newRequest(setup)); alg != ChecksumAlgorithmSHA1 || header != s3_constants.AmzChecksumSHA1 || code != s3err.ErrNone {
t.Errorf("%s: got %v, %q, %v, want SHA1, %q, ErrNone", name, alg, header, code, s3_constants.AmzChecksumSHA1)
}
}
})
}
func TestFIPS140OnlySHA1ChunkedTrailer(t *testing.T) {
newRequest := func() *http.Request {
r, _ := http.NewRequest(http.MethodPut, "/test-bucket/test-object", bytes.NewReader(nil))
r.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
r.Header.Set("x-amz-trailer", "x-amz-checksum-sha1")
return r
}
iam := setupTestIAM()
for _, enforced := range []bool{false, true} {
t.Run("enforced="+strconv.FormatBool(enforced), func(t *testing.T) {
setFIPS140Enforced(t, enforced)
want := s3err.ErrNone
if enforced {
want = s3err.ErrNotImplemented
}
if _, code := iam.newChunkedReader(newRequest()); code != want {
t.Errorf("got %v, want %v", code, want)
}
})
}
}
// policyV4Form is a POST policy form signed with SigV4 by cred.
func policyV4Form(cred *Credential) http.Header {
now := time.Now().UTC()
policy := base64.StdEncoding.EncodeToString([]byte(`{"expiration":"2099-01-01T00:00:00Z","conditions":[]}`))
form := http.Header{}
form.Set("X-Amz-Credential", fmt.Sprintf("%s/%s/us-east-1/s3/aws4_request", cred.AccessKey, now.Format(yyyymmdd)))
form.Set("X-Amz-Date", now.Format(iso8601Format))
form.Set("Policy", policy)
form.Set("X-Amz-Signature", getSignature(getSigningKey(cred.SecretKey, now.Format(yyyymmdd), "us-east-1", "s3"), policy))
return form
}
func TestFIPS140OnlyShortSecret(t *testing.T) {
if fips140.Enforced() {
t.Skip("GODEBUG=fips140=only panics signing the fixtures with a 9-character secret")
}
short := &Credential{AccessKey: "AKIASHORTSECRET0001", SecretKey: "abcd12345"}
ten := &Credential{AccessKey: "AKIATENSECRET000001", SecretKey: "abcd123456"}
iam := &IdentityAccessManagement{accessKeyIdent: map[string]*Identity{}}
for _, cred := range []*Credential{short, ten} {
ident := &Identity{Name: cred.AccessKey, Credentials: []*Credential{cred}, Actions: []Action{s3_constants.ACTION_ADMIN}}
iam.identities = append(iam.identities, ident)
iam.accessKeyIdent[cred.AccessKey] = ident
}
signed := func(cred *Credential) *http.Request {
req := mustNewRequest(http.MethodGet, "http://example.com/bucket/object", 0, nil, t)
if err := signRequestV4(req, cred.AccessKey, cred.SecretKey); err != nil {
t.Fatal(err)
}
return req
}
presigned := func(cred *Credential) *http.Request {
req := mustNewRequest(http.MethodGet, "http://example.com/bucket/object", 0, nil, t)
if err := preSignV4(iam, req, cred.AccessKey, cred.SecretKey, 600); err != nil {
t.Fatal(err)
}
return req
}
for _, enforced := range []bool{false, true} {
t.Run("enforced="+strconv.FormatBool(enforced), func(t *testing.T) {
setFIPS140Enforced(t, enforced)
for _, cred := range []*Credential{short, ten} {
want := s3err.ErrNone
if enforced && cred == short {
want = s3err.ErrSignatureDoesNotMatch
}
if _, _, code := iam.doesSignatureMatch(signed(cred)); code != want {
t.Errorf("header SigV4 with a %d-character secret: got %v, want %v", len(cred.SecretKey), code, want)
}
if _, _, code := iam.doesSignatureMatch(presigned(cred)); code != want {
t.Errorf("presigned SigV4 with a %d-character secret: got %v, want %v", len(cred.SecretKey), code, want)
}
if _, code := iam.doesPolicySignatureV4Match(t.Context(), policyV4Form(cred)); code != want {
t.Errorf("POST policy SigV4 with a %d-character secret: got %v, want %v", len(cred.SecretKey), code, want)
}
}
})
}
}
// 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")
}
}