Files
seaweedfs/weed/s3api/s3err/audit_fluent.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

281 lines
9.6 KiB
Go

package s3err
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
"github.com/fluent/fluent-logger-golang/fluent"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
)
type AccessLogExtend struct {
AccessLog
AccessLogHTTP
}
type AccessLog struct {
Bucket string `msg:"bucket" json:"bucket"` // awsexamplebucket1
Time int64 `msg:"time" json:"time"` // [06/Feb/2019:00:00:38 +0000]
RemoteIP string `msg:"remote_ip" json:"remote_ip,omitempty"` // 192.0.2.3
Requester string `msg:"requester" json:"requester,omitempty"` // IAM user id
RequesterArn string `msg:"requester_arn" json:"requester_arn,omitempty"` // arn:aws:sts::0:assumed-role/Role/session
RequesterIdentity string `msg:"requester_identity" json:"requester_identity,omitempty"` // authoritative OIDC identity claim (preferred_username/email/sub)
AccessKeyId string `msg:"access_key_id" json:"access_key_id,omitempty"` // the key the request was signed with; an STS session's temporary key id
RequestID string `msg:"request_id" json:"request_id,omitempty"` // 3E57427F33A59F07
Operation string `msg:"operation" json:"operation,omitempty"` // REST.HTTP_method.resource_type REST.PUT.OBJECT
Key string `msg:"key" json:"key,omitempty"` // /photos/2019/08/puppy.jpg
ErrorCode string `msg:"error_code" json:"error_code,omitempty"`
HostId string `msg:"host_id" json:"host_id,omitempty"`
HostHeader string `msg:"host_header" json:"host_header,omitempty"` // s3.us-west-2.amazonaws.com
UserAgent string `msg:"user_agent" json:"user_agent,omitempty"`
HTTPStatus int `msg:"status" json:"status,omitempty"`
SignatureVersion string `msg:"signature_version" json:"signature_version,omitempty"`
}
type AccessLogHTTP struct {
RequestURI string `json:"request_uri,omitempty"` // "GET /awsexamplebucket1/photos/2019/08/puppy.jpg?x-foo=bar HTTP/1.1"
BytesSent string `json:"bytes_sent,omitempty"`
ObjectSize string `json:"object_size,omitempty"`
TotalTime int `json:"total_time,omitempty"`
TurnAroundTime int `json:"turn_around_time,omitempty"`
Referer string `json:"Referer,omitempty"`
VersionId string `json:"version_id,omitempty"`
CipherSuite string `json:"cipher_suite,omitempty"`
AuthenticationType string `json:"auth_type,omitempty"`
TLSVersion string `json:"TLS_version,omitempty"`
}
const tag = "s3.access"
var (
Logger *fluent.Fluent
hostname = os.Getenv("HOSTNAME")
environment = os.Getenv("ENVIRONMENT")
)
func InitAuditLog(config string) {
configContent, readErr := os.ReadFile(config)
if readErr != nil {
glog.Errorf("fail to read fluent config %s : %v", config, readErr)
return
}
fluentConfig := &fluent.Config{}
if err := json.Unmarshal(configContent, fluentConfig); err != nil {
glog.Errorf("fail to parse fluent config %s : %v", string(configContent), err)
return
}
if len(fluentConfig.TagPrefix) == 0 && len(environment) > 0 {
fluentConfig.TagPrefix = environment
}
fluentConfig.Async = true
fluentConfig.AsyncResultCallback = func(data []byte, err error) {
if err != nil {
glog.Warning("Error while posting log: ", err)
}
}
var err error
Logger, err = fluent.New(*fluentConfig)
if err != nil {
glog.Errorf("fail to load fluent config: %v", err)
}
}
// getRemoteIP returns the client IP for the audit log, honoring forwarding
// headers set by reverse proxies. Preference order: X-Forwarded-For (first
// non-empty entry), X-Real-IP, then r.RemoteAddr. Headers are trusted as-is;
// operators who expose the S3 endpoint directly to untrusted networks should
// strip these headers at the proxy boundary so clients cannot spoof them.
func getRemoteIP(r *http.Request) string {
if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" {
for _, entry := range strings.Split(forwardedFor, ",") {
if ip := strings.TrimSpace(entry); ip != "" {
return ip
}
}
}
if realIP := strings.TrimSpace(r.Header.Get("X-Real-IP")); realIP != "" {
return realIP
}
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}
// RemoteIP is the client IP the audit log records for r.
func RemoteIP(r *http.Request) string {
return getRemoteIP(r)
}
func getREST(httpMetod string, resourceType string) string {
return fmt.Sprintf("REST.%s.%s", httpMetod, resourceType)
}
func getResourceType(object string, query_key string, method string) (string, bool) {
// Bucket-level routes have no object; NormalizeObjectKey makes that "", not "/".
if object == "" || object == "/" {
switch query_key {
case "delete":
if method == http.MethodPost {
return "BATCH.DELETE.OBJECT", true
}
return getREST(method, "BUCKET"), false
case "tagging":
return getREST(method, "OBJECTTAGGING"), true
case "lifecycle":
return getREST(method, "LIFECYCLECONFIGURATION"), true
case "acl":
return getREST(method, "ACCESSCONTROLPOLICY"), true
case "policy":
return getREST(method, "BUCKETPOLICY"), true
default:
return getREST(method, "BUCKET"), false
}
} else {
switch query_key {
case "tagging":
return getREST(method, "OBJECTTAGGING"), true
default:
return getREST(method, "OBJECT"), false
}
}
}
type accessLogOperationKey struct{}
func WithAccessLogOperation(r *http.Request, operation string) *http.Request {
return r.WithContext(context.WithValue(r.Context(), accessLogOperationKey{}, operation))
}
func getOperation(object string, r *http.Request) string {
if operation, ok := r.Context().Value(accessLogOperationKey{}).(string); ok {
return operation
}
queries := r.URL.Query()
var operation string
var queryFound bool
for key, _ := range queries {
operation, queryFound = getResourceType(object, key, r.Method)
if queryFound {
return operation
}
}
if len(queries) == 0 {
operation, _ = getResourceType(object, "", r.Method)
}
return operation
}
func GetAccessLog(r *http.Request, HTTPStatusCode int, s3errCode ErrorCode) *AccessLog {
bucket, key := s3_constants.GetBucketAndObject(r)
var errorCode string
if s3errCode != ErrNone {
errorCode = GetAPIError(s3errCode).Code
}
remoteIP := getRemoteIP(r)
hostHeader := r.Header.Get("X-Forwarded-Host")
if len(hostHeader) == 0 {
hostHeader = r.Host
}
return &AccessLog{
HostHeader: hostHeader,
RequestID: request_id.GetFromRequest(r),
RemoteIP: remoteIP,
Requester: s3_constants.GetIdentityNameFromContext(r), // Get from context, not header (secure)
RequesterArn: s3_constants.GetPrincipalArnFromContext(r),
RequesterIdentity: s3_constants.GetIdentityClaimFromContext(r),
AccessKeyId: s3_constants.GetAccessKeyIdFromContext(r),
SignatureVersion: r.Header.Get(s3_constants.AmzAuthType),
UserAgent: r.Header.Get("user-agent"),
HostId: hostname,
Bucket: bucket,
HTTPStatus: HTTPStatusCode,
Time: time.Now().Unix(),
Key: key,
Operation: getOperation(key, r),
ErrorCode: errorCode,
}
}
func PostLog(r *http.Request, HTTPStatusCode int, errorCode ErrorCode) {
if r == nil {
return
}
// Mark before the Logger nil-check so the middleware fallback in track()
// still sees that audit was handled by the caller in deployments that
// haven't configured fluent — keeps the flag behavior consistent and
// makes wiring testable without standing up a fluent server.
markAuditLogged(r)
if Logger == nil {
return
}
if err := Logger.Post(tag, *GetAccessLog(r, HTTPStatusCode, errorCode)); err != nil {
glog.Warning("Error while posting log: ", err)
}
}
func PostAccessLog(log AccessLog) {
if Logger == nil {
return
}
if err := Logger.Post(tag, log); err != nil {
glog.Warning("Error while posting log: ", err)
}
}
// auditLogCtxKey identifies the per-request flag used to detect whether an
// audit entry has already been emitted, so middleware can supply a fallback
// log for handlers that don't call PostLog themselves without double-logging
// the ones that do.
type auditLogCtxKey struct{}
// EnsureAuditTracking attaches an audit-tracking flag to the request context
// if one is not already present. Safe to call when no fluent logger is
// configured; the flag is harmless in that case.
func EnsureAuditTracking(r *http.Request) *http.Request {
if r == nil {
return nil
}
if v, ok := r.Context().Value(auditLogCtxKey{}).(*atomic.Bool); ok && v != nil {
return r
}
flag := new(atomic.Bool)
return r.WithContext(context.WithValue(r.Context(), auditLogCtxKey{}, flag))
}
// MarkAuditLogged signals that an audit entry has already been emitted for r.
// Callers that emit logs via paths other than PostLog (e.g. PostAccessLog in
// batch delete) should invoke this so the middleware fallback skips r.
func MarkAuditLogged(r *http.Request) {
markAuditLogged(r)
}
func markAuditLogged(r *http.Request) {
if r == nil {
return
}
if v, ok := r.Context().Value(auditLogCtxKey{}).(*atomic.Bool); ok && v != nil {
v.Store(true)
}
}
// AuditAlreadyLogged reports whether PostLog (or MarkAuditLogged) has run for r.
func AuditAlreadyLogged(r *http.Request) bool {
if r == nil {
return false
}
if v, ok := r.Context().Value(auditLogCtxKey{}).(*atomic.Bool); ok && v != nil {
return v.Load()
}
return false
}