mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
feat(cognito): support passkeys (WebAuthn) registration and sign-in (#5102)
* feat(cognito): register passkeys and sign in with WEB_AUTHN * test(cognito): cover passkeys with the Java SDK * docs(cognito): document passkey registration and sign-in * fix(cognito): check passkey counters under the user lock and tighten passkey origins * fix(cognito): turn passkey MFA on per user and page passkeys with a cursor * fix(cognito): verify passkeys without webauthn4j and gate passkey MFA on tier Drops the webauthn4j dependency and its native-image entries. Cognito recognizes only ES256 and RS256 passkeys and does not enforce attestation, so jackson-dataformat-cbor decodes the attestation object, the authenticator data and the COSE key, and java.security checks the signature. The attestation statement is no longer verified. The helpers the verifier needs live in core.common, and the existing copies across main and test code now call them: - PublicKeys builds a public key from its raw components, for the JWT verifiers of API Gateway and Verified Permissions, SshPublicKeys, and the CloudFront and SES curve lookups. - Digests.sha256 and Digests.sha256Hex replace every one-shot SHA-256 digest and the private hex helpers built on one, including the two public sha256Hex methods on SigV4RequestValidator; incremental and streaming digests keep MessageDigest. - Base64Url.encode, for bytes or the UTF-8 bytes of a string, replaces every unpadded base64url encode and the private helpers wrapping it. - DomainNames.isWithin replaces the same-domain-or-subdomain check in SES, ACM, Route 53, the embedded DNS server, the TLS certificate manager and the Cognito message dispatcher. Every replacement produces the same bytes as the code it replaces. Turning passkey MFA on now also needs a pool in the Essentials tier or higher, and in an optional-MFA pool a user with software-token MFA keeps WEB_AUTHN when passkey MFA is on, as the AWS MFA table describes. --------- Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
1 parent
162ac6dea7
commit
5092713a6e
149 files changed
+3494
-919
No files matched your search
+265
@@ -0,0 +1,265 @@
|
||||
package com.floci.test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.document.Document;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.GetUserPoolMfaConfigResponse;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAuthResponse;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidParameterException;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListWebAuthnCredentialsResponse;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.RespondToAuthChallengeResponse;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolMfaType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.UserVerificationType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnCredentialDescription;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnFactorConfigurationType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.WebAuthnNotEnabledException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class CognitoWebAuthnTest {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String USERNAME = "passkey-sdk-user";
|
||||
private static final String PASSWORD = "SdkPasskey123!";
|
||||
|
||||
@Test
|
||||
@DisplayName("passkey registration and WEB_AUTHN sign-in through the SDK's document members")
|
||||
void sdkRegistersAPasskeyAndSignsInWithIt() throws Exception {
|
||||
try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
|
||||
String poolId = cognito.createUserPool(b -> b.poolName("passkey-sdk-" + UUID.randomUUID())
|
||||
.policies(p -> p.signInPolicy(s -> s.allowedFirstAuthFactorsWithStrings("PASSWORD", "WEB_AUTHN"))))
|
||||
.userPool().id();
|
||||
try {
|
||||
cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.OFF)
|
||||
.webAuthnConfiguration(w -> w.relyingPartyId("localhost")
|
||||
.userVerification(UserVerificationType.PREFERRED)));
|
||||
GetUserPoolMfaConfigResponse mfaConfig = cognito.getUserPoolMfaConfig(b -> b.userPoolId(poolId));
|
||||
assertThat(mfaConfig.webAuthnConfiguration().relyingPartyId()).isEqualTo("localhost");
|
||||
String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
|
||||
.clientName("passkey-sdk-client")
|
||||
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH,
|
||||
ExplicitAuthFlowsType.ALLOW_USER_AUTH))
|
||||
.userPoolClient().clientId();
|
||||
cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.messageAction(MessageActionType.SUPPRESS));
|
||||
cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.password(PASSWORD).permanent(true));
|
||||
String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
|
||||
.authenticationResult().accessToken();
|
||||
|
||||
Document options = cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
|
||||
.credentialCreationOptions();
|
||||
JsonNode creationOptions = toJson(options);
|
||||
assertThat(creationOptions.path("rp").path("id").asText()).isEqualTo("localhost");
|
||||
|
||||
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
|
||||
Document credential = toDocument(authenticator.register(creationOptions, "packed"));
|
||||
cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(credential));
|
||||
|
||||
ListWebAuthnCredentialsResponse listed = cognito.listWebAuthnCredentials(b -> b.accessToken(accessToken));
|
||||
assertThat(listed.credentials()).hasSize(1);
|
||||
WebAuthnCredentialDescription description = listed.credentials().get(0);
|
||||
assertThat(description.credentialId()).isEqualTo(authenticator.credentialId());
|
||||
assertThat(description.relyingPartyId()).isEqualTo("localhost");
|
||||
assertThat(description.createdAt()).isNotNull();
|
||||
|
||||
InitiateAuthResponse challenge = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
|
||||
assertThat(challenge.challengeName()).isEqualTo(ChallengeNameType.WEB_AUTHN);
|
||||
String assertion = authenticator.authenticate(
|
||||
challenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS"));
|
||||
RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b.clientId(clientId)
|
||||
.challengeName(ChallengeNameType.WEB_AUTHN)
|
||||
.session(challenge.session())
|
||||
.challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", assertion)));
|
||||
assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
|
||||
|
||||
WebAuthnTestAuthenticator rsa = WebAuthnTestAuthenticator.rs256("http://localhost:5173");
|
||||
JsonNode rsaOptions = toJson(cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
|
||||
.credentialCreationOptions());
|
||||
Document rsaCredential = toDocument(rsa.register(rsaOptions, "none"));
|
||||
cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(rsaCredential));
|
||||
InitiateAuthResponse rsaChallenge = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
|
||||
String rsaAssertion = rsa.authenticate(
|
||||
rsaChallenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS"));
|
||||
assertThat(cognito.respondToAuthChallenge(b -> b.clientId(clientId)
|
||||
.challengeName(ChallengeNameType.WEB_AUTHN)
|
||||
.session(rsaChallenge.session())
|
||||
.challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", rsaAssertion)))
|
||||
.authenticationResult().accessToken()).isNotBlank();
|
||||
|
||||
cognito.deleteWebAuthnCredential(b -> b.accessToken(accessToken)
|
||||
.credentialId(authenticator.credentialId()));
|
||||
cognito.deleteWebAuthnCredential(b -> b.accessToken(accessToken)
|
||||
.credentialId(rsa.credentialId()));
|
||||
assertThat(cognito.listWebAuthnCredentials(b -> b.accessToken(accessToken)).credentials()).isEmpty();
|
||||
} finally {
|
||||
cognito.deleteUserPool(b -> b.userPoolId(poolId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a passkey stands in for required MFA only for a user who turned WebAuthnMfaSettings on")
|
||||
void sdkTurnsPasskeyMfaOnPerUser() throws Exception {
|
||||
try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
|
||||
String poolId = cognito.createUserPool(b -> b.poolName("passkey-mfa-sdk-" + UUID.randomUUID())
|
||||
.policies(p -> p.signInPolicy(s -> s.allowedFirstAuthFactorsWithStrings("PASSWORD", "WEB_AUTHN"))))
|
||||
.userPool().id();
|
||||
try {
|
||||
cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.OFF)
|
||||
.webAuthnConfiguration(w -> w.relyingPartyId("localhost")));
|
||||
String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
|
||||
.clientName("passkey-mfa-sdk-client")
|
||||
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH,
|
||||
ExplicitAuthFlowsType.ALLOW_USER_AUTH))
|
||||
.userPoolClient().clientId();
|
||||
cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.messageAction(MessageActionType.SUPPRESS));
|
||||
cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.password(PASSWORD).permanent(true));
|
||||
String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
|
||||
.authenticationResult().accessToken();
|
||||
WebAuthnTestAuthenticator authenticator = WebAuthnTestAuthenticator.es256("http://localhost:5173");
|
||||
JsonNode creationOptions = toJson(cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken))
|
||||
.credentialCreationOptions());
|
||||
Document credential = toDocument(authenticator.register(creationOptions, "none"));
|
||||
cognito.completeWebAuthnRegistration(b -> b.accessToken(accessToken).credential(credential));
|
||||
|
||||
assertThatThrownBy(() -> cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
|
||||
.webAuthnMfaSettings(w -> w.enabled(true))))
|
||||
.isInstanceOf(InvalidParameterException.class);
|
||||
|
||||
cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId).mfaConfiguration(UserPoolMfaType.ON)
|
||||
.softwareTokenMfaConfiguration(t -> t.enabled(true))
|
||||
.webAuthnConfiguration(w -> w.relyingPartyId("localhost")
|
||||
.factorConfiguration(WebAuthnFactorConfigurationType.MULTI_FACTOR_WITH_USER_VERIFICATION)));
|
||||
InitiateAuthResponse withoutOptIn = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME)));
|
||||
assertThat(withoutOptIn.challengeName()).isEqualTo(ChallengeNameType.SELECT_CHALLENGE);
|
||||
assertThat(withoutOptIn.availableChallengesAsStrings()).containsExactly("PASSWORD", "PASSWORD_SRP");
|
||||
|
||||
cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
|
||||
.webAuthnMfaSettings(w -> w.enabled(true)));
|
||||
InitiateAuthResponse challenge = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PREFERRED_CHALLENGE", "WEB_AUTHN")));
|
||||
assertThat(challenge.challengeName()).isEqualTo(ChallengeNameType.WEB_AUTHN);
|
||||
String requestOptions = challenge.challengeParameters().get("CREDENTIAL_REQUEST_OPTIONS");
|
||||
assertThat(JSON.readTree(requestOptions).path("userVerification").asText()).isEqualTo("required");
|
||||
String assertion = authenticator.authenticate(requestOptions);
|
||||
RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b.clientId(clientId)
|
||||
.challengeName(ChallengeNameType.WEB_AUTHN)
|
||||
.session(challenge.session())
|
||||
.challengeResponses(Map.of("USERNAME", USERNAME, "CREDENTIAL", assertion)));
|
||||
assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
|
||||
|
||||
cognito.adminSetUserMFAPreference(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.webAuthnMfaSettings(w -> w.enabled(false)));
|
||||
assertThat(cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME))).availableChallengesAsStrings())
|
||||
.containsExactly("PASSWORD", "PASSWORD_SRP");
|
||||
} finally {
|
||||
cognito.deleteUserPool(b -> b.userPoolId(poolId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("StartWebAuthnRegistration is refused when the pool does not allow WEB_AUTHN")
|
||||
void sdkSeesWebAuthnNotEnabled() {
|
||||
try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
|
||||
String poolId = cognito.createUserPool(b -> b.poolName("no-passkey-sdk-" + UUID.randomUUID()))
|
||||
.userPool().id();
|
||||
try {
|
||||
String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
|
||||
.clientName("no-passkey-sdk-client")
|
||||
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
|
||||
.userPoolClient().clientId();
|
||||
cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.messageAction(MessageActionType.SUPPRESS));
|
||||
cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
|
||||
.password(PASSWORD).permanent(true));
|
||||
String accessToken = cognito.initiateAuth(b -> b.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
|
||||
.authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)))
|
||||
.authenticationResult().accessToken();
|
||||
|
||||
assertThatThrownBy(() -> cognito.startWebAuthnRegistration(b -> b.accessToken(accessToken)))
|
||||
.isInstanceOf(WebAuthnNotEnabledException.class);
|
||||
} finally {
|
||||
cognito.deleteUserPool(b -> b.userPoolId(poolId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode toJson(Document document) {
|
||||
if (document.isMap()) {
|
||||
ObjectNode node = JSON.createObjectNode();
|
||||
document.asMap().forEach((key, value) -> node.set(key, toJson(value)));
|
||||
return node;
|
||||
}
|
||||
if (document.isList()) {
|
||||
ArrayNode node = JSON.createArrayNode();
|
||||
document.asList().forEach(value -> node.add(toJson(value)));
|
||||
return node;
|
||||
}
|
||||
if (document.isString()) {
|
||||
return JSON.getNodeFactory().textNode(document.asString());
|
||||
}
|
||||
if (document.isNumber()) {
|
||||
return JSON.getNodeFactory().numberNode(document.asNumber().bigDecimalValue());
|
||||
}
|
||||
if (document.isBoolean()) {
|
||||
return JSON.getNodeFactory().booleanNode(document.asBoolean());
|
||||
}
|
||||
return JSON.getNodeFactory().nullNode();
|
||||
}
|
||||
|
||||
private static Document toDocument(JsonNode node) {
|
||||
if (node.isObject()) {
|
||||
Map<String, Document> members = new LinkedHashMap<>();
|
||||
node.fields().forEachRemaining(entry -> members.put(entry.getKey(), toDocument(entry.getValue())));
|
||||
return Document.fromMap(members);
|
||||
}
|
||||
if (node.isArray()) {
|
||||
List<Document> items = new ArrayList<>();
|
||||
node.forEach(item -> items.add(toDocument(item)));
|
||||
return Document.fromList(items);
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
return Document.fromBoolean(node.asBoolean());
|
||||
}
|
||||
if (node.isNumber()) {
|
||||
return Document.fromNumber(node.decimalValue());
|
||||
}
|
||||
if (node.isNull()) {
|
||||
return Document.fromNull();
|
||||
}
|
||||
return Document.fromString(node.asText());
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package com.floci.test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Signature;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A software passkey authenticator for tests, standing in for a browser and its authenticator:
|
||||
* it answers creation options with a {@code RegistrationResponseJSON} ({@code none} or
|
||||
* {@code packed} self attestation) and request options with an {@code AuthenticationResponseJSON}.
|
||||
*/
|
||||
final class WebAuthnTestAuthenticator {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final byte FLAG_UP = 0x01;
|
||||
private static final byte FLAG_UV = 0x04;
|
||||
private static final byte FLAG_AT = 0x40;
|
||||
|
||||
private final String origin;
|
||||
private final KeyPair keyPair;
|
||||
private final long algorithm;
|
||||
private final String signatureAlgorithm;
|
||||
private final byte[] credentialId = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
|
||||
private String relyingPartyIdOverride;
|
||||
private boolean userVerified = true;
|
||||
private boolean corruptAttestation;
|
||||
private long signCount;
|
||||
|
||||
private WebAuthnTestAuthenticator(String origin, KeyPair keyPair, long algorithm, String signatureAlgorithm) {
|
||||
this.origin = origin;
|
||||
this.keyPair = keyPair;
|
||||
this.algorithm = algorithm;
|
||||
this.signatureAlgorithm = signatureAlgorithm;
|
||||
}
|
||||
|
||||
static WebAuthnTestAuthenticator es256(String origin) throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
|
||||
generator.initialize(new ECGenParameterSpec("secp256r1"));
|
||||
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -7, "SHA256withECDSA");
|
||||
}
|
||||
|
||||
static WebAuthnTestAuthenticator es384(String origin) throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
|
||||
generator.initialize(new ECGenParameterSpec("secp384r1"));
|
||||
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -35, "SHA384withECDSA");
|
||||
}
|
||||
|
||||
static WebAuthnTestAuthenticator rs256(String origin) throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(2048);
|
||||
return new WebAuthnTestAuthenticator(origin, generator.generateKeyPair(), -257, "SHA256withRSA");
|
||||
}
|
||||
|
||||
/** Claims {@code relyingPartyId} instead of the one the options name. */
|
||||
WebAuthnTestAuthenticator relyingPartyId(String relyingPartyId) {
|
||||
this.relyingPartyIdOverride = relyingPartyId;
|
||||
return this;
|
||||
}
|
||||
|
||||
WebAuthnTestAuthenticator userVerified(boolean userVerified) {
|
||||
this.userVerified = userVerified;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Signs a {@code packed} attestation statement over the wrong data. */
|
||||
WebAuthnTestAuthenticator corruptAttestation() {
|
||||
this.corruptAttestation = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
String credentialId() {
|
||||
return base64Url(credentialId);
|
||||
}
|
||||
|
||||
ObjectNode register(JsonNode creationOptions, String format) throws Exception {
|
||||
String relyingPartyId = relyingPartyIdOverride != null
|
||||
? relyingPartyIdOverride : creationOptions.path("rp").path("id").asText();
|
||||
byte[] clientData = clientData("webauthn.create", creationOptions.path("challenge").asText());
|
||||
ByteArrayOutputStream authData = new ByteArrayOutputStream();
|
||||
authData.write(sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)));
|
||||
authData.write(FLAG_UP | FLAG_AT | (userVerified ? FLAG_UV : 0));
|
||||
authData.write(ByteBuffer.allocate(4).putInt((int) signCount).array());
|
||||
authData.write(new byte[16]);
|
||||
authData.write(ByteBuffer.allocate(2).putShort((short) credentialId.length).array());
|
||||
authData.write(credentialId);
|
||||
authData.write(coseKey());
|
||||
byte[] authenticatorData = authData.toByteArray();
|
||||
|
||||
Cbor statement = new Cbor();
|
||||
if ("packed".equals(format)) {
|
||||
byte[] signed = concat(authenticatorData, sha256(clientData));
|
||||
if (corruptAttestation) {
|
||||
signed[0] ^= 0x01;
|
||||
}
|
||||
statement.map(2).text("alg").integer(algorithm).text("sig").bytes(sign(signed));
|
||||
} else {
|
||||
statement.map(0);
|
||||
}
|
||||
byte[] attestationObject = new Cbor().map(3)
|
||||
.text("fmt").text(format)
|
||||
.text("attStmt").raw(statement.toByteArray())
|
||||
.text("authData").bytes(authenticatorData)
|
||||
.toByteArray();
|
||||
|
||||
ObjectNode credential = JSON.createObjectNode();
|
||||
credential.put("id", credentialId());
|
||||
credential.put("rawId", credentialId());
|
||||
credential.put("type", "public-key");
|
||||
credential.put("authenticatorAttachment", "platform");
|
||||
credential.putObject("clientExtensionResults");
|
||||
ObjectNode response = credential.putObject("response");
|
||||
response.put("clientDataJSON", base64Url(clientData));
|
||||
response.put("attestationObject", base64Url(attestationObject));
|
||||
response.putArray("transports").add("internal").add("hybrid");
|
||||
return credential;
|
||||
}
|
||||
|
||||
String authenticate(String requestOptionsJson) throws Exception {
|
||||
JsonNode options = JSON.readTree(requestOptionsJson);
|
||||
String relyingPartyId = relyingPartyIdOverride != null ? relyingPartyIdOverride : options.path("rpId").asText();
|
||||
byte[] clientData = clientData("webauthn.get", options.path("challenge").asText());
|
||||
signCount++;
|
||||
byte[] authenticatorData = concat(sha256(relyingPartyId.getBytes(StandardCharsets.UTF_8)),
|
||||
new byte[] {(byte) (FLAG_UP | (userVerified ? FLAG_UV : 0))},
|
||||
ByteBuffer.allocate(4).putInt((int) signCount).array());
|
||||
|
||||
ObjectNode credential = JSON.createObjectNode();
|
||||
credential.put("id", credentialId());
|
||||
credential.put("rawId", credentialId());
|
||||
credential.put("type", "public-key");
|
||||
credential.put("authenticatorAttachment", "platform");
|
||||
credential.putObject("clientExtensionResults");
|
||||
ObjectNode response = credential.putObject("response");
|
||||
response.put("authenticatorData", base64Url(authenticatorData));
|
||||
response.put("clientDataJSON", base64Url(clientData));
|
||||
response.put("signature", base64Url(sign(concat(authenticatorData, sha256(clientData)))));
|
||||
return JSON.writeValueAsString(credential);
|
||||
}
|
||||
|
||||
private byte[] clientData(String type, String challenge) throws Exception {
|
||||
ObjectNode clientData = JSON.createObjectNode();
|
||||
clientData.put("type", type);
|
||||
clientData.put("challenge", challenge);
|
||||
clientData.put("origin", origin);
|
||||
clientData.put("crossOrigin", false);
|
||||
return JSON.writeValueAsBytes(clientData);
|
||||
}
|
||||
|
||||
private byte[] coseKey() {
|
||||
if (keyPair.getPublic() instanceof RSAPublicKey rsa) {
|
||||
return new Cbor().map(4)
|
||||
.integer(1).integer(3)
|
||||
.integer(3).integer(algorithm)
|
||||
.integer(-1).bytes(unsigned(rsa.getModulus()))
|
||||
.integer(-2).bytes(unsigned(rsa.getPublicExponent()))
|
||||
.toByteArray();
|
||||
}
|
||||
ECPublicKey ec = (ECPublicKey) keyPair.getPublic();
|
||||
int size = algorithm == -35 ? 48 : 32;
|
||||
return new Cbor().map(5)
|
||||
.integer(1).integer(2)
|
||||
.integer(3).integer(algorithm)
|
||||
.integer(-1).integer(algorithm == -35 ? 2 : 1)
|
||||
.integer(-2).bytes(fixed(ec.getW().getAffineX(), size))
|
||||
.integer(-3).bytes(fixed(ec.getW().getAffineY(), size))
|
||||
.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] sign(byte[] data) throws Exception {
|
||||
Signature signature = Signature.getInstance(signatureAlgorithm);
|
||||
signature.initSign(keyPair.getPrivate());
|
||||
signature.update(data);
|
||||
return signature.sign();
|
||||
}
|
||||
|
||||
private static byte[] sha256(byte[] data) throws Exception {
|
||||
return MessageDigest.getInstance("SHA-256").digest(data);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (byte[] part : parts) {
|
||||
out.writeBytes(part);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] unsigned(BigInteger value) {
|
||||
byte[] bytes = value.toByteArray();
|
||||
return bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes;
|
||||
}
|
||||
|
||||
private static byte[] fixed(BigInteger value, int size) {
|
||||
byte[] bytes = unsigned(value);
|
||||
byte[] padded = new byte[size];
|
||||
System.arraycopy(bytes, 0, padded, size - bytes.length, bytes.length);
|
||||
return padded;
|
||||
}
|
||||
|
||||
static String base64Url(byte[] bytes) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
/** The few CBOR items an attestation object and a COSE key need. */
|
||||
private static final class Cbor {
|
||||
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
|
||||
Cbor map(int entries) {
|
||||
head(5, entries);
|
||||
return this;
|
||||
}
|
||||
|
||||
Cbor text(String value) {
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
head(3, bytes.length);
|
||||
out.writeBytes(bytes);
|
||||
return this;
|
||||
}
|
||||
|
||||
Cbor bytes(byte[] value) {
|
||||
head(2, value.length);
|
||||
out.writeBytes(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
Cbor integer(long value) {
|
||||
if (value >= 0) {
|
||||
head(0, value);
|
||||
} else {
|
||||
head(1, -1 - value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
Cbor raw(byte[] encoded) {
|
||||
out.writeBytes(encoded);
|
||||
return this;
|
||||
}
|
||||
|
||||
byte[] toByteArray() {
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private void head(int majorType, long value) {
|
||||
int major = majorType << 5;
|
||||
if (value < 24) {
|
||||
out.write(major | (int) value);
|
||||
} else if (value < 0x100) {
|
||||
out.write(major | 24);
|
||||
out.write((int) value);
|
||||
} else if (value < 0x10000) {
|
||||
out.write(major | 25);
|
||||
out.writeBytes(ByteBuffer.allocate(2).putShort((short) value).array());
|
||||
} else {
|
||||
out.write(major | 26);
|
||||
out.writeBytes(ByteBuffer.allocate(4).putInt((int) value).array());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user