mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(security): reject unregistered SigV4 access keys and unbound usernames (#2680)
* fix(security): reject unregistered SigV4 access keys and unbound usernames
SigV4Validator.java and RdsSigV4Validator.java both fell back to
`iamService.findSecretKey(accessKeyId).orElse(accessKeyId)` when the
access key wasn't registered. Since the attacker chooses accessKeyId
themselves, they can self-sign a token using secret == accessKeyId,
producing the exact signing key this fallback derives -- a full
signature-forgery auth bypass for any unregistered IAM key. Both now
fail closed when the key isn't registered.
SigV4Validator's ElastiCache username binding
(`expectedUsername != null && user != null && !expectedUsername.equals(user)`)
also skipped the check whenever the token simply omitted the User
query param, letting any expectedUsername through. Dropped the
`user != null` conjunct so a null user now correctly fails the check.
Each fix has a RED test proving the exploit against the unpatched
code (self-signed token with secret == accessKeyId; token missing
User) before asserting the fixed behavior.
RdsSigV4Validator's DBUser check was investigated but is not
vulnerable: DBUser is already required by the missing-parameters
check above it, so the null-skip path is unreachable via a crafted
token. PreSignedUrlFilter's well-known "test"/"test" credential and
its lack of a bucket-ownership check were also investigated and are
not presigned-URL-specific bugs -- see
issues/sigv4-review-remaining-findings.md for the evidence and for
everything else from the review pass deferred out of this PR.
* fix(security): restore well-known local-dev credential, sanitize log lines
The fail-closed fix in the prior commit broke the emulator's default
local-dev credential flow: AwsBasicCredentials.create("test", "test")
is used pervasively by SDK clients against RDS/ElastiCache IAM auth
(and S3) in this project's compat test suite, and was never actually
registered in IamService -- it only "worked" before because the
vulnerable fallback happened to derive the same secret ("test") from
the access key ID by coincidence (accessKeyId == secretKey == "test").
Carve out that exact, already-public pair explicitly in both
validators, mirroring the identical LEGACY_ACCESS_KEY_ID/SECRET_KEY
idiom already used by S3Service/PreSignedUrlFilter -- this does not
reopen the forgery bug, since it only ever matches the literal string
"test", never an attacker-chosen access key.
Also addresses two Copilot review comments: the debug logs added in
the fail-closed fix (and the pre-existing signature-mismatch log)
interpolated the attacker-controlled, URL-decoded accessKeyId with no
sanitization, allowing CR/LF-based log injection. Added a
sanitizeForLog helper (strips control characters) and applied it to
every log line that includes accessKeyId in both files.
* docs(security): update ledger after rebasing past PR #2657's merge
PR #2657 merged with the misleading "always fails the signature check"
comment in both SigV4Validator.java and RdsSigV4Validator.java (not
just the ElastiCache file, as first flagged). Rebasing this branch
onto upstream/main produced real conflicts on both files; resolved by
keeping the fail-closed fix and dropping the comment. Updated the
ledger from future-tense speculation to the resolved outcome.
This commit is contained in:
1 parent
acf88794ca
commit
f9d28c9649
6 files changed
+423
-15
No files matched your search
@@ -0,0 +1,202 @@
|
||||
# SigV4 / presigned-URL review — remaining findings
|
||||
|
||||
Companion to branch `fix/sigv4-auth-bypass` (PR fixing the SigV4 signature-forgery
|
||||
auth-bypass). This ledgers everything from the original review pass that is
|
||||
**not** fixed in that PR, plus two findings from the original brief that turned
|
||||
out, on investigation, not to be real bugs.
|
||||
|
||||
Source review: `.temp/wt-l10-lambdaowner/review-2657.md` (41 findings across 6 files).
|
||||
|
||||
## Fixed in fix/sigv4-auth-bypass
|
||||
|
||||
- `SigV4Validator.java:104` (elasticache) — unregistered access key fell back to
|
||||
itself as the signing secret (self-signable auth bypass). Fixed: fail closed
|
||||
when `findSecretKey` returns empty.
|
||||
- `RdsSigV4Validator.java:104` — identical bug, identical fix.
|
||||
- `SigV4Validator.java:80` (elasticache) — `expectedUsername != null && user != null && ...`
|
||||
let a token that omits `User` bypass the username binding. Fixed: drop the
|
||||
`user != null` conjunct.
|
||||
|
||||
## Investigated, NOT bugs — do not re-fix
|
||||
|
||||
- **`RdsSigV4Validator.java:80`** (originally flagged as the same missing-User
|
||||
bypass as the ElastiCache file). Not exploitable here: `dbUser` is in the
|
||||
required-parameters check at line 74-75, so `dbUser` can never be null by the
|
||||
time line 80 runs. The `clientUsername == null` branch is the documented
|
||||
"may be null to skip" contract, and the only live caller
|
||||
(`PostgresProtocolHandler.java:84`) always passes a real username. Confirmed
|
||||
by a RED test that could not be made to fail — the exploit doesn't exist.
|
||||
|
||||
- **`PreSignedUrlFilter.java:30` — hardcoded "test"/"test" credential accepted
|
||||
under auth enforcement.** Originally flagged HIGH. This is a deliberate,
|
||||
already-tested convenience credential, not a presigned-URL-specific hole:
|
||||
`S3Service.isKnownAccessKey` (S3Service.java, private method backing
|
||||
`authorizeSignedRequest`/`authorizeS3Read`/`authorizeObjectWrite`) has the
|
||||
identical `LEGACY_ACCESS_KEY_ID.equals(accessKeyId)` fallback, and
|
||||
`S3AuthEnforcementIntegrationTest.java` has two tests — line 210
|
||||
(`signedRequestWithLocalAccessKeyCanReadPrivateObject`, header-signed) and
|
||||
line 222 (`presignedRequestWithLocalAccessKeyCanReadPrivateObject`, presigned)
|
||||
— that assert this credential works identically on *both* paths under
|
||||
enforced auth. I removed the fallback from `PreSignedUrlFilter.resolveSecretKey`
|
||||
as a RED test, confirmed it broke both of the above tests plus two others in
|
||||
that suite, and reverted. If this convenience credential is ever revoked,
|
||||
it has to happen symmetrically in `S3Service.isKnownAccessKey` too — that's
|
||||
an architectural decision (removes a documented local-dev affordance for the
|
||||
entire S3 emulator, not a 3-line patch), out of scope for a signature-forgery
|
||||
fix PR.
|
||||
|
||||
- **`PreSignedUrlFilter.java:128` — signature verified but no bucket/key
|
||||
authorization check.** Originally flagged HIGH. Checked: `S3Service` has no
|
||||
bucket-owner/account field anywhere, and `authorizeS3Read`/`authorizeObjectWrite`
|
||||
return early ("allow") for *any* signed request with a known access key,
|
||||
regardless of path — this is the same idiom used for ordinary header-signed
|
||||
requests via `S3RequestAuthorizationParser` + `S3Controller` (see
|
||||
`S3Controller.java:720,797,802,...` calling `authorizeObjectRead`/
|
||||
`authorizePutObject`). Multi-account bucket ownership enforcement doesn't
|
||||
exist anywhere in this codebase's S3 implementation; this isn't a gap
|
||||
`PreSignedUrlFilter` introduced. Real per-account S3 authorization would be a
|
||||
separate, much larger feature.
|
||||
|
||||
**Related, unresolved, worth a second look:** `S3RequestAuthorizationParser.parse`
|
||||
returns `RequestAuthorization(true, accessKeyId)` for a presigned request
|
||||
based only on the *presence* of `X-Amz-Algorithm` in the query string — it
|
||||
does not itself verify the signature. Actual signature verification happens
|
||||
separately in `PreSignedUrlFilter`. These two are independent checks that
|
||||
currently line up because the filter runs on every request with
|
||||
`X-Amz-Algorithm` set. If any route ever reaches `S3Controller`'s
|
||||
`authorizeObjectRead`/etc. without `PreSignedUrlFilter` having run first,
|
||||
that route would treat `signed=true` (and thus "authorized") for a payload
|
||||
whose signature was never checked. I did not find such a route, but I also
|
||||
didn't exhaustively verify filter registration/ordering across every
|
||||
`@Provider`. Worth a targeted audit.
|
||||
|
||||
## Deferred — real bug, not fixed here (plumbing too large for this PR)
|
||||
|
||||
- **`RdsSigV4Validator.java:52` — signed host/port never verified against the
|
||||
actual DB endpoint; region/service not pinned (cross-resource token
|
||||
replay).** Real: `validate()` builds its canonical request purely from the
|
||||
token's own `host:port`/region/service and never compares any of it to the
|
||||
endpoint this particular proxy fronts. A token signed for any other RDS
|
||||
instance in the same account validates here.
|
||||
|
||||
Plumbing needed to fix properly (mapped, not implemented):
|
||||
- `RdsSigV4Validator.validate(...)` needs an `expectedHost`, `expectedPort`,
|
||||
`expectedRegion` (and pin `service.equals("rds-db")`).
|
||||
- `RdsAuthProxy` constructor needs to carry those through to the
|
||||
`PostgresProtocolHandler`/`MySqlProtocolHandler` call sites
|
||||
(`PostgresProtocolHandler.java:84`, and the MySQL equivalent).
|
||||
- `RdsProxyManager.startProxy(...)` already receives `advertisedHost` (used
|
||||
today only for `tlsCertificates.ensureHost(advertisedHost)`) and
|
||||
`proxyPort` — both would need to be threaded into `RdsAuthProxy` instead of
|
||||
being dropped.
|
||||
- Region isn't threaded down to `RdsProxyManager` at all today; it's
|
||||
available at the `RdsService` call sites (`instanceRegion` computed just
|
||||
above each `proxyManager.startProxy(...)` call) but not passed.
|
||||
- Seven call sites in `RdsService.java` construct/start proxies:
|
||||
lines 628, 1123, 1319, 1931, 3803, 3887, 4008. All seven would need the new
|
||||
parameters.
|
||||
- **Caveat that needs its own investigation before touching this:**
|
||||
`RdsService.proxyEndpoint(int proxyPort)` calls
|
||||
`currentContainerNetworkResolver.resolvePublishedPort(proxyPort)` — the
|
||||
port a real client signs against (the published/advertised port) is not
|
||||
guaranteed to equal `proxyPort`, the port the proxy binds to internally.
|
||||
Comparing the wrong one would turn a security fix into an outage for every
|
||||
RDS IAM-auth user. This needs to be nailed down before writing the
|
||||
validator-side check, not guessed at in the same PR as the signature fix.
|
||||
|
||||
- **`ContainerLauncher.java` — lost in-flight volume reference race between
|
||||
`ensureCodeVolume` and `releaseCodeVolumeReference`.** Not a SigV4 bug — the
|
||||
7th HIGH finding from the same review pass, unrelated feature area.
|
||||
`ensureCodeVolume` does
|
||||
`volumesInFlight.computeIfAbsent(volName, ...).incrementAndGet()` — the map
|
||||
lookup and the increment are two separate steps. A concurrent
|
||||
`releaseCodeVolumeReference` for the same volume can run its
|
||||
`computeIfPresent` (decrement to 0, remove the mapping) in between: the first
|
||||
thread's `incrementAndGet()` then mutates an `AtomicInteger` that is no
|
||||
longer in the map. The new launch's in-flight reservation is silently lost,
|
||||
so `cleanupSupersededVolumes` sees no reservation and can delete the volume
|
||||
while that launch is still pre-`create()` — Docker auto-creates an empty
|
||||
volume and the container gets an empty `/var/task`.
|
||||
- Fix: make the increment atomic with map membership —
|
||||
`volumesInFlight.compute(volName, (k, c) -> { if (c == null) c = new AtomicInteger(); c.incrementAndGet(); return c; });`
|
||||
(compute's function runs under the bin lock, serialized against
|
||||
`computeIfPresent`). Not fixed here — different subsystem, deserves its
|
||||
own PR and its own tests.
|
||||
- **Collision note:** PR #2657 (`fix/lambda-placeholder-owner-account`)
|
||||
touches `ContainerLauncher.java` extensively (credential-triad
|
||||
all-or-nothing logic) but does *not* touch `ensureCodeVolume`/
|
||||
`releaseCodeVolumeReference`/`volumesInFlight` — no overlap, safe to fix
|
||||
independently whenever picked up.
|
||||
|
||||
## Resolved collision: PR #2657 had reintroduced the false "safe" comment
|
||||
|
||||
PR #2657 (`fix/lambda-placeholder-owner-account`) merged into `upstream/main`
|
||||
as `be892864d` and added this comment directly above the vulnerable
|
||||
`iamService.findSecretKey(accessKeyId).orElse(accessKeyId)` line in **both**
|
||||
`SigV4Validator.java` and `RdsSigV4Validator.java` (not just the ElastiCache
|
||||
file, as first flagged here):
|
||||
|
||||
> "Deliberately no fallback for a bare 12-digit account ID here: trusting an
|
||||
> unregistered numeric access key paired with the well-known "test" secret
|
||||
> would let any client forge an IAM-auth token for an arbitrary account and
|
||||
> authenticate as any matching cache user. An unregistered key falls back to
|
||||
> itself, unchanged (never a valid secret), so it always fails the signature
|
||||
> check below."
|
||||
|
||||
This is the exact false safety claim `fix/sigv4-auth-bypass` proves wrong with
|
||||
a RED test (self-signing with `secret == accessKeyId` produces a matching
|
||||
signature). Rebasing `fix/sigv4-auth-bypass` onto `upstream/main` after #2657
|
||||
merged produced real conflicts on both files (this comment vs. the fail-closed
|
||||
fix); both were resolved by keeping the fail-closed fix and dropping the
|
||||
misleading comment entirely. No follow-up needed here — the comment is gone
|
||||
from both files as of this branch's rebase.
|
||||
|
||||
## Medium/low findings not touched by this PR (from review-2657.md)
|
||||
|
||||
By file:line, one line each — none of these are exploitable auth bypasses,
|
||||
just correctness/robustness/availability issues:
|
||||
|
||||
**SigV4Validator.java (elasticache)**
|
||||
- `:87` — no upper bound on `X-Amz-Expires`, no future-dated-token rejection (medium)
|
||||
- `:102` — credential-scope date/region/service accepted without cross-validation (medium)
|
||||
- `:160` — catch-all exception handler logs only at debug, masking real operational faults (low)
|
||||
|
||||
**RdsSigV4Validator.java**
|
||||
- `:86` — no not-yet-valid check, unbounded `X-Amz-Expires` (medium)
|
||||
- `:96` — credential-scope date vs `X-Amz-Date` not cross-checked; malformed scope rejected with no log (medium)
|
||||
- `:114` — canonical query string sorted by param name only, not name-then-value (low, availability false-negative)
|
||||
- general — `URLDecoder.decode` treats literal `+` as space, can cause spurious mismatches (low)
|
||||
|
||||
**PreSignedUrlFilter.java (s3)**
|
||||
- `:109` — `X-Amz-Credential` is double URL-decoded (JAX-RS already decodes it) (medium)
|
||||
- `:132` — path parsing in the custom-signature branch assumes a leading slash that `UriInfo.getPath()` doesn't have; can select the wrong bucket/key (medium)
|
||||
- `:100` — malformed `X-Amz-Date` throws unhandled from `isExpired()`, producing a 500 instead of 400/403 (medium)
|
||||
- `:150` — credential scope date/region/service accepted verbatim, not cross-checked against `X-Amz-Date`/expected service/region (medium)
|
||||
- `:154` — `signedHeaders.split(";")` NPE risk; no requirement that `host` is among signed headers (low)
|
||||
- `:215` — all verification exceptions swallowed at debug level (low)
|
||||
- `:138` — fail-open (no signature check at all) if both `isAuthEnforced()` and `shouldValidateSignatures()` are false (low, config-dependent)
|
||||
|
||||
**LaunchedContainerAwsEnv.java** (unrelated feature area, same review pass)
|
||||
- `:152` — inconsistent credential triple when host env is partially set (medium)
|
||||
- `:148` — host AWS secrets forwarded into container env, visible via `docker inspect` (medium)
|
||||
- `:146` — warning-once gate can silently stop warning on subsequent real-credential forwards (low)
|
||||
- `:168` — `URI.create(flociEndpoint).getHost()` can NPE-adjacent produce `FLOCI_HOSTNAME=null` (low)
|
||||
- `:160` — `SessionCreds` fields not null-checked before interpolation into env (low)
|
||||
|
||||
**ContainerLauncher.java** (beyond the HIGH race above, unrelated to SigV4)
|
||||
- one uncaught exception permanently kills the volume-cleanup scheduler (medium)
|
||||
- small-code `/var/task` copy uses the non-strict tar path; can start container with partial/empty code (medium)
|
||||
- `copyFileToContainer` never joins its writer thread or surfaces tar failures (medium)
|
||||
- `createTarFromDir` silently drops symlinked directories, mangles symlinks (medium)
|
||||
- `launch()` cleanup only triggers on `RuntimeException`; an `Error` leaks the runtime-api port and container (low)
|
||||
- credential all-or-nothing filter misses legacy `AWS_SECURITY_TOKEN` (low)
|
||||
- `expectExtensions` counts extensions that failed to exec-launch, forcing a full 5s stall every cold start (low)
|
||||
- Lambda version hardcoded to `$LATEST` in env and log-stream name despite versioned functions (low)
|
||||
|
||||
**KubernetesPodLauncher.java** (unrelated feature area, same review pass)
|
||||
- runtime API port released even when server stop fails/times out (medium)
|
||||
- `launch()` cleanup only triggers on `RuntimeException`; Errors leak the port and pod (medium)
|
||||
- interrupted stop leaves pod running and port leaked while handle reports STOPPED (medium)
|
||||
- unauthenticated plain-HTTP code/layer download URLs are guessable (medium)
|
||||
- `awaitRunning` swallows `InterruptedException` without restoring the interrupt flag (low)
|
||||
- `ensureCaConfigMap` check-then-act race causes redundant concurrent applies (low)
|
||||
+31
-8
@@ -15,6 +15,7 @@ import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -28,6 +29,15 @@ public class SigV4Validator {
|
||||
private static final DateTimeFormatter DATETIME_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
/**
|
||||
* Well-known local-dev credential pair used pervasively by default AWS SDK clients
|
||||
* (AwsBasicCredentials.create("test", "test")) against this emulator, mirrored from the
|
||||
* identical fallback in S3Service/PreSignedUrlFilter. Deliberately not a fallback for any
|
||||
* other unregistered access key -- only this exact, already-public pair is honored.
|
||||
*/
|
||||
private static final String LEGACY_ACCESS_KEY_ID = "test";
|
||||
private static final String LEGACY_SECRET_KEY = "test";
|
||||
|
||||
private final IamService iamService;
|
||||
|
||||
@Inject
|
||||
@@ -77,7 +87,7 @@ public class SigV4Validator {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (expectedUsername != null && user != null && !expectedUsername.equals(user)) {
|
||||
if (expectedUsername != null && !expectedUsername.equals(user)) {
|
||||
LOG.debugv("IAM token user mismatch: expected={0}, got={1}",
|
||||
expectedUsername, user);
|
||||
return false;
|
||||
@@ -101,12 +111,17 @@ public class SigV4Validator {
|
||||
String service = credParts[3];
|
||||
String credentialScope = date + "/" + region + "/" + service + "/aws4_request";
|
||||
|
||||
// Deliberately no fallback for a bare 12-digit account ID here: trusting an
|
||||
// unregistered numeric access key paired with the well-known "test" secret would
|
||||
// let any client forge an IAM-auth token for an arbitrary account and authenticate
|
||||
// as any matching cache user. An unregistered key falls back to itself, unchanged
|
||||
// (never a valid secret), so it always fails the signature check below.
|
||||
String secretKey = iamService.findSecretKey(accessKeyId).orElse(accessKeyId);
|
||||
String secretKey;
|
||||
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
|
||||
secretKey = LEGACY_SECRET_KEY;
|
||||
} else {
|
||||
Optional<String> registeredSecretKey = iamService.findSecretKey(accessKeyId);
|
||||
if (registeredSecretKey.isEmpty()) {
|
||||
LOG.debugv("IAM token references unregistered access key={0}", sanitizeForLog(accessKeyId));
|
||||
return false;
|
||||
}
|
||||
secretKey = registeredSecretKey.get();
|
||||
}
|
||||
|
||||
String canonicalQueryString = Arrays.stream(rawPairs)
|
||||
.filter(p -> !rawParamName(p).equals("X-Amz-Signature"))
|
||||
@@ -131,7 +146,7 @@ public class SigV4Validator {
|
||||
expectedSignature.getBytes(StandardCharsets.UTF_8),
|
||||
signature.getBytes(StandardCharsets.UTF_8));
|
||||
if (!valid) {
|
||||
LOG.debugv("IAM token signature mismatch for accessKey={0}", accessKeyId);
|
||||
LOG.debugv("IAM token signature mismatch for accessKey={0}", sanitizeForLog(accessKeyId));
|
||||
}
|
||||
return valid;
|
||||
|
||||
@@ -160,6 +175,14 @@ public class SigV4Validator {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips control characters (CR, LF, etc.) from an attacker-controlled value before it is
|
||||
* interpolated into a log line, preventing log injection / forged multi-line log entries.
|
||||
*/
|
||||
private static String sanitizeForLog(String value) {
|
||||
return value == null ? null : value.replaceAll("\\p{Cntrl}", "");
|
||||
}
|
||||
|
||||
private static byte[] deriveSigningKey(String secretKey, String date, String region,
|
||||
String service) throws Exception {
|
||||
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -30,6 +31,15 @@ public class RdsSigV4Validator {
|
||||
private static final DateTimeFormatter DATETIME_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
/**
|
||||
* Well-known local-dev credential pair used pervasively by default AWS SDK clients
|
||||
* (AwsBasicCredentials.create("test", "test")) against this emulator, mirrored from the
|
||||
* identical fallback in S3Service/PreSignedUrlFilter. Deliberately not a fallback for any
|
||||
* other unregistered access key -- only this exact, already-public pair is honored.
|
||||
*/
|
||||
private static final String LEGACY_ACCESS_KEY_ID = "test";
|
||||
private static final String LEGACY_SECRET_KEY = "test";
|
||||
|
||||
private final IamService iamService;
|
||||
|
||||
@Inject
|
||||
@@ -101,12 +111,17 @@ public class RdsSigV4Validator {
|
||||
String service = credParts[3];
|
||||
String credentialScope = date + "/" + region + "/" + service + "/aws4_request";
|
||||
|
||||
// Deliberately no fallback for a bare 12-digit account ID here: trusting an
|
||||
// unregistered numeric access key paired with the well-known "test" secret would
|
||||
// let any client forge an IAM-auth token for an arbitrary account and authenticate
|
||||
// as any matching database user. An unregistered key falls back to itself, unchanged
|
||||
// (never a valid secret), so it always fails the signature check below.
|
||||
String secretKey = iamService.findSecretKey(accessKeyId).orElse(accessKeyId);
|
||||
String secretKey;
|
||||
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
|
||||
secretKey = LEGACY_SECRET_KEY;
|
||||
} else {
|
||||
Optional<String> registeredSecretKey = iamService.findSecretKey(accessKeyId);
|
||||
if (registeredSecretKey.isEmpty()) {
|
||||
LOG.debugv("RDS IAM token references unregistered access key={0}", sanitizeForLog(accessKeyId));
|
||||
return false;
|
||||
}
|
||||
secretKey = registeredSecretKey.get();
|
||||
}
|
||||
|
||||
// Canonical query string: sorted pairs, excluding X-Amz-Signature
|
||||
String canonicalQueryString = Arrays.stream(rawPairs)
|
||||
@@ -133,7 +148,7 @@ public class RdsSigV4Validator {
|
||||
expectedSignature.getBytes(StandardCharsets.UTF_8),
|
||||
signature.getBytes(StandardCharsets.UTF_8));
|
||||
if (!valid) {
|
||||
LOG.debugv("RDS IAM token signature mismatch for accessKey={0}", accessKeyId);
|
||||
LOG.debugv("RDS IAM token signature mismatch for accessKey={0}", sanitizeForLog(accessKeyId));
|
||||
}
|
||||
return valid;
|
||||
|
||||
@@ -162,6 +177,14 @@ public class RdsSigV4Validator {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips control characters (CR, LF, etc.) from an attacker-controlled value before it is
|
||||
* interpolated into a log line, preventing log injection / forged multi-line log entries.
|
||||
*/
|
||||
private static String sanitizeForLog(String value) {
|
||||
return value == null ? null : value.replaceAll("\\p{Cntrl}", "");
|
||||
}
|
||||
|
||||
private static byte[] deriveSigningKey(String secretKey, String date, String region,
|
||||
String service) throws Exception {
|
||||
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
+82
@@ -5,8 +5,10 @@ import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -230,4 +232,84 @@ class SigV4ValidatorTest {
|
||||
|
||||
assertFalse(validator.validate(withoutSignature, "cache-cluster-01", "default"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsTokenSelfSignedWithUnregisteredAccessKeyAsSecret() throws Exception {
|
||||
// Only "AKIDCACHE" is registered; the attacker picks an arbitrary, unregistered
|
||||
// access key and signs using that same access key as the secret. If the validator
|
||||
// ever falls back to accessKeyId as the signing secret for unknown keys, this forged
|
||||
// token would be accepted for any cluster/user the attacker chooses.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
|
||||
|
||||
SigV4Validator validator = new SigV4Validator(iamService);
|
||||
String forgedAccessKeyId = "AKIDFORGEDBYATTACKER";
|
||||
String token = SigV4TokenTestHelper.createElastiCacheToken(
|
||||
"cache-cluster-01",
|
||||
"default",
|
||||
forgedAccessKeyId,
|
||||
forgedAccessKeyId,
|
||||
Instant.now().minusSeconds(60),
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "cache-cluster-01", "default"),
|
||||
"A token self-signed with secret == accessKeyId for an unregistered access key "
|
||||
+ "must never validate; unregistered keys must fail closed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsTokenMissingUserParameterWhenUsernameExpected() throws Exception {
|
||||
// A validly-signed token that simply never includes User as a query param (the
|
||||
// attacker controls exactly what they sign) must not bypass the expectedUsername
|
||||
// identity check just because User is absent.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
|
||||
|
||||
SigV4Validator validator = new SigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createElastiCacheTokenWithoutUser(
|
||||
"cache-cluster-01",
|
||||
"AKIDCACHE",
|
||||
"secret-cache",
|
||||
Instant.now().minusSeconds(60),
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "cache-cluster-01", "default"),
|
||||
"Omitting User from the token must not bypass the expectedUsername identity check");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateAcceptsWellKnownLocalDevCredentialEvenWhenNotRegisteredInIam() throws Exception {
|
||||
// AwsBasicCredentials.create("test", "test") is the default local-dev credential used
|
||||
// pervasively by SDK clients against this emulator (RDS, S3, etc. compat tests). It must
|
||||
// keep working even though it is never registered in IamService -- this is the same
|
||||
// "test"/"test" convenience already honored by S3Service/PreSignedUrlFilter, carved out
|
||||
// explicitly rather than via the removed generic unregistered-key fallback.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDCACHE", "secret-cache");
|
||||
|
||||
SigV4Validator validator = new SigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createElastiCacheToken(
|
||||
"cache-cluster-01",
|
||||
"default",
|
||||
"test",
|
||||
"test",
|
||||
Instant.now().minusSeconds(60),
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "cache-cluster-01", "default"),
|
||||
"The well-known \"test\"/\"test\" local-dev credential pair must still validate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitizeForLogStripsControlCharacters() throws Exception {
|
||||
// A forged accessKeyId containing CR/LF must not be able to inject fake log lines into
|
||||
// the debug logs this validator writes.
|
||||
Method sanitizeForLog = SigV4Validator.class.getDeclaredMethod("sanitizeForLog", String.class);
|
||||
sanitizeForLog.setAccessible(true);
|
||||
|
||||
String malicious = "AKID\r\nINJECTEDLINE\r\n";
|
||||
String sanitized = (String) sanitizeForLog.invoke(null, malicious);
|
||||
|
||||
assertEquals("AKIDINJECTEDLINE", sanitized);
|
||||
}
|
||||
}
|
||||
+65
@@ -5,8 +5,10 @@ import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
|
||||
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -307,4 +309,67 @@ class RdsSigV4ValidatorTest {
|
||||
assertFalse(validator.validate(token, "admin"),
|
||||
"Validator must reject STS token signed with wrong secret");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsTokenSelfSignedWithUnregisteredAccessKeyAsSecret() throws Exception {
|
||||
// Only "AKIDRDS" is registered; the attacker picks an arbitrary, unregistered
|
||||
// access key and signs using that same access key as the secret. If the validator
|
||||
// ever falls back to accessKeyId as the signing secret for unknown keys, this forged
|
||||
// token would be accepted for any DB user the attacker chooses.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String forgedAccessKeyId = "AKIDFORGEDBYATTACKER";
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local",
|
||||
5432,
|
||||
"admin",
|
||||
forgedAccessKeyId,
|
||||
forgedAccessKeyId,
|
||||
Instant.now().minusSeconds(60),
|
||||
900
|
||||
);
|
||||
|
||||
assertFalse(validator.validate(token, "admin"),
|
||||
"A token self-signed with secret == accessKeyId for an unregistered access key "
|
||||
+ "must never validate; unregistered keys must fail closed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateAcceptsWellKnownLocalDevCredentialEvenWhenNotRegisteredInIam() throws Exception {
|
||||
// AwsBasicCredentials.create("test", "test") is the default local-dev credential used
|
||||
// pervasively by SDK clients against this emulator (RDS compat tests generate real IAM
|
||||
// tokens with it). It must keep working even though it is never registered in
|
||||
// IamService -- the same "test"/"test" convenience already honored by
|
||||
// S3Service/PreSignedUrlFilter, carved out explicitly rather than via the removed
|
||||
// generic unregistered-key fallback.
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithAccessKey("AKIDRDS", "secret-rds");
|
||||
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService);
|
||||
String token = SigV4TokenTestHelper.createRdsToken(
|
||||
"db.example.local",
|
||||
5432,
|
||||
"admin",
|
||||
"test",
|
||||
"test",
|
||||
Instant.now().minusSeconds(60),
|
||||
900
|
||||
);
|
||||
|
||||
assertTrue(validator.validate(token, "admin"),
|
||||
"The well-known \"test\"/\"test\" local-dev credential pair must still validate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitizeForLogStripsControlCharacters() throws Exception {
|
||||
// A forged accessKeyId containing CR/LF must not be able to inject fake log lines into
|
||||
// the debug logs this validator writes.
|
||||
Method sanitizeForLog = RdsSigV4Validator.class.getDeclaredMethod("sanitizeForLog", String.class);
|
||||
sanitizeForLog.setAccessible(true);
|
||||
|
||||
String malicious = "AKID\r\nINJECTEDLINE\r\n";
|
||||
String sanitized = (String) sanitizeForLog.invoke(null, malicious);
|
||||
|
||||
assertEquals("AKIDINJECTEDLINE", sanitized);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,19 @@ public final class SigV4TokenTestHelper {
|
||||
"elasticache", timestamp, expiresSeconds, params);
|
||||
}
|
||||
|
||||
public static String createElastiCacheTokenWithoutUser(
|
||||
String clusterId,
|
||||
String accessKeyId,
|
||||
String secretKey,
|
||||
Instant timestamp,
|
||||
int expiresSeconds
|
||||
) throws Exception {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("Action", "connect");
|
||||
return signToken(clusterId, null, clusterId, accessKeyId, secretKey, "us-east-1",
|
||||
"elasticache", timestamp, expiresSeconds, params);
|
||||
}
|
||||
|
||||
public static String createRdsToken(
|
||||
String host,
|
||||
int port,
|
||||
|
||||
Reference in new issue
Block a user