mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(cognito): HMAC-sign refresh tokens to prevent forgery (#2139)
* fix(cognito): HMAC-sign refresh tokens to prevent forgery Refresh tokens were plain poolId|username|clientId|issuedAt|familyId strings, base64-encoded with no signature or encryption. Anyone who knew a pool id, client id, and a valid username could hand-craft a token accepted by InitiateAuth REFRESH_TOKEN_AUTH / GetTokensFrom RefreshToken, unlike real Cognito, which documents refresh tokens as encrypted and opaque. buildRefreshToken now appends an HmacSHA256 signature over the payload, keyed by a random secret generated and persisted per pool (mirroring the existing lazy RSA JWT signing key pattern). parse RefreshToken verifies that signature with a constant-time comparison before returning any decoded field, and rejects the token (same as today's null-parse contract) on any mismatch, tampering, or unknown pool. * fix(cognito): reject invalid refresh tokens in REFRESH_TOKEN_AUTH instead of impersonating "unknown" handleRefreshToken fell through to minting real, correctly-signed AccessToken/IdToken JWTs for a hardcoded "unknown" user whenever parseRefreshToken returned null (or adminGetUser failed). With refresh tokens now HMAC-verified, every forged/tampered/garbage token takes that null path, so this fallback would have kept handing out valid signed tokens for exactly the forgery attempts this fix is meant to close off. parseRefreshToken returning null is now treated the same way it already is in getTokensFromRefreshToken: NotAuthorizedException / "Invalid Refresh Token". * fix(cognito): guard non-numeric issued-at and drop unused variable in handleRefreshToken Static analysis flagged two issues in the handleRefreshToken rewrite: Long.parseLong(parts[3]) could throw an uncaught NumberFormatException, and tokenClientId was parsed but never read. Wrap the parse and reject with the same NotAuthorizedException/"Invalid Refresh Token" used elsewhere in this method, and drop the dead variable.
This commit is contained in:
1 parent
8d2a5bdd46
commit
c4f4181c3d
4 files changed
+182
-39
No files matched your search
+19
-24
@@ -231,32 +231,27 @@ final class CognitoAuthFlowHandler {
|
||||
String refreshToken = params.get("REFRESH_TOKEN");
|
||||
if (refreshToken == null) throw new AwsException("InvalidParameterException", "REFRESH_TOKEN is required", 400);
|
||||
String[] parts = service.parseRefreshToken(refreshToken);
|
||||
if (parts != null) {
|
||||
String username = parts[1];
|
||||
String tokenClientId = parts[2];
|
||||
long iat = parts.length > 3 && !parts[3].isEmpty() ? Long.parseLong(parts[3]) : 0L;
|
||||
String refreshTokenUuid = parts.length > 4 ? parts[4] : null;
|
||||
|
||||
// Check revocation before issuing new tokens
|
||||
service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
|
||||
|
||||
try {
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), username);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
|
||||
clientMetadata, "TokenGeneration_RefreshTokens");
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", auth);
|
||||
return result;
|
||||
} catch (AwsException ignored) { }
|
||||
if (parts == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
|
||||
}
|
||||
String username = parts[1];
|
||||
long iat;
|
||||
try {
|
||||
iat = parts.length > 3 && !parts[3].isEmpty() ? Long.parseLong(parts[3]) : 0L;
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid Refresh Token", 400);
|
||||
}
|
||||
String refreshTokenUuid = parts.length > 4 ? parts[4] : null;
|
||||
|
||||
// Check revocation before issuing new tokens
|
||||
service.validateRefreshTokenNotRevoked(refreshTokenUuid, pool.getId(), username, iat);
|
||||
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), username);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
|
||||
clientMetadata, "TokenGeneration_RefreshTokens");
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", service.generateTokenString("access", "unknown", pool, client));
|
||||
auth.put("IdToken", service.generateTokenString("id", "unknown", pool, client));
|
||||
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
auth.put("ExpiresIn", service.getAccessTokenExpiresInSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
@@ -25,6 +25,8 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
@@ -166,6 +168,7 @@ public class CognitoService {
|
||||
populateUserPool(pool, request);
|
||||
|
||||
ensureJwtSigningKeys(pool);
|
||||
ensureRefreshTokenSecret(pool);
|
||||
poolStore.put(id, pool);
|
||||
LOG.infov("Created User Pool: {0}", id);
|
||||
return pool;
|
||||
@@ -271,7 +274,9 @@ public class CognitoService {
|
||||
public UserPool describeUserPool(String id) {
|
||||
UserPool pool = poolStore.get(id)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
|
||||
if (ensureJwtSigningKeys(pool)) {
|
||||
boolean generatedKeys = ensureJwtSigningKeys(pool);
|
||||
boolean generatedSecret = ensureRefreshTokenSecret(pool);
|
||||
if (generatedKeys || generatedSecret) {
|
||||
poolStore.put(id, pool);
|
||||
}
|
||||
return pool;
|
||||
@@ -1703,7 +1708,7 @@ public class CognitoService {
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id", client, override, originJti));
|
||||
auth.put("RefreshToken", buildRefreshToken(pool.getId(), user.getUsername(), client.getClientId(), originJti));
|
||||
auth.put("RefreshToken", buildRefreshToken(pool, user.getUsername(), client.getClientId(), originJti));
|
||||
auth.put("ExpiresIn", resolveAccessTokenLifetimeSeconds(client));
|
||||
auth.put("TokenType", "Bearer");
|
||||
return auth;
|
||||
@@ -2192,6 +2197,32 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean ensureRefreshTokenSecret(UserPool pool) {
|
||||
synchronized (pool) {
|
||||
if (pool.getSigningSecret() != null && !pool.getSigningSecret().isBlank()) {
|
||||
return false;
|
||||
}
|
||||
byte[] secretBytes = new byte[32];
|
||||
new SecureRandom().nextBytes(secretBytes);
|
||||
pool.setSigningSecret(Base64.getEncoder().encodeToString(secretBytes));
|
||||
if (pool.getId() != null) {
|
||||
pool.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
static String hmacSha256(byte[] key, String data) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return Base64.getEncoder().withoutPadding()
|
||||
.encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to compute refresh token HMAC", e);
|
||||
}
|
||||
}
|
||||
|
||||
String hashPassword(String password) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
@@ -2293,11 +2324,20 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
String buildRefreshToken(String poolId, String username, String clientId, String originJti) {
|
||||
String buildRefreshToken(UserPool pool, String username, String clientId, String originJti) {
|
||||
if (ensureRefreshTokenSecret(pool)) {
|
||||
poolStore.put(pool.getId(), pool);
|
||||
}
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
String familyId = originJti != null ? originJti : UUID.randomUUID().toString();
|
||||
String raw = poolId + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;
|
||||
return Base64.getEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
String raw = pool.getId() + "|" + username + "|" + clientId + "|" + issuedAt + "|" + familyId;
|
||||
String signature = hmacSha256(refreshTokenSecretBytes(pool), raw);
|
||||
return Base64.getEncoder().withoutPadding()
|
||||
.encodeToString((raw + "|" + signature).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
static byte[] refreshTokenSecretBytes(UserPool pool) {
|
||||
return Base64.getDecoder().decode(pool.getSigningSecret());
|
||||
}
|
||||
|
||||
private boolean isTokenRevocationEnabled(UserPoolClient client) {
|
||||
@@ -2309,13 +2349,21 @@ public class CognitoService {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(refreshToken);
|
||||
String raw = new String(decoded, StandardCharsets.UTF_8);
|
||||
String[] parts = raw.split("\\|", 5);
|
||||
if (parts.length == 5) {
|
||||
return parts; // [poolId, username, clientId, issuedAt, nonce]
|
||||
String[] parts = raw.split("\\|", 6);
|
||||
if (parts.length != 6) {
|
||||
return null;
|
||||
}
|
||||
if (parts.length == 4) {
|
||||
return new String[] { parts[0], parts[1], parts[2], "", parts[3] };
|
||||
UserPool pool = poolStore.get(parts[0]).orElse(null);
|
||||
if (pool == null || pool.getSigningSecret() == null || pool.getSigningSecret().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String payload = String.join("|", Arrays.copyOf(parts, 5));
|
||||
byte[] expectedSignature = Base64.getDecoder().decode(hmacSha256(refreshTokenSecretBytes(pool), payload));
|
||||
byte[] actualSignature = Base64.getDecoder().decode(parts[5]);
|
||||
if (!MessageDigest.isEqual(expectedSignature, actualSignature)) {
|
||||
return null;
|
||||
}
|
||||
return Arrays.copyOf(parts, 5); // [poolId, username, clientId, issuedAt, nonce]
|
||||
} catch (Exception ignored) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ public class UserPool {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
this.lastModifiedDate = now;
|
||||
this.signingSecret = java.util.UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
|
||||
Reference in new issue
Block a user