From 7c6e6a6dfaa5fc73ebfa41a17ab40f506baba3c6 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 8 Apr 2026 22:47:49 -0500 Subject: [PATCH] fix: implement SRP-6a authentication for Cognito (#284) (#298) --- compatibility-tests/compat-cdk/bin/app.d.ts | 2 + compatibility-tests/compat-cdk/bin/app.js | 13 + .../compat-cdk/lib/floci-stack.d.ts | 5 + .../compat-cdk/lib/floci-stack.js | 64 ++++ compatibility-tests/compat-cdk/run.sh | 1 + docs/services/cognito.md | 2 +- .../services/cognito/CognitoService.java | 134 +++++++- .../services/cognito/CognitoSrpHelper.java | 308 ++++++++++++++++++ .../services/cognito/model/CognitoUser.java | 8 + .../services/cognito/CognitoServiceTest.java | 47 +++ 10 files changed, 577 insertions(+), 7 deletions(-) create mode 100644 compatibility-tests/compat-cdk/bin/app.d.ts create mode 100644 compatibility-tests/compat-cdk/bin/app.js create mode 100644 compatibility-tests/compat-cdk/lib/floci-stack.d.ts create mode 100644 compatibility-tests/compat-cdk/lib/floci-stack.js create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java diff --git a/compatibility-tests/compat-cdk/bin/app.d.ts b/compatibility-tests/compat-cdk/bin/app.d.ts new file mode 100644 index 0000000000..b7988016da --- /dev/null +++ b/compatibility-tests/compat-cdk/bin/app.d.ts @@ -0,0 +1,2 @@ +#!/usr/bin/env node +export {}; diff --git a/compatibility-tests/compat-cdk/bin/app.js b/compatibility-tests/compat-cdk/bin/app.js new file mode 100644 index 0000000000..b7f9dddf93 --- /dev/null +++ b/compatibility-tests/compat-cdk/bin/app.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const cdk = require("aws-cdk-lib"); +const floci_stack_1 = require("../lib/floci-stack"); +const app = new cdk.App(); +new floci_stack_1.FlociTestStack(app, 'FlociTestStack', { + env: { + account: '000000000000', + region: 'us-east-1', + }, +}); +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYXBwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUNBLG1DQUFtQztBQUNuQyxvREFBb0Q7QUFFcEQsTUFBTSxHQUFHLEdBQUcsSUFBSSxHQUFHLENBQUMsR0FBRyxFQUFFLENBQUM7QUFDMUIsSUFBSSw0QkFBYyxDQUFDLEdBQUcsRUFBRSxnQkFBZ0IsRUFBRTtJQUN4QyxHQUFHLEVBQUU7UUFDSCxPQUFPLEVBQUUsY0FBYztRQUN2QixNQUFNLEVBQUUsV0FBVztLQUNwQjtDQUNGLENBQUMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIiMhL3Vzci9iaW4vZW52IG5vZGVcbmltcG9ydCAqIGFzIGNkayBmcm9tICdhd3MtY2RrLWxpYic7XG5pbXBvcnQgeyBGbG9jaVRlc3RTdGFjayB9IGZyb20gJy4uL2xpYi9mbG9jaS1zdGFjayc7XG5cbmNvbnN0IGFwcCA9IG5ldyBjZGsuQXBwKCk7XG5uZXcgRmxvY2lUZXN0U3RhY2soYXBwLCAnRmxvY2lUZXN0U3RhY2snLCB7XG4gIGVudjoge1xuICAgIGFjY291bnQ6ICcwMDAwMDAwMDAwMDAnLFxuICAgIHJlZ2lvbjogJ3VzLWVhc3QtMScsXG4gIH0sXG59KTtcbiJdfQ== \ No newline at end of file diff --git a/compatibility-tests/compat-cdk/lib/floci-stack.d.ts b/compatibility-tests/compat-cdk/lib/floci-stack.d.ts new file mode 100644 index 0000000000..edd63e529e --- /dev/null +++ b/compatibility-tests/compat-cdk/lib/floci-stack.d.ts @@ -0,0 +1,5 @@ +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +export declare class FlociTestStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps); +} diff --git a/compatibility-tests/compat-cdk/lib/floci-stack.js b/compatibility-tests/compat-cdk/lib/floci-stack.js new file mode 100644 index 0000000000..dc8b6311c9 --- /dev/null +++ b/compatibility-tests/compat-cdk/lib/floci-stack.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FlociTestStack = void 0; +const cdk = require("aws-cdk-lib"); +const s3 = require("aws-cdk-lib/aws-s3"); +const sqs = require("aws-cdk-lib/aws-sqs"); +const dynamodb = require("aws-cdk-lib/aws-dynamodb"); +const secretsmanager = require("aws-cdk-lib/aws-secretsmanager"); +class FlociTestStack extends cdk.Stack { + constructor(scope, id, props) { + super(scope, id, props); + const bucket = new s3.Bucket(this, 'TestBucket', { + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + const queue = new sqs.Queue(this, 'TestQueue', { + queueName: 'floci-cdk-test-queue', + visibilityTimeout: cdk.Duration.seconds(30), + }); + const table = new dynamodb.TableV2(this, 'TestTable', { + tableName: 'floci-cdk-test-table', + partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING }, + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + // DynamoDB table with GSI and LSI — validates CloudFormation index provisioning + const indexTable = new dynamodb.TableV2(this, 'IndexTestTable', { + tableName: 'floci-cdk-index-table', + partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'sk', type: dynamodb.AttributeType.STRING }, + removalPolicy: cdk.RemovalPolicy.DESTROY, + globalSecondaryIndexes: [ + { + indexName: 'gsi-1', + partitionKey: { name: 'gsiPk', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'sk', type: dynamodb.AttributeType.STRING }, + projectionType: dynamodb.ProjectionType.ALL, + }, + ], + localSecondaryIndexes: [ + { + indexName: 'lsi-1', + sortKey: { name: 'lsiSk', type: dynamodb.AttributeType.STRING }, + projectionType: dynamodb.ProjectionType.KEYS_ONLY, + }, + ], + }); + const generatedSecret = new secretsmanager.CfnSecret(this, 'GeneratedSecret', { + name: 'floci-cdk-generated-secret', + generateSecretString: { + secretStringTemplate: '{"username":"admin"}', + generateStringKey: 'password', + passwordLength: 24, + excludeCharacters: 'abc', + }, + }); + generatedSecret.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY); + new cdk.CfnOutput(this, 'BucketName', { value: bucket.bucketName }); + new cdk.CfnOutput(this, 'QueueUrl', { value: queue.queueUrl }); + new cdk.CfnOutput(this, 'TableName', { value: table.tableName }); + new cdk.CfnOutput(this, 'IndexTableName', { value: indexTable.tableName }); + new cdk.CfnOutput(this, 'GeneratedSecretName', { value: generatedSecret.name || 'floci-cdk-generated-secret' }); + } +} +exports.FlociTestStack = FlociTestStack; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmxvY2ktc3RhY2suanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJmbG9jaS1zdGFjay50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSxtQ0FBbUM7QUFDbkMseUNBQXlDO0FBQ3pDLDJDQUEyQztBQUMzQyxxREFBcUQ7QUFDckQsaUVBQWlFO0FBR2pFLE1BQWEsY0FBZSxTQUFRLEdBQUcsQ0FBQyxLQUFLO0lBQzNDLFlBQVksS0FBZ0IsRUFBRSxFQUFVLEVBQUUsS0FBc0I7UUFDOUQsS0FBSyxDQUFDLEtBQUssRUFBRSxFQUFFLEVBQUUsS0FBSyxDQUFDLENBQUM7UUFFeEIsTUFBTSxNQUFNLEdBQUcsSUFBSSxFQUFFLENBQUMsTUFBTSxDQUFDLElBQUksRUFBRSxZQUFZLEVBQUU7WUFDL0MsYUFBYSxFQUFFLEdBQUcsQ0FBQyxhQUFhLENBQUMsT0FBTztTQUN6QyxDQUFDLENBQUM7UUFFSCxNQUFNLEtBQUssR0FBRyxJQUFJLEdBQUcsQ0FBQyxLQUFLLENBQUMsSUFBSSxFQUFFLFdBQVcsRUFBRTtZQUM3QyxTQUFTLEVBQUUsc0JBQXNCO1lBQ2pDLGlCQUFpQixFQ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VwiOlwiYWRtaW5cIn0nLFxuICAgICAgICBnZW5lcmF0ZVN0cmluZ0tleTogJ3Bhc3N3b3JkJyxcbiAgICAgICAgcGFzc3dvcmRMZW5ndGg6IDI0LFxuICAgICAgICBleGNsdWRlQ2hhcmFjdGVyczogJ2FiYycsXG4gICAgICB9LFxuICAgIH0pO1xuICAgIGdlbmVyYXRlZFNlY3JldC5hcHBseVJlbW92YWxQb2xpY3koY2RrLlJlbW92YWxQb2xpY3kuREVTVFJPWSk7XG5cbiAgICBuZXcgY2RrLkNmbk91dHB1dCh0aGlzLCAnQnVja2V0TmFtZScsIHsgdmFsdWU6IGJ1Y2tldC5idWNrZXROYW1lIH0pO1xuICAgIG5ldyBjZGsuQ2ZuT3V0cHV0KHRoaXMsICdRdWV1ZVVybCcsIHsgdmFsdWU6IHF1ZXVlLnF1ZXVlVXJsIH0pO1xuICAgIG5ldyBjZGsuQ2ZuT3V0cHV0KHRoaXMsICdUYWJsZU5hbWUnLCB7IHZhbHVlOiB0YWJsZS50YWJsZU5hbWUgfSk7XG4gICAgbmV3IGNkay5DZm5PdXRwdXQodGhpcywgJ0luZGV4VGFibGVOYW1lJywgeyB2YWx1ZTogaW5kZXhUYWJsZS50YWJsZU5hbWUgfSk7XG4gICAgbmV3IGNkay5DZm5PdXRwdXQodGhpcywgJ0dlbmVyYXRlZFNlY3JldE5hbWUnLCB7IHZhbHVlOiBnZW5lcmF0ZWRTZWNyZXQubmFtZSB8fCAnZmxvY2ktY2RrLWdlbmVyYXRlZC1zZWNyZXQnIH0pO1xuICB9XG59XG4iXX0= \ No newline at end of file diff --git a/compatibility-tests/compat-cdk/run.sh b/compatibility-tests/compat-cdk/run.sh index 17b1847ee7..f7c7d7ea58 100755 --- a/compatibility-tests/compat-cdk/run.sh +++ b/compatibility-tests/compat-cdk/run.sh @@ -8,6 +8,7 @@ export AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-test}" export AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-test}" export FLOCI_ENDPOINT="${FLOCI_ENDPOINT:-http://localhost:4566}" export AWS_ENDPOINT_URL="$FLOCI_ENDPOINT" +export AWS_ENDPOINT_URL_S3="$FLOCI_ENDPOINT" # CDK-specific: derive hostname and port from endpoint export LOCALSTACK_HOSTNAME="${FLOCI_ENDPOINT#http://}" export LOCALSTACK_HOSTNAME="${LOCALSTACK_HOSTNAME%:*}" diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 7b114bbcc8..6e67d38f93 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -14,7 +14,7 @@ Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth to | **Resource Servers** | CreateResourceServer, DescribeResourceServer, ListResourceServers, DeleteResourceServer | | **Admin User Management** | AdminCreateUser, AdminGetUser, AdminDeleteUser, AdminSetUserPassword, AdminUpdateUserAttributes | | **User Operations** | SignUp, ConfirmSignUp, GetUser, UpdateUserAttributes, ChangePassword, ForgotPassword, ConfirmForgotPassword | -| **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge | +| **Authentication** | InitiateAuth, AdminInitiateAuth, RespondToAuthChallenge (supports USER_PASSWORD_AUTH, USER_SRP_AUTH, ADMIN_USER_SRP_AUTH) | | **User Listing** | ListUsers | | **Groups** | CreateGroup, GetGroup, ListGroups, DeleteGroup, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser | diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index a90c0259fd..e40dfe46b3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -28,6 +28,7 @@ import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @ApplicationScoped @@ -43,6 +44,13 @@ public class CognitoService { private final String baseUrl; private final RegionResolver regionResolver; + // Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock) + private final ConcurrentHashMap srpSessions = new ConcurrentHashMap<>(); + + private record SrpSession(String userPoolId, String username, String clientId, + String aHex, String bHex, String bPublicHex, + String secretBlockBase64) {} + @Inject public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig, RegionResolver regionResolver) { this.poolStore = storageFactory.create("cognito", "cognito-pools.json", @@ -280,7 +288,7 @@ public class CognitoService { } if (temporaryPassword != null && !temporaryPassword.isEmpty()) { - user.setPasswordHash(hashPassword(temporaryPassword)); + updateUserPassword(user, temporaryPassword); user.setTemporaryPassword(true); user.setUserStatus("FORCE_CHANGE_PASSWORD"); } @@ -323,7 +331,7 @@ public class CognitoService { public void adminSetUserPassword(String userPoolId, String username, String password, boolean permanent) { CognitoUser user = adminGetUser(userPoolId, username); - user.setPasswordHash(hashPassword(password)); + updateUserPassword(user, password); user.setTemporaryPassword(!permanent); user.setUserStatus(permanent ? "CONFIRMED" : "FORCE_CHANGE_PASSWORD"); user.setLastModifiedDate(System.currentTimeMillis() / 1000L); @@ -483,7 +491,7 @@ public class CognitoService { CognitoUser user = new CognitoUser(); user.setUsername(username); user.setUserPoolId(userPoolId); - user.setPasswordHash(hashPassword(password)); + updateUserPassword(user, password); user.setUserStatus("UNCONFIRMED"); if (attributes != null) { user.getAttributes().putAll(attributes); @@ -518,8 +526,9 @@ public class CognitoService { return switch (authFlow) { case "USER_PASSWORD_AUTH" -> authenticateWithPassword(pool, authParameters, clientId); case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters, clientId); + case "USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters); default -> { - // For other flows (USER_SRP_AUTH, etc.), if user exists return tokens + // For other flows, if user exists return tokens String username = authParameters.get("USERNAME"); if (username == null) { throw new AwsException("InvalidParameterException", "USERNAME is required", 400); @@ -534,13 +543,14 @@ public class CognitoService { public Map adminInitiateAuth(String userPoolId, String clientId, String authFlow, Map authParameters) { - describeUserPoolClient(userPoolId, clientId); + UserPoolClient client = describeUserPoolClient(userPoolId, clientId); UserPool pool = describeUserPool(userPoolId); return switch (authFlow) { case "ADMIN_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH" -> authenticateWithPassword(pool, authParameters, clientId); case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters, clientId); + case "ADMIN_USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters); default -> { String username = authParameters.get("USERNAME"); CognitoUser user = adminGetUser(userPoolId, username); @@ -551,12 +561,111 @@ public class CognitoService { }; } + private Map handleUserSrpAuth(UserPool pool, UserPoolClient client, Map authParameters) { + String username = authParameters.get("USERNAME"); + String aHex = authParameters.get("SRP_A"); + + if (username == null || aHex == null) { + throw new AwsException("InvalidParameterException", "USERNAME and SRP_A are required", 400); + } + + CognitoUser user = adminGetUser(pool.getId(), username); + if (user.getSrpVerifier() == null) { + throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); + } + + String[] serverB = CognitoSrpHelper.generateServerB(user.getSrpVerifier()); + String bHex = serverB[0]; + String bPublicHex = serverB[1]; + + String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId()); + + byte[] secretBlock = new byte[16]; + new java.security.SecureRandom().nextBytes(secretBlock); + String secretBlockBase64 = Base64.getEncoder().encodeToString(secretBlock); + + srpSessions.put(sessionToken, new SrpSession( + pool.getId(), + user.getUsername(), + client.getClientId(), + aHex, + bHex, + bPublicHex, + secretBlockBase64 + )); + + Map result = new HashMap<>(); + result.put("ChallengeName", "PASSWORD_VERIFIER"); + result.put("Session", sessionToken); + result.put("ChallengeParameters", Map.of( + "SALT", user.getSrpSalt(), + "SRP_B", bPublicHex, + "SECRET_BLOCK", secretBlockBase64, + "USER_ID_FOR_SRP", user.getUsername() + )); + return result; + } + + private Map handlePasswordVerifierChallenge(UserPool pool, UserPoolClient client, + String session, Map responses) { + SrpSession srp = srpSessions.get(session); + if (srp == null) { + throw new AwsException("NotAuthorizedException", "Session not found", 400); + } + + String username = responses.get("USERNAME"); + String claimSignature = responses.get("PASSWORD_CLAIM_SIGNATURE"); + String timestamp = responses.get("TIMESTAMP"); + + if (username == null || claimSignature == null || timestamp == null) { + throw new AwsException("InvalidParameterException", "USERNAME, PASSWORD_CLAIM_SIGNATURE and TIMESTAMP are required", 400); + } + + CognitoUser user = adminGetUser(pool.getId(), username); + if (user.getSrpVerifier() == null) { + throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400); + } + + byte[] sessionKey = CognitoSrpHelper.computeSessionKey(srp.aHex(), srp.bHex(), srp.bPublicHex(), user.getSrpVerifier()); + byte[] secretBlock = Base64.getDecoder().decode(srp.secretBlockBase64()); + + boolean valid = CognitoSrpHelper.verifySignature(sessionKey, pool.getId(), user.getUsername(), secretBlock, timestamp, claimSignature); + + if (!valid) { + throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); + } + + // Session consumed + srpSessions.remove(session); + + if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { + String newSession = buildSessionToken(pool.getId(), username, client.getClientId()); + Map result = new HashMap<>(); + result.put("ChallengeName", "NEW_PASSWORD_REQUIRED"); + result.put("Session", newSession); + result.put("ChallengeParameters", Map.of( + "USER_ID_FOR_SRP", username, + "requiredAttributes", "[]", + "userAttributes", "{}" + )); + return result; + } + + Map result = new HashMap<>(); + result.put("AuthenticationResult", generateAuthResult(user, pool, client.getClientId())); + return result; + } + public Map respondToAuthChallenge(String clientId, String challengeName, String session, Map responses) { UserPoolClient client = clientStore.get(clientId) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404)); UserPool pool = describeUserPool(client.getUserPoolId()); + if ("PASSWORD_VERIFIER".equals(challengeName)) { + return handlePasswordVerifierChallenge(pool, client, session, responses); + } + if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) { String username = responses.get("USERNAME"); String newPassword = responses.get("NEW_PASSWORD"); @@ -585,7 +694,7 @@ public class CognitoService { throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400); } - user.setPasswordHash(hashPassword(proposedPassword)); + updateUserPassword(user, proposedPassword); user.setTemporaryPassword(false); user.setUserStatus("CONFIRMED"); user.setLastModifiedDate(System.currentTimeMillis() / 1000L); @@ -1067,6 +1176,19 @@ public class CognitoService { } } + private void updateUserPassword(CognitoUser user, String password) { + String saltHex = CognitoSrpHelper.generateSalt(); + String verifierHex = CognitoSrpHelper.computeVerifier( + CognitoSrpHelper.extractPoolName(user.getUserPoolId()), + user.getUsername(), + password, + saltHex + ); + user.setPasswordHash(hashPassword(password)); + user.setSrpSalt(saltHex); + user.setSrpVerifier(verifierHex); + } + private String buildSessionToken(String poolId, String username, String clientId) { String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID(); return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java new file mode 100644 index 0000000000..ad1fe5e7e3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoSrpHelper.java @@ -0,0 +1,308 @@ +package io.github.hectorvent.floci.services.cognito; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; + +/** + * Server-side SRP-6a helpers for AWS Cognito USER_SRP_AUTH flow. + * + *

Implements the "Caldera" variant used by Cognito: + *

    + *
  • 3072-bit prime N from RFC 5054
  • + *
  • g = 2
  • + *
  • k = SHA-256(N || pad(g))
  • + *
  • x = SHA-256(salt || SHA-256(poolName + username + ":" + password))
  • + *
  • Session key derived with HKDF using info = "Caldera Derived Key"
  • + *
+ */ +final class CognitoSrpHelper { + + // RFC 5054 3072-bit prime + static final String N_HEX = + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43" + + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" + + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43"; + + // Caldera uses the same prime — exact hex from AWS Cognito SDK references + private static final String PRIME_HEX = + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; + + static final BigInteger N = new BigInteger(PRIME_HEX, 16); + static final BigInteger G = BigInteger.valueOf(2); + + // k = SHA-256(N || pad(g)) — Caldera convention + static final BigInteger K; + + private static final int N_BYTES = (N.bitLength() + 7) / 8; // 384 for 3072-bit + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final byte[] INFO_BITS = "Caldera Derived Key".getBytes(StandardCharsets.UTF_8); + + static { + try { + byte[] nBytes = padTo(N.toByteArray(), N_BYTES); + byte[] gBytes = padTo(G.toByteArray(), N_BYTES); + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + sha256.update(nBytes); + sha256.update(gBytes); + K = new BigInteger(1, sha256.digest()); + } catch (Exception e) { + throw new ExceptionInInitializerError(e); + } + } + + private CognitoSrpHelper() {} + + // ──────────────────────────── Password verifier ──────────────────────────── + + /** + * Generates a 16-byte random salt (hex-encoded). + */ + static String generateSalt() { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + return HexFormat.of().formatHex(salt); + } + + /** + * Computes the SRP password verifier v = g^x mod N. + * + * @param poolName the portion of the user pool ID after the underscore (e.g. "ABC123456") + * @param username the Cognito username + * @param password the plaintext password + * @param saltHex hex-encoded salt + * @return the verifier as a hex string + */ + static String computeVerifier(String poolName, String username, String password, String saltHex) { + BigInteger x = computeX(poolName, username, password, saltHex); + BigInteger v = G.modPow(x, N); + return v.toString(16); + } + + // ──────────────────────────── Server B ──────────────────────────── + + /** + * Generates server's ephemeral private b and public B. + * + * @param verifierHex the stored SRP verifier (hex) + * @return array of {bPrivate (hex), B (hex)} + */ + static String[] generateServerB(String verifierHex) { + BigInteger v = new BigInteger(verifierHex, 16); + BigInteger b; + BigInteger B; + do { + b = new BigInteger(256, RANDOM); + BigInteger gB = G.modPow(b, N); + B = K.multiply(v).add(gB).mod(N); + } while (B.mod(N).equals(BigInteger.ZERO)); + return new String[]{b.toString(16), B.toString(16)}; + } + + // ──────────────────────────── Server session key ──────────────────────────── + + /** + * Computes the server-side session key from SRP parameters. + * + * @param aHex client's public A (hex) + * @param bHex server's private b (hex) + * @param bPublicHex server's public B (hex) + * @param verifierHex stored verifier (hex) + * @return session key bytes (32 bytes) + */ + static byte[] computeSessionKey(String aHex, String bHex, String bPublicHex, String verifierHex) { + BigInteger A = new BigInteger(aHex, 16); + BigInteger b = new BigInteger(bHex, 16); + BigInteger B = new BigInteger(bPublicHex, 16); + BigInteger v = new BigInteger(verifierHex, 16); + + BigInteger u = computeU(A, B); + // S = (A * v^u)^b mod N + BigInteger base = A.multiply(v.modPow(u, N)).mod(N); + BigInteger S = base.modPow(b, N); + + // Derive key using Caldera interleaved hash + return deriveCalderaKey(S); + } + + // ──────────────────────────── HMAC signature ──────────────────────────── + + /** + * Computes the expected PASSWORD_CLAIM_SIGNATURE. + * + * @param sessionKey derived session key bytes + * @param userPoolId full user pool ID (e.g., "us-east-1_ABC123") + * @param username Cognito username + * @param secretBlock raw bytes of the SECRET_BLOCK + * @param timestamp formatted timestamp string sent by the client + */ + static byte[] computeSignature(byte[] sessionKey, String userPoolId, String username, + byte[] secretBlock, String timestamp) { + try { + byte[] hkdfKey = hkdf(sessionKey, INFO_BITS); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(hkdfKey, "HmacSHA256")); + mac.update(userPoolId.getBytes(StandardCharsets.UTF_8)); + mac.update(username.getBytes(StandardCharsets.UTF_8)); + mac.update(secretBlock); + mac.update(timestamp.getBytes(StandardCharsets.UTF_8)); + return mac.doFinal(); + } catch (Exception e) { + throw new RuntimeException("SRP signature computation failed", e); + } + } + + /** + * Verifies the client's PASSWORD_CLAIM_SIGNATURE. + */ + static boolean verifySignature(byte[] sessionKey, String userPoolId, String username, + byte[] secretBlock, String timestamp, String claimSignatureBase64) { + byte[] expected = computeSignature(sessionKey, userPoolId, username, secretBlock, timestamp); + byte[] claimed; + try { + claimed = Base64.getDecoder().decode(claimSignatureBase64); + } catch (Exception e) { + return false; + } + return MessageDigest.isEqual(expected, claimed); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + /** + * Extracts the pool name (part after the underscore) from the full pool ID. + * e.g., "us-east-1_ABC123" → "ABC123" + */ + static String extractPoolName(String userPoolId) { + int idx = userPoolId.indexOf('_'); + return idx >= 0 ? userPoolId.substring(idx + 1) : userPoolId; + } + + // ──────────────────────────── Private ──────────────────────────── + + private static BigInteger computeX(String poolName, String username, String password, String saltHex) { + try { + // inner = SHA-256(poolName + username + ":" + password) + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + sha256.update(poolName.getBytes(StandardCharsets.UTF_8)); + sha256.update(username.getBytes(StandardCharsets.UTF_8)); + sha256.update(":".getBytes(StandardCharsets.UTF_8)); + sha256.update(password.getBytes(StandardCharsets.UTF_8)); + byte[] innerHash = sha256.digest(); + + // x = SHA-256(pad(salt) || innerHash) + byte[] saltBytes = HexFormat.of().parseHex(saltHex); + sha256.reset(); + sha256.update(saltBytes); + sha256.update(innerHash); + return new BigInteger(1, sha256.digest()); + } catch (Exception e) { + throw new RuntimeException("SRP x computation failed", e); + } + } + + private static BigInteger computeU(BigInteger A, BigInteger B) { + try { + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + sha256.update(padTo(A.toByteArray(), N_BYTES)); + sha256.update(padTo(B.toByteArray(), N_BYTES)); + return new BigInteger(1, sha256.digest()); + } catch (Exception e) { + throw new RuntimeException("SRP u computation failed", e); + } + } + + /** + * Caldera interleaved hash to derive session key from S. + * SHA-256 is applied to even-indexed and odd-indexed bytes of S separately, + * then interleaved. + */ + private static byte[] deriveCalderaKey(BigInteger S) { + try { + byte[] sBytes = padTo(S.toByteArray(), N_BYTES); + + // Split into even/odd positions + byte[] even = new byte[N_BYTES / 2]; + byte[] odd = new byte[N_BYTES / 2]; + for (int i = 0; i < N_BYTES / 2; i++) { + even[i] = sBytes[i * 2]; + odd[i] = sBytes[i * 2 + 1]; + } + + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + byte[] hashEven = sha256.digest(even); + sha256.reset(); + byte[] hashOdd = sha256.digest(odd); + + // Interleave the two hashes + byte[] result = new byte[64]; + for (int i = 0; i < 32; i++) { + result[i * 2] = hashEven[i]; + result[i * 2 + 1] = hashOdd[i]; + } + return result; + } catch (Exception e) { + throw new RuntimeException("Caldera key derivation failed", e); + } + } + + /** + * HKDF extract-and-expand using SHA-256 (salt = zeroes, no extract step). + * Compatible with Cognito's "Caldera Derived Key" derivation. + */ + private static byte[] hkdf(byte[] ikm, byte[] info) throws Exception { + // Extract: PRK = HMAC-SHA256(salt=zeroes_32, IKM) + byte[] salt = new byte[32]; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(salt, "HmacSHA256")); + byte[] prk = mac.doFinal(ikm); + + // Expand: T(1) = HMAC-SHA256(PRK, info || 0x01) + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + mac.update(info); + mac.update((byte) 1); + byte[] t1 = mac.doFinal(); + return Arrays.copyOf(t1, 32); + } + + /** + * Left-pads a byte array to the given length. + * If the array has a leading 0x00 sign byte, it is stripped before padding. + */ + static byte[] padTo(byte[] bytes, int length) { + // Strip sign byte if present + if (bytes.length > length && bytes[0] == 0) { + bytes = Arrays.copyOfRange(bytes, 1, bytes.length); + } + if (bytes.length == length) { + return bytes; + } + byte[] padded = new byte[length]; + int offset = length - bytes.length; + System.arraycopy(bytes, 0, padded, offset, bytes.length); + return padded; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java index 3506dc2385..7894d9d15d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java @@ -21,6 +21,8 @@ public class CognitoUser { private String passwordHash; private boolean temporaryPassword; private List groupNames = new ArrayList<>(); + private String srpSalt; + private String srpVerifier; public CognitoUser() { long now = System.currentTimeMillis() / 1000L; @@ -59,4 +61,10 @@ public class CognitoUser { public List getGroupNames() { return groupNames; } public void setGroupNames(List groupNames) { this.groupNames = groupNames == null ? new ArrayList<>() : new ArrayList<>(groupNames); } + + public String getSrpSalt() { return srpSalt; } + public void setSrpSalt(String srpSalt) { this.srpSalt = srpSalt; } + + public String getSrpVerifier() { return srpVerifier; } + public void setSrpVerifier(String srpVerifier) { this.srpVerifier = srpVerifier; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index da4a6c9d6c..6b08d3a1da 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -449,6 +449,53 @@ class CognitoServiceTest { assertEquals("NEW_PASSWORD_REQUIRED", result.get("ChallengeName")); } + // ========================================================================= + // USER_SRP_AUTH flow + // ========================================================================= + + @Test + @SuppressWarnings("unchecked") + void initiateAuthWithUserSrpAuthFlow() { + UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1"); + String password = "Password123!"; + service.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null); + service.adminSetUserPassword(pool.getId(), "bob", password, true); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of()); + + Map initResult = service.initiateAuth(client.getClientId(), "USER_SRP_AUTH", + Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890")); + + assertEquals("PASSWORD_VERIFIER", initResult.get("ChallengeName")); + assertNotNull(initResult.get("Session")); + Map params = (Map) initResult.get("ChallengeParameters"); + assertNotNull(params.get("SALT")); + assertNotNull(params.get("SRP_B")); + assertNotNull(params.get("SECRET_BLOCK")); + assertEquals("bob", params.get("USER_ID_FOR_SRP")); + } + + @Test + void respondToAuthChallengeWithInvalidSrpSignatureRejects() { + UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1"); + String password = "Password123!"; + service.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null); + service.adminSetUserPassword(pool.getId(), "bob", password, true); + UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of()); + + Map initResult = service.initiateAuth(client.getClientId(), "USER_SRP_AUTH", + Map.of("USERNAME", "bob", "SRP_A", "ABCDEF1234567890")); + String session = (String) initResult.get("Session"); + + AwsException ex = assertThrows(AwsException.class, () -> + service.respondToAuthChallenge(client.getClientId(), "PASSWORD_VERIFIER", session, + Map.of( + "USERNAME", "bob", + "PASSWORD_CLAIM_SIGNATURE", "invalid-sig", + "TIMESTAMP", "Wed Apr 8 12:00:00 UTC 2026" + ))); + assertEquals("NotAuthorizedException", ex.getErrorCode()); + } + // ========================================================================= // Issue #228 — AccessToken contains client_id claim // =========================================================================