Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,15 @@

import static org.keycloak.WebAuthnConstants.AUTH_ERR_DETAIL_LABEL;
import static org.keycloak.WebAuthnConstants.AUTH_ERR_LABEL;
import static org.keycloak.authentication.requiredactions.WebAuthnRegister.mapBrowserApiErrorToMessageKey;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_GET;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_INVALID_STATE;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_NOT_ALLOWED;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_SECURITY;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_AUTH_VERIFICATION;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_DIFFERENT_USER;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTRATION;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_UNSUPPORTED_BROWSER;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_USER_NOT_FOUND;

/**
Expand Down Expand Up @@ -155,7 +160,8 @@ public void action(AuthenticationFlowContext context) {
// receive error from navigator.credentials.get()
String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
if (StringUtil.isNotBlank(errorMsgFromWebAuthnApi)) {
setErrorResponse(context, WEBAUTHN_ERROR_API_GET, errorMsgFromWebAuthnApi);
String mappedKey = mapBrowserApiErrorToMessageKey(errorMsgFromWebAuthnApi, false);
setErrorResponse(context, mappedKey, errorMsgFromWebAuthnApi);
return;
Comment thread
uzmamansoor09 marked this conversation as resolved.
}

Expand Down Expand Up @@ -253,6 +259,7 @@ public void action(AuthenticationFlowContext context) {
try {
result = user.credentialManager().isValid(cred);
} catch (WebAuthnException wae) {
logger.debug("WebAuthn authentication verification failed.", wae);
setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As commented by Martin and in #44963, here we can use the WebAuthnException type to give detailed messages (maybe not all of them, but the common ones). But #44963 will be managed as a follow-up.

return;
}
Expand Down Expand Up @@ -311,24 +318,26 @@ public WebAuthnCredentialProvider getCredentialProvider(KeycloakSession session)
return (WebAuthnCredentialProvider)session.getProvider(CredentialProvider.class, WebAuthnCredentialProviderFactory.PROVIDER_ID);
}

protected void setErrorResponse(AuthenticationFlowContext context, final String errorCase, final String errorMessage) {
protected void setErrorResponse(AuthenticationFlowContext context, final String errorCase, final String errorMessage, Object... parameters) {
Response errorResponse = null;
switch (errorCase) {
case WEBAUTHN_ERROR_REGISTRATION:
logger.warn(errorCase);
context.getEvent()
.detail(AUTH_ERR_LABEL, errorCase)
.error(Errors.INVALID_USER_CREDENTIALS);
errorResponse = createErrorResponse(context, errorCase);
errorResponse = createErrorResponse(context, errorCase, parameters);
context.failure(AuthenticationFlowError.INVALID_CREDENTIALS, errorResponse);
break;
case WEBAUTHN_ERROR_API_GET:
logger.warnv("error returned from navigator.credentials.get(). {0}", errorMessage);
case WEBAUTHN_ERROR_API_NOT_ALLOWED:
case WEBAUTHN_ERROR_API_INVALID_STATE:
case WEBAUTHN_ERROR_API_SECURITY:
case WEBAUTHN_ERROR_UNSUPPORTED_BROWSER:
context.getEvent()
.detail(AUTH_ERR_LABEL, errorCase)
.detail(AUTH_ERR_DETAIL_LABEL, errorMessage)
.error(Errors.NOT_ALLOWED);
errorResponse = createErrorResponse(context, errorCase);
errorResponse = createErrorResponse(context, errorCase, parameters);
context.failure(AuthenticationFlowError.INVALID_USER, errorResponse);
break;
case WEBAUTHN_ERROR_DIFFERENT_USER:
Expand All @@ -340,29 +349,28 @@ protected void setErrorResponse(AuthenticationFlowContext context, final String
context.failure(AuthenticationFlowError.USER_CONFLICT, errorResponse);
break;
case WEBAUTHN_ERROR_AUTH_VERIFICATION:
logger.warnv("WebAuthn API .get() response validation failure. {0}", errorMessage);
context.getEvent()
.detail(AUTH_ERR_LABEL, errorCase)
.detail(AUTH_ERR_DETAIL_LABEL, errorMessage)
.error(Errors.INVALID_USER_CREDENTIALS);
errorResponse = createErrorResponse(context, errorCase);
errorResponse = createErrorResponse(context, errorCase, parameters);
context.failure(AuthenticationFlowError.INVALID_USER, errorResponse);
break;
case WEBAUTHN_ERROR_USER_NOT_FOUND:
logger.warn(errorCase);
context.getEvent()
.detail(AUTH_ERR_LABEL, errorCase)
.error(Errors.USER_NOT_FOUND);
errorResponse = createErrorResponse(context, errorCase);
errorResponse = createErrorResponse(context, errorCase, parameters);
context.failure(AuthenticationFlowError.UNKNOWN_USER, errorResponse);
break;
default:
// NOP
}
}

protected Response createErrorResponse(AuthenticationFlowContext context, final String errorCase) {
LoginFormsProvider provider = context.form().setError(errorCase, "");
protected Response createErrorResponse(AuthenticationFlowContext context, final String errorCase, Object... parameters) {
LoginFormsProvider provider = context.form().setError(errorCase, parameters);
UserModel user = context.getUser();
if (user != null) {
WebAuthnMetadataService metadataService = getCredentialProvider(context.getSession()).getMetadataService();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public LoginFormsProvider fillContextForm(AuthenticationFlowContext context) {
}

@Override
protected Response createErrorResponse(AuthenticationFlowContext context, final String errorCase) {
protected Response createErrorResponse(AuthenticationFlowContext context, final String errorCase, Object... parameters) {
// the passkey failed, show error and maintain passkeys
context.form().setError(errorCase, "");
context.form().setError(errorCase, parameters);
context.form().setAttribute(WebAuthnConstants.ENABLE_WEBAUTHN_CONDITIONAL_UI, Boolean.TRUE);

AuthenticatorUtils.setupReauthenticationInUsernamePasswordFormError(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import org.keycloak.http.HttpRequest;
import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.UserModel;
import org.keycloak.models.WebAuthnPolicy;
import org.keycloak.models.credential.WebAuthnCredentialModel;
Expand Down Expand Up @@ -91,8 +92,17 @@

import static org.keycloak.WebAuthnConstants.REG_ERR_DETAIL_LABEL;
import static org.keycloak.WebAuthnConstants.REG_ERR_LABEL;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_GET;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_INVALID_STATE;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_NOT_ALLOWED;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_API_SECURITY;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_DUPLICATED_DEVICE;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTER_VERIFICATION;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTRATION;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTRATION_AAGUID_ATTESTATION_REQUIRED;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTRATION_ATTACHMENT_MISMATCH;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_REGISTRATION_NOT_ALLOWED_AAGUID;
import static org.keycloak.services.messages.Messages.WEBAUTHN_ERROR_UNSUPPORTED_BROWSER;
import static org.keycloak.services.messages.Messages.WEBAUTHN_REGISTER_TITLE;

/**
Expand Down Expand Up @@ -234,7 +244,8 @@ public void processAction(RequiredActionContext context) {
// receive error from navigator.credentials.create()
String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
if (errorMsgFromWebAuthnApi != null && !errorMsgFromWebAuthnApi.isEmpty()) {
setErrorResponse(context, WEBAUTHN_ERROR_REGISTER_VERIFICATION, errorMsgFromWebAuthnApi, originalEventType);
String mappedKey = mapBrowserApiErrorToMessageKey(errorMsgFromWebAuthnApi, true);
setErrorResponse(context, mappedKey, errorMsgFromWebAuthnApi, originalEventType);
return;
}

Expand Down Expand Up @@ -317,14 +328,17 @@ public void processAction(RequiredActionContext context) {
.detail(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, aaguid);
context.getEvent().clone().event(originalEventType).success();
context.success();
} catch (WebAuthnPolicyException wpe) {
logger.debug("WebAuthn policy violation during registration.", wpe);
setErrorResponse(context, wpe.getMessageKey(), wpe.getMessage(), originalEventType, wpe.getParameters());
} catch (WebAuthnException wae) {
if (logger.isDebugEnabled()) logger.debug(wae.getMessage(), wae);
logger.debug("WebAuthn registration failed.", wae);
setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, wae.getMessage(), originalEventType);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, the WebAuthnExceptioncan be used to set a more detailed message instead of the generic one. But there will be another PR for that.

return;
} catch (ModelDuplicateException e) {
setErrorResponse(context, WEBAUTHN_ERROR_DUPLICATED_DEVICE, e.getMessage(), originalEventType);
} catch (Exception e) {
if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e);
logger.debug("WebAuthn registration failed with unexpected error.", e);
setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, e.getMessage(), originalEventType);
return;
}
}

Expand Down Expand Up @@ -451,7 +465,7 @@ public void evaluateTriggers(RequiredActionContext context) {
// NOP
}

private void setErrorResponse(RequiredActionContext context, final String errorCase, final String errorMessage, @Deprecated final EventType originalEventType) {
private void setErrorResponse(RequiredActionContext context, final String errorCase, final String errorMessage, @Deprecated final EventType originalEventType, Object... parameters) {
Response errorResponse = null;
switch (errorCase) {
case WEBAUTHN_ERROR_REGISTER_VERIFICATION:
Expand All @@ -463,30 +477,69 @@ private void setErrorResponse(RequiredActionContext context, final String errorC
registerVerificationEvent.error(Errors.INVALID_USER_CREDENTIALS);
deprecatedRegisterVerificationEvent.error(Errors.INVALID_USER_CREDENTIALS);
errorResponse = context.form()
.setError(errorCase, errorMessage)
.setError(errorCase, parameters)
.setAttribute(WEB_AUTHN_TITLE_ATTR, WEBAUTHN_REGISTER_TITLE)
.createWebAuthnErrorPage();
Comment thread
uzmamansoor09 marked this conversation as resolved.
context.challenge(errorResponse);
break;
case WEBAUTHN_ERROR_REGISTRATION:
logger.warn(errorCase);
case WEBAUTHN_ERROR_REGISTRATION_NOT_ALLOWED_AAGUID:
case WEBAUTHN_ERROR_REGISTRATION_AAGUID_ATTESTATION_REQUIRED:
case WEBAUTHN_ERROR_REGISTRATION_ATTACHMENT_MISMATCH:
EventBuilder registrationEvent = context.getEvent()
.detail(REG_ERR_LABEL, errorCase)
.detail(REG_ERR_DETAIL_LABEL, errorMessage);
EventBuilder deprecatedRegistrationEvent = registrationEvent.clone().event(originalEventType);
deprecatedRegistrationEvent.error(Errors.INVALID_REGISTRATION);
registrationEvent.error(Errors.INVALID_REGISTRATION);
errorResponse = context.form()
.setError(errorCase, errorMessage)
.setError(errorCase, parameters)
.setAttribute(WEB_AUTHN_TITLE_ATTR, WEBAUTHN_REGISTER_TITLE)
.createWebAuthnErrorPage();
context.challenge(errorResponse);
Comment thread
uzmamansoor09 marked this conversation as resolved.
break;
default:
// NOP
// browser API error keys (not-allowed, timeout, etc.) — same event as a general registration failure
EventBuilder apiErrorEvent = context.getEvent()
.detail(REG_ERR_LABEL, errorCase)
.detail(REG_ERR_DETAIL_LABEL, errorMessage);
EventBuilder deprecatedApiErrorEvent = apiErrorEvent.clone().event(originalEventType);
deprecatedApiErrorEvent.error(Errors.INVALID_USER_CREDENTIALS);
apiErrorEvent.error(Errors.INVALID_USER_CREDENTIALS);
errorResponse = context.form()
.setError(errorCase, parameters)
.setAttribute(WEB_AUTHN_TITLE_ATTR, WEBAUTHN_REGISTER_TITLE)
.createWebAuthnErrorPage();
context.challenge(errorResponse);
break;
}
}

/**
* Maps a browser WebAuthn API error name (a {@code DOMException.name}) to a localizable message key.
*
* @param browserErrorName the raw error name from the browser (e.g. "NotAllowedError")
*/
public static String mapBrowserApiErrorToMessageKey(String browserErrorName, boolean isRegistration) {
if (StringUtil.isBlank(browserErrorName)) {
return isRegistration ? WEBAUTHN_ERROR_REGISTRATION : WEBAUTHN_ERROR_API_GET;
}
if(browserErrorName.contains("WebAuthnUnsupportedBrowser")) {
return WEBAUTHN_ERROR_UNSUPPORTED_BROWSER;
}
// DOMException names per https://webidl.spec.whatwg.org/#idl-DOMException-error-names
if (browserErrorName.contains("NotAllowedError") || browserErrorName.contains("TimeoutError")) {
return WEBAUTHN_ERROR_API_NOT_ALLOWED;
}
if (browserErrorName.contains("InvalidStateError")) {
return WEBAUTHN_ERROR_API_INVALID_STATE;
}
if (browserErrorName.contains("SecurityError")) {
return WEBAUTHN_ERROR_API_SECURITY;
}
return isRegistration ? WEBAUTHN_ERROR_REGISTRATION: WEBAUTHN_ERROR_API_GET;
Comment thread
uzmamansoor09 marked this conversation as resolved.
}

private boolean isFormDataRequest(HttpRequest request) {
MediaType mediaType = request.getHttpHeaders().getMediaType();
return mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
Expand All @@ -510,10 +563,12 @@ private static void verifyAcceptableAaguids(RegistrationData registrationData, W
if (CollectionUtil.isNotEmpty(acceptableAaguids)) {
// AAGUID comes from the authenticator data itself; only real attestation cryptographically proves the authenticator model
if (NoneAttestationStatement.FORMAT.equals(registrationData.getAttestationObject().getFormat())) {
throw new WebAuthnException("Acceptable AAGUIDs require an attestation format other than 'none'.");
throw new WebAuthnPolicyException(WEBAUTHN_ERROR_REGISTRATION_AAGUID_ATTESTATION_REQUIRED,
"Acceptable AAGUIDs require an attestation format other than 'none'.");
} else if (acceptableAaguids.stream().noneMatch(aaguid::equals)) {
logger.debugf("Rejected authenticator with AAGUID '%s'. Acceptable AAGUIDs: %s", aaguid, acceptableAaguids);
throw new WebAuthnException("Not acceptable authenticator model (based on the AAGUID).");
throw new WebAuthnPolicyException(WEBAUTHN_ERROR_REGISTRATION_NOT_ALLOWED_AAGUID,
"Not acceptable authenticator model (based on the AAGUID): " + aaguid, aaguid);
}
}
}
Expand All @@ -530,12 +585,38 @@ private static void verifyAuthenticatorAttachment(String authenticatorAttachment
}

if (!WebAuthnConstants.SUPPORTED_AUTHENTICATOR_ATTACHMENTS.contains(authenticatorAttachment)) {
throw new WebAuthnException("Unexpected authenticator attachment value. Possible values are: " + String.join(", ", WebAuthnConstants.SUPPORTED_AUTHENTICATOR_ATTACHMENTS));
throw new WebAuthnPolicyException(WEBAUTHN_ERROR_REGISTRATION_ATTACHMENT_MISMATCH,
"Unexpected authenticator attachment value. Possible values are: " + String.join(", ", WebAuthnConstants.SUPPORTED_AUTHENTICATOR_ATTACHMENTS), authenticatorAttachment);
}

if (!requiredAttachment.equals(authenticatorAttachment)) {
throw new WebAuthnException("Policy requires '" + requiredAttachment + "' authenticator attachment but got '" + authenticatorAttachment + "'");
throw new WebAuthnPolicyException(WEBAUTHN_ERROR_REGISTRATION_ATTACHMENT_MISMATCH,
"Policy requires '" + requiredAttachment + "' authenticator attachment but got '" + authenticatorAttachment + "'", authenticatorAttachment);
}
}
}

/**
* Carries a localizable message key, allowing the
* error to be displayed using a specific, translatable string rather than the raw exception text.
*/
static class WebAuthnPolicyException extends WebAuthnException {

private final String messageKey;
private final Object[] parameters;

WebAuthnPolicyException(String messageKey, String technicalDetail, Object... parameters) {
super(technicalDetail);
this.messageKey = messageKey;
this.parameters = parameters;
}

String getMessageKey() {
return messageKey;
}

Object[] getParameters() {
return parameters;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,16 @@ public class Messages {
public static final String WEBAUTHN_ERROR_REGISTER_VERIFICATION = "webauthn-error-register-verification";
public static final String WEBAUTHN_ERROR_USER_NOT_FOUND = "webauthn-error-user-not-found";

// WebAuthn Error — specific localizable cases
public static final String WEBAUTHN_ERROR_REGISTRATION_NOT_ALLOWED_AAGUID = "webauthn-error-registration-not-allowed-aaguid";
public static final String WEBAUTHN_ERROR_REGISTRATION_AAGUID_ATTESTATION_REQUIRED = "webauthn-error-registration-aaguid-attestation-required";
public static final String WEBAUTHN_ERROR_REGISTRATION_ATTACHMENT_MISMATCH = "webauthn-error-registration-attachment-mismatch";
public static final String WEBAUTHN_ERROR_API_NOT_ALLOWED = "webauthn-error-api-not-allowed";
public static final String WEBAUTHN_ERROR_API_INVALID_STATE = "webauthn-error-api-invalid-state";
public static final String WEBAUTHN_ERROR_API_SECURITY = "webauthn-error-api-security";
public static final String WEBAUTHN_ERROR_UNSUPPORTED_BROWSER = "webauthn-unsupported-browser-text";
public static final String WEBAUTHN_ERROR_DUPLICATED_DEVICE = "webauthn-error-duplicated-device";

// Conditions in Conditional Flow
public static final String ACCESS_DENIED = "access-denied";

Expand Down
Loading
Loading