mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
* 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>
265 lines
9.3 KiB
Go
265 lines
9.3 KiB
Go
package security
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
var (
|
|
ErrUnauthorized = errors.New("unauthorized token")
|
|
)
|
|
|
|
/*
|
|
Guard is to ensure data access security.
|
|
There are 2 ways to check access:
|
|
1. white list. It's checking request ip address.
|
|
2. JSON Web Token(JWT) generated from secretKey.
|
|
The jwt can come from:
|
|
1. url parameter jwt=...
|
|
2. request header "Authorization"
|
|
3. cookie with the name "jwt"
|
|
|
|
The white list is checked first because it is easy.
|
|
Then the JWT is checked.
|
|
|
|
The Guard will also check these claims if provided:
|
|
1. "exp" Expiration Time
|
|
2. "nbf" Not Before
|
|
|
|
Generating JWT:
|
|
1. use HS256 to sign
|
|
2. optionally set "exp", "nbf" fields, in Unix time,
|
|
the number of seconds elapsed since January 1, 1970 UTC.
|
|
|
|
Referenced:
|
|
https://github.com/pkieltyka/jwtauth/blob/master/jwtauth.go
|
|
*/
|
|
// guardState is the immutable snapshot of all hot-reloadable Guard state. The
|
|
// Update* methods build a new snapshot from the current one and swap it in
|
|
// atomically, so request-path readers (WhiteList, IsWhiteListed, the SigningKey
|
|
// accessors) always observe a consistent set of keys and whitelist — never a
|
|
// torn slice header or a mix of old and new state across a SIGHUP.
|
|
type guardState struct {
|
|
signingKey SigningKey
|
|
expiresAfterSec int
|
|
readSigningKey SigningKey
|
|
readExpiresAfterSec int
|
|
// previous keys are accepted when verifying, never used to sign
|
|
previousSigningKey SigningKey
|
|
previousReadSigningKey SigningKey
|
|
|
|
whiteListIp map[string]struct{}
|
|
whiteListCIDR map[string]*net.IPNet
|
|
isWriteActive bool
|
|
isEmptyWhiteList bool
|
|
}
|
|
|
|
type Guard struct {
|
|
// state is swapped atomically by the Update* methods. Read it via Load.
|
|
state atomic.Pointer[guardState]
|
|
// updateMu serializes the read-modify-write inside the Update* methods so
|
|
// concurrent reloads don't clobber each other; readers stay lock-free.
|
|
updateMu sync.Mutex
|
|
}
|
|
|
|
func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int, previousSigningKey string, previousReadSigningKey string) *Guard {
|
|
g := &Guard{}
|
|
g.state.Store(&guardState{
|
|
signingKey: SigningKey(signingKey),
|
|
expiresAfterSec: expiresAfterSec,
|
|
readSigningKey: SigningKey(readSigningKey),
|
|
readExpiresAfterSec: readExpiresAfterSec,
|
|
previousSigningKey: SigningKey(previousSigningKey),
|
|
previousReadSigningKey: SigningKey(previousReadSigningKey),
|
|
})
|
|
g.UpdateWhiteList(whiteList)
|
|
return g
|
|
}
|
|
|
|
func (g *Guard) SigningKey() SigningKey { return g.state.Load().signingKey }
|
|
func (g *Guard) ExpiresAfterSec() int { return g.state.Load().expiresAfterSec }
|
|
func (g *Guard) ReadSigningKey() SigningKey { return g.state.Load().readSigningKey }
|
|
func (g *Guard) ReadExpiresAfterSec() int { return g.state.Load().readExpiresAfterSec }
|
|
|
|
// VerificationKeys returns the write (or read) signing key and the previous
|
|
// key still accepted for it, from one snapshot.
|
|
func (g *Guard) VerificationKeys(isWrite bool) (signingKey, previousSigningKey SigningKey) {
|
|
st := g.state.Load()
|
|
if isWrite {
|
|
return st.signingKey, st.previousSigningKey
|
|
}
|
|
return st.readSigningKey, st.previousReadSigningKey
|
|
}
|
|
|
|
func (g *Guard) WhiteList(f http.HandlerFunc) http.HandlerFunc {
|
|
if !g.state.Load().isWriteActive {
|
|
//if no security needed, just skip all checking
|
|
return f
|
|
}
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if err := g.checkWhiteList(w, r); err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
f(w, r)
|
|
}
|
|
}
|
|
|
|
func GetActualRemoteHost(r *http.Request) string {
|
|
// For security reasons, only use RemoteAddr to determine the client's IP address.
|
|
// Do not trust headers like X-Forwarded-For, as they can be easily spoofed by clients.
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err == nil {
|
|
return host
|
|
}
|
|
|
|
// If SplitHostPort fails, it may be because of a missing port.
|
|
// We try to parse RemoteAddr as a raw host (IP or hostname).
|
|
host = strings.TrimSpace(r.RemoteAddr)
|
|
// It might be an IPv6 address without a port, but with brackets.
|
|
// e.g. "[::1]"
|
|
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
|
|
host = host[1 : len(host)-1]
|
|
}
|
|
|
|
// Return the host (can be IP or hostname, just like headers)
|
|
return host
|
|
}
|
|
|
|
func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
|
|
host := GetActualRemoteHost(r)
|
|
if g.IsWhiteListed(host) {
|
|
return nil
|
|
}
|
|
glog.V(0).Infof("Not in whitelist: %s (original RemoteAddr: %s)", host, r.RemoteAddr)
|
|
return fmt.Errorf("Not in whitelist: %s", host)
|
|
}
|
|
|
|
// IsWhiteListed returns true if the given host IP is allowed by the guard.
|
|
// When no whitelist is configured (security inactive), all hosts are allowed.
|
|
func (g *Guard) IsWhiteListed(host string) bool {
|
|
st := g.state.Load()
|
|
if !st.isWriteActive {
|
|
return true
|
|
}
|
|
if st.isEmptyWhiteList {
|
|
return true
|
|
}
|
|
if _, ok := st.whiteListIp[host]; ok {
|
|
return true
|
|
}
|
|
remote := net.ParseIP(host)
|
|
if remote != nil {
|
|
for _, cidrnet := range st.whiteListCIDR {
|
|
if cidrnet.Contains(remote) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// UpdateSigningKeys refreshes the JWT signing keys and their expirations so
|
|
// operators can rotate keys (e.g. via SIGHUP) without restarting the process.
|
|
// It swaps in a new snapshot carrying the existing whitelist, so a concurrent
|
|
// reader sees either the old keys or the new ones, never a torn slice header.
|
|
// Current keys too short for GODEBUG=fips140=only keep the keys in effect, as
|
|
// signing with them would panic; it then returns false.
|
|
func (g *Guard) UpdateSigningKeys(signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int, previousSigningKey string, previousReadSigningKey string) bool {
|
|
if err := util.CheckFips140HmacKeys([]string{"signing key", "read signing key"}, []string{signingKey, readSigningKey}); err != nil {
|
|
glog.Errorf("JWT reload: keeping the keys in effect, because %v", err)
|
|
return false
|
|
}
|
|
previousSigningKey = usablePreviousKey("previous signing key", previousSigningKey)
|
|
previousReadSigningKey = usablePreviousKey("previous read signing key", previousReadSigningKey)
|
|
g.updateMu.Lock()
|
|
defer g.updateMu.Unlock()
|
|
next := *g.state.Load()
|
|
next.signingKey = SigningKey(signingKey)
|
|
next.expiresAfterSec = expiresAfterSec
|
|
next.readSigningKey = SigningKey(readSigningKey)
|
|
next.readExpiresAfterSec = readExpiresAfterSec
|
|
next.previousSigningKey = SigningKey(previousSigningKey)
|
|
next.previousReadSigningKey = SigningKey(previousReadSigningKey)
|
|
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
|
|
g.state.Store(&next)
|
|
return true
|
|
}
|
|
|
|
// ReloadSigningKeys applies the [section] keys after util.LoadConfiguration
|
|
// merged security.toml again. The merge keeps a key the file no longer sets,
|
|
// so the keys are read from the file anew: a removed previous key stops
|
|
// verifying, and a swapped pair comes from one read. A file that cannot be
|
|
// read keeps the keys in effect. It reports whether the new keys are in effect.
|
|
func (g *Guard) ReloadSigningKeys(section string) bool {
|
|
fresh, used := util.ReadConfiguration("security", "")
|
|
if used == "" {
|
|
glog.Warningf("reload %s: security.toml cannot be read, keeping the keys in effect", section)
|
|
return false
|
|
}
|
|
v := util.GetViper()
|
|
return g.UpdateSigningKeys(
|
|
freshKey(fresh, section+".key"),
|
|
v.GetInt(section+".expires_after_seconds"),
|
|
freshKey(fresh, section+".read.key"),
|
|
v.GetInt(section+".read.expires_after_seconds"),
|
|
fresh.GetString(section+".previous_key"),
|
|
fresh.GetString(section+".read.previous_key"),
|
|
)
|
|
}
|
|
|
|
// usablePreviousKey returns key, or "" with an error log when it is too short
|
|
// for HMAC under GODEBUG=fips140=only. Nothing in that mode can sign with such a
|
|
// key, so dropping it rejects no token; keeping the new current keys keeps a
|
|
// reload's outcome the same on servers that pass previous keys and on those
|
|
// that do not, such as the filer's volume signer.
|
|
func usablePreviousKey(name, key string) string {
|
|
if err := util.CheckFips140HmacKey(name, []byte(key)); err != nil {
|
|
glog.Errorf("JWT reload: ignoring the %s, which is shorter than the %d characters FIPS 140 needs for HMAC keys; the new keys are in effect", name, util.Fips140MinHmacKeyBytes)
|
|
return ""
|
|
}
|
|
return key
|
|
}
|
|
|
|
// freshKey returns name as the fresh read sets it, else its merged value, so
|
|
// removing a current key from the file does not turn verification off.
|
|
func freshKey(fresh *util.ViperProxy, name string) string {
|
|
if fresh.IsSet(name) {
|
|
return fresh.GetString(name)
|
|
}
|
|
return util.GetViper().GetString(name)
|
|
}
|
|
|
|
func (g *Guard) UpdateWhiteList(whiteList []string) {
|
|
whiteListIp := make(map[string]struct{})
|
|
whiteListCIDR := make(map[string]*net.IPNet)
|
|
for _, ip := range whiteList {
|
|
if strings.Contains(ip, "/") {
|
|
_, cidrnet, err := net.ParseCIDR(ip)
|
|
if err != nil {
|
|
glog.Errorf("Parse CIDR %s in whitelist failed: %v", ip, err)
|
|
continue
|
|
}
|
|
whiteListCIDR[ip] = cidrnet
|
|
} else {
|
|
whiteListIp[ip] = struct{}{}
|
|
}
|
|
}
|
|
g.updateMu.Lock()
|
|
defer g.updateMu.Unlock()
|
|
next := *g.state.Load()
|
|
next.isEmptyWhiteList = len(whiteListIp) == 0 && len(whiteListCIDR) == 0
|
|
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
|
|
next.whiteListIp = whiteListIp
|
|
next.whiteListCIDR = whiteListCIDR
|
|
g.state.Store(&next)
|
|
}
|