s3: verify SigV4 header values with each SDK's Trimall (Go, Java, botocore) (#13036)

* s3: trim only ASCII spaces in SigV4 canonical header values

signV4TrimAll used strings.Fields, which also splits on Unicode spaces
(U+00A0, U+202F, ...). A signed header whose value holds one inside, such
as an x-amz-meta-* filename from a macOS screenshot ("... at 2.20.09 PM"),
got a different canonical request than the client signed, and the request
failed with SignatureDoesNotMatch. Trim and compress only ' ', as the AWS
SDKs do (aws-sdk-go-v2's v4.StripExcessSpaces).

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

* s3: verify SigV4 with both clients' Trimall for non-ASCII-space whitespace

The AWS SDK for Go v2 collapses only ASCII spaces in a signed header value and
trims the edges with strings.TrimSpace; botocore turns every whitespace
character into a space. Match the Go SDK first (now also trimming Unicode
whitespace at the edges) and, when it gives a different canonical request,
retry with the previous strings.Fields form so botocore signatures keep
verifying.

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

* s3: pass the header value trim to getCanonicalRequest and getCanonicalHeaders

Fold canonicalRequestWith and canonicalHeadersWith into the existing
functions instead of keeping them as wrappers.

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

* s3: also verify SigV4 header values with the AWS SDK for Java Trimall

The Java SDKs collapse runs of spaces and tabs but keep Unicode spaces, so
a value with both a tab and a U+00A0/U+202F matched neither the Go SDK nor
the botocore form. It is tried between the two, so a value with only one
kind of whitespace still computes at most two signatures.

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

---------

Co-authored-by: Bear1110 <14165451+Bear1110@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-26 21:57:31 -08:00
1 parent e743f99bb5
commit aaca5c8c0a
5 files changed
+101 -24

No files matched your search

+37 -17
View File
@@ -613,18 +613,24 @@ func (iam *IdentityAccessManagement) vendedSessionKeyLive(owner, accessKey, fing
// calculateAndVerifySignature contains the core logic for creating the canonical request,
// string-to-sign, and comparing the final signature.
func calculateAndVerifySignature(secretKey, method, urlPath, queryStr string, extractedSignedHeaders http.Header, authInfo *v4AuthInfo) (string, s3err.ErrorCode) {
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, authInfo.HashedPayload, queryStr, urlPath, method)
stringToSign := getStringToSign(canonicalRequest, authInfo.Date, authInfo.Scope)
signingKey := getSigningKey(secretKey, authInfo.Date.Format(yyyymmdd), authInfo.Region, authInfo.Service)
newSignature := getSignature(signingKey, stringToSign)
if !compareSignatureV4(newSignature, authInfo.Signature) {
glog.V(4).Infof("Signature mismatch. Details:\n- CanonicalRequest: %q\n- StringToSign: %q\n- Calculated: %s, Provided: %s",
canonicalRequest, stringToSign, newSignature, authInfo.Signature)
return "", s3err.ErrSignatureDoesNotMatch
var canonicalRequest, stringToSign, newSignature string
for i, trim := range signV4HeaderValueTrims {
cr := getCanonicalRequest(extractedSignedHeaders, authInfo.HashedPayload, queryStr, urlPath, method, trim)
if i > 0 && cr == canonicalRequest {
continue // same canonical request, same signature
}
canonicalRequest = cr
stringToSign = getStringToSign(canonicalRequest, authInfo.Date, authInfo.Scope)
newSignature = getSignature(signingKey, stringToSign)
if compareSignatureV4(newSignature, authInfo.Signature) {
return newSignature, s3err.ErrNone
}
}
return newSignature, s3err.ErrNone
glog.V(4).Infof("Signature mismatch. Details:\n- CanonicalRequest: %q\n- StringToSign: %q\n- Calculated: %s, Provided: %s",
canonicalRequest, stringToSign, newSignature, authInfo.Signature)
return "", s3err.ErrSignatureDoesNotMatch
}
func extractV4AuthInfo(r *http.Request) (*v4AuthInfo, s3err.ErrorCode) {
@@ -1224,14 +1230,14 @@ func getScope(t time.Time, region string, service string) string {
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string) string {
func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string, trim func(string) string) string {
rawQuery := strings.Replace(queryStr, "+", "%20", -1)
encodedPath := encodePath(urlPath)
canonicalRequest := strings.Join([]string{
method,
encodedPath,
rawQuery,
getCanonicalHeaders(extractedSignedHeaders),
getCanonicalHeaders(extractedSignedHeaders, trim),
getSignedHeaders(extractedSignedHeaders),
payload,
}, "\n")
@@ -1269,7 +1275,7 @@ func getSigningKey(secretKey string, time string, region string, service string)
}
// getCanonicalHeaders generate a list of request headers with their values
func getCanonicalHeaders(signedHeaders http.Header) string {
func getCanonicalHeaders(signedHeaders http.Header, trim func(string) string) string {
var headers []string
vals := make(http.Header)
for k, vv := range signedHeaders {
@@ -1288,18 +1294,32 @@ func getCanonicalHeaders(signedHeaders http.Header) string {
if idx > 0 {
buf.WriteByte(',')
}
buf.WriteString(signV4TrimAll(v))
buf.WriteString(trim(v))
}
buf.WriteByte('\n')
}
return buf.String()
}
// signV4TrimAll trims leading and trailing spaces from each string in the slice, and trims sequential spaces.
// SigV4 clients disagree on Trimall for whitespace other than the ASCII space,
// so a signature is checked against each client's form in turn.
var signV4HeaderValueTrims = []func(string) string{signV4TrimAll, signV4TrimAllASCIIWhitespace, signV4TrimAllWhitespace}
// signV4TrimAll compresses sequential ASCII spaces in a header value to one and
// trims leading and trailing whitespace, as the AWS SDK for Go v2 does.
func signV4TrimAll(input string) string {
// Compress adjacent spaces (a space is determined by
// unicode.IsSpace() internally here) to a single space and trim
// leading and trailing spaces.
return strings.TrimSpace(strings.Join(strings.FieldsFunc(input, func(r rune) bool { return r == ' ' }), " "))
}
// signV4TrimAllASCIIWhitespace turns every run of spaces and tabs into a single
// space and keeps other whitespace, as the AWS SDK for Java does.
func signV4TrimAllASCIIWhitespace(input string) string {
return strings.Join(strings.FieldsFunc(input, func(r rune) bool { return r == ' ' || r == '\t' }), " ")
}
// signV4TrimAllWhitespace turns every run of whitespace into a single space and
// trims the edges, as botocore does.
func signV4TrimAllWhitespace(input string) string {
return strings.Join(strings.Fields(input), " ")
}
+59 -2
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"net/url"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -674,7 +675,7 @@ func TestExtractSignedHeadersCase(t *testing.T) {
if errCode != s3err.ErrNone {
t.Fatalf("extractSignedHeaders failed: %v", errCode)
}
actual := getCanonicalHeaders(extracted)
actual := getCanonicalHeaders(extracted, signV4TrimAll)
if actual != tt.expected {
t.Errorf("%s: expected %q, got %q", tt.name, tt.expected, actual)
}
@@ -693,7 +694,7 @@ func TestExtractSignedHeadersContentLength(t *testing.T) {
if errCode != s3err.ErrNone {
t.Fatalf("extractSignedHeaders failed: %v", errCode)
}
if got := getCanonicalHeaders(extracted); got != "content-length:0\nhost:bucket.domain.com\n" {
if got := getCanonicalHeaders(extracted, signV4TrimAll); got != "content-length:0\nhost:bucket.domain.com\n" {
t.Fatalf("unexpected canonical headers %q", got)
}
}
@@ -768,3 +769,59 @@ func TestSignatureV4WithForwardedPrefixUnicodeKey(t *testing.T) {
t.Fatalf("signature verification failed for unicode key behind forwarded prefix: code %d", int(errCode))
}
}
func TestSignV4TrimAll(t *testing.T) {
tests := []struct {
in, sdkGoV2, sdkJava, botocore string
}{
{" a b ", "a b", "a b", "a b"},
{"plain", "plain", "plain", "plain"},
{"tab\tkept", "tab\tkept", "tab kept", "tab kept"},
{"at 2.20.09\u202fPM.png", "at 2.20.09\u202fPM.png", "at 2.20.09\u202fPM.png", "at 2.20.09 PM.png"},
{"news\u00a0| headline.txt", "news\u00a0| headline.txt", "news\u00a0| headline.txt", "news | headline.txt"},
{" report.txt\u00a0 ", "report.txt", "report.txt\u00a0", "report.txt"},
{"at 2.20.09\u202fPM\tcopy.png", "at 2.20.09\u202fPM\tcopy.png", "at 2.20.09\u202fPM copy.png", "at 2.20.09 PM copy.png"},
}
for _, tt := range tests {
if got := signV4TrimAll(tt.in); got != tt.sdkGoV2 {
t.Errorf("signV4TrimAll(%q) = %q, want %q", tt.in, got, tt.sdkGoV2)
}
if got := signV4TrimAllASCIIWhitespace(tt.in); got != tt.sdkJava {
t.Errorf("signV4TrimAllASCIIWhitespace(%q) = %q, want %q", tt.in, got, tt.sdkJava)
}
if got := signV4TrimAllWhitespace(tt.in); got != tt.botocore {
t.Errorf("signV4TrimAllWhitespace(%q) = %q, want %q", tt.in, got, tt.botocore)
}
}
}
func TestCalculateAndVerifySignatureTrimVariants(t *testing.T) {
headers := http.Header{}
headers.Set("Host", "bucket.domain.com")
headers.Set("X-Amz-Meta-Filename", "at 2.20.09\u202fPM\tcopy.png")
date := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
const secret, payload = "secret", "UNSIGNED-PAYLOAD"
scope := getScope(date, "us-east-1", "s3")
signingKey := getSigningKey(secret, date.Format(yyyymmdd), "us-east-1", "s3")
for name, trim := range map[string]func(string) string{
"sdk-go-v2": signV4TrimAll,
"sdk-java-v2": signV4TrimAllASCIIWhitespace,
"botocore": signV4TrimAllWhitespace,
} {
t.Run(name, func(t *testing.T) {
canonical := getCanonicalRequest(headers, payload, "", "/bucket/key", http.MethodPut, trim)
signature := getSignature(signingKey, getStringToSign(canonical, date, scope))
authInfo := &v4AuthInfo{HashedPayload: payload, Date: date, Scope: scope, Region: "us-east-1", Service: "s3", Signature: signature}
got, errCode := calculateAndVerifySignature(secret, http.MethodPut, "/bucket/key", "", headers, authInfo)
if errCode != s3err.ErrNone || got != signature {
t.Fatalf("got %q, %v; want %q", got, errCode, signature)
}
})
}
authInfo := &v4AuthInfo{HashedPayload: payload, Date: date, Scope: scope, Region: "us-east-1", Service: "s3", Signature: strings.Repeat("0", 64)}
if _, errCode := calculateAndVerifySignature(secret, http.MethodPut, "/bucket/key", "", headers, authInfo); errCode != s3err.ErrSignatureDoesNotMatch {
t.Fatalf("wrong signature: got %v, want ErrSignatureDoesNotMatch", errCode)
}
}
@@ -358,7 +358,7 @@ func preSignV4WithHeaders(_ *IdentityAccessManagement, req *http.Request, access
}
}
canonicalRequest := getCanonicalRequest(extracted, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method)
canonicalRequest := getCanonicalRequest(extracted, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method, signV4TrimAll)
stringToSign := getStringToSign(canonicalRequest, now, scope)
signingKey := getSigningKey(secretKey, now.Format(yyyymmdd), "us-east-1", "s3")
signature := getSignature(signingKey, stringToSign)
+3 -3
View File
@@ -271,7 +271,7 @@ func preSignV4(iam *IdentityAccessManagement, req *http.Request, accessKey, secr
extractedSignedHeaders["host"] = []string{req.Host}
// Get canonical request
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method)
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, req.URL.Path, req.Method, signV4TrimAll)
// Get string to sign
stringToSign := getStringToSign(canonicalRequest, now, scope)
@@ -1033,7 +1033,7 @@ func preSignV4WithPath(iam *IdentityAccessManagement, req *http.Request, accessK
extractedSignedHeaders["host"] = []string{extractHostHeader(req, "")}
// Get canonical request with custom path
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method)
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method, signV4TrimAll)
// Get string to sign
stringToSign := getStringToSign(canonicalRequest, now, scope)
@@ -1076,7 +1076,7 @@ func signV4WithPath(req *http.Request, accessKey, secretKey, urlPath string) {
hashedPayload := getContentSha256Cksum(req)
// Get canonical request with custom path
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method)
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, req.URL.RawQuery, urlPath, req.Method, signV4TrimAll)
// Get string to sign
stringToSign := getStringToSign(canonicalRequest, now, scope)
+1 -1
View File
@@ -245,7 +245,7 @@ func TestPrebufferedSignedBodyChecksContentMd5(t *testing.T) {
"x-amz-date": {req.Header.Get("X-Amz-Date")},
}
sum := sha256.Sum256(body)
canonical := getCanonicalRequest(signed, hex.EncodeToString(sum[:]), "", "/", http.MethodPost)
canonical := getCanonicalRequest(signed, hex.EncodeToString(sum[:]), "", "/", http.MethodPost, signV4TrimAll)
signature := getSignature(getSigningKey("secret_key_1", now.Format(yyyymmdd), "us-east-1", "iam"), getStringToSign(canonical, now, scope))
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=access_key_1/"+scope+", SignedHeaders=content-md5;content-type;host;x-amz-date, Signature="+signature)
return req