8000 Do not complete login from a consent request without a valid session code by huyenvu2101 · Pull Request #55398 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
8000
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,13 @@ public Response processConsent() {
MultivaluedMap<String, String> formData = request.getDecodedFormParameters();
event.event(EventType.LOGIN);
String code = formData.getFirst(SESSION_CODE);
if (code == null) {
// Support custom themes that still submit the legacy field
code = formData.getFirst(OAuth2Constants.CODE);
if (code != null) {
logger.debugf("Consent form submitted the legacy '%s' field. Use '%s' in the template.", OAuth2Constants.CODE, SESSION_CODE);
}
}
String clientId = session.getContext().getUri().getQueryParameters().getFirst(Constants.CLIENT_ID);
String tabId = session.getContext().getUri().getQueryParameters().getFirst(Constants.TAB_ID);
String clientData = session.getContext().getUri().getQueryParameters().getFirst(Constants.CLIENT_DATA);
Expand All @@ -1083,6 +1090,12 @@ public Response processConsent() {

initLoginEvent(authSession);

if (!checks.isActionRequest()) {
// Request without a session code is not a consent submission, the action matching the consent screen
// was not verified. Continue with whatever is pending instead of granting the consent.
return AuthenticationManager.nextActionAfterAuthentication(session, authSession, clientConnection, request, session.getContext().getUri(), event);
}

UserModel user = authSession.getAuthenticatedUser();
ClientModel client = authSession.getClient();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.tests.oauth;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import jakarta.ws.rs.core.UriBuilder;

import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.events.Details;
import org.keycloak.models.UserModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testframework.annotations.InjectClient;
import org.keycloak.testframework.annotations.InjectEvents;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.events.EventAssertion;
import org.keycloak.testframework.events.Events;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.ClientBuilder;
import org.keycloak.testframework.realm.ClientConfig;
import org.keycloak.testframework.realm.ManagedClient;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.annotations.InjectWebDriver;
import org.keycloak.testframework.ui.page.LoginExpiredPage;
import org.keycloak.testframework.ui.page.LoginPasswordUpdatePage;
import org.keycloak.testframework.ui.page.OAuthGrantPage;
import org.keycloak.testframework.ui.webdriver.ManagedWebDriver;
import org.keycloak.tests.utils.admin.AdminApiUtil;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;

/**
* Consent requests without a valid session code must not complete the login, see CVE-2026-133221.
*/
@KeycloakIntegrationTest
public class ConsentRequiredActionBypassTest {

private static final String THIRD_PARTY_APP = "third-party";
private static final String THIRD_PARTY_SECRET = "password";
// Client created by @InjectOAuthClient, see DefaultOAuthClientConfiguration
private static final String NO_CONSENT_APP = "test-app";
private static final String NO_CONSENT_SECRET = "test-secret";
private static final String USERNAME = "test-user@localhost";
private static final String PASSWORD = "password";

@InjectRealm(config = ConsentRealmConfig.class)
ManagedRealm realm;

@InjectClient(config = ThirdPartyClientConfig.class)
ManagedClient thirdParty;

@InjectOAuthClient
OAuthClient oauth;

@InjectWebDriver
ManagedWebDriver driver;

@InjectEvents
Events events;

@InjectPage
OAuthGrantPage grantPage;

@InjectPage
LoginPasswordUpdatePage updatePasswordPage;

@InjectPage
LoginExpiredPage loginExpiredPage;

@AfterEach
public void cleanup() {
// Undo any effect of the test, including a successful bypass, so that it does not leak into other tests
UserResource user = user();
user.logout();
user.getConsents().forEach(consent -> user.revokeConsent((String) consent.get("clientId")));
UserRepresentation rep = user.toRepresentation();
rep.setRequiredActions(List.of());
user.update(rep);
AdminApiUtil.resetUserPassword(user, PASSWORD, false);
}

@Test
public void consentWithLegacyCodeFieldCompletesLogin() {
loginToConsentScreen();

// Custom themes based on the previous template submit the session code in the "code" field
String sessionCode = driver.findElement(By.name("session_code")).getAttribute("value");
submitForm(consentFormAction(), Map.of("code", sessionCode));

Assertions.assertTrue(oauth.parseLoginResponse().isSuccess(), driver.getCurrentUrl());
EventAssertion.expectLoginSuccess(events.poll())
.clientId(THIRD_PARTY_APP)
.details(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
}

@Test
public void consentWithoutSessionCodeDoesNotGrantConsent() {
loginToConsentScreen();

// Submit the consent form without its session code, while no other required action is pending
submitForm(consentFormAction(), Map.of());

// The consent screen is shown again, and nothing was granted
grantPage.assertCurrent();
Assertions.assertTrue(user().getUserSessions().isEmpty());
Assertions.assertTrue(user().getConsents().isEmpty());

// Submitting the consent screen with its session code still completes the login
grantPage.accept();
Assertions.assertTrue(oauth.parseLoginResponse().isSuccess(), driver.getCurrentUrl());
}

@Test
public void consentWithoutSessionCodeDoesNotSkipRequiredActionConsentClient() {
assertConsentRequestDoesNotSkipRequiredAction(true, actionUri -> Map.of(), false);
}

@Test
public void consentWithoutSessionCodeDoesNotSkipRequiredActionNoConsentClient() {
assertConsentRequestDoesNotSkipRequiredAction(false, actionUri -> Map.of(), false);
}

// The next tests submit the code in the legacy "code" field, which the consent endpoint used to ignore

@Test
public void consentWithInvalidSessionCodeDoesNotSkipRequiredAction() {
assertConsentRequestDoesNotSkipRequiredAction(true, actionUri -> Map.of("code", "invalid"), true);
}

@Test
public void consentWithSessionCodeOfOtherRequiredActionDoesNotSkipRequiredAction() {
assertConsentRequestDoesNotSkipRequiredAction(true, actionUri -> Map.of("code", queryParam(actionUri, "session_code")), false);
}

private void assertConsentRequestDoesNotSkipRequiredAction(boolean consentClient, Function<String, Map<String, String>> consentForm, boolean expectPageExpired) {
UserResource user = user();
UserRepresentation rep = user.toRepresentation();
rep.setRequiredActions(List.of(UserModel.RequiredAction.UPDATE_PASSWORD.name()));
user.update(rep);

if (consentClient) {
oauth.client(THIRD_PARTY_APP, THIRD_PARTY_SECRET);
} else {
oauth.client(NO_CONSENT_APP, NO_CONSENT_SECRET);
}
oauth.openLoginForm();
oauth.fillLoginForm(USERNAME, PASSWORD);
updatePasswordPage.assertCurrent();

// Send the consent request directly, while the required action is still pending
String actionUri = driver.findElement(By.cssSelector("form[action*='/login-actions/required-action']")).getAttribute("action");
String consentUri = UriBuilder.fromUri(actionUri.replace("/login-actions/required-action", "/login-actions/consent"))
.replaceQueryParam("session_code")
.replaceQueryParam("execution")
.build().toString();
submitForm(consentUri, consentForm.apply(actionUri));

// No authorization code is issued and the user did not get past the required action
Assertions.assertFalse(driver.getCurrentUrl().startsWith(oauth.getRedirectUri()), driver.getCurrentUrl());
Assertions.assertFalse(driver.getCurrentUrl().contains("code="), driver.getCurrentUrl());
Assertions.assertTrue(user.toRepresentation().getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name()));
Assertions.assertTrue(user.getUserSessions().isEmpty());
Assertions.assertTrue(user.getConsents().isEmpty());

// The user can continue with the pending required action and complete the login
if (expectPageExpired) {
loginExpiredPage.assertCurrent();
loginExpiredPage.clickLoginContinueLink();
}
updatePasswordPage.assertCurrent();
updatePasswordPage.changePassword("new-password", "new-password");
if (consentClient) {
grantPage.assertCurrent();
grantPage.accept();
}
Assertions.assertTrue(oauth.parseLoginResponse().isSuccess(), driver.getCurrentUrl());
}

private void loginToConsentScreen() {
oauth.client(THIRD_PARTY_APP, THIRD_PARTY_SECRET);
oauth.openLoginForm();
oauth.fillLoginForm(USERNAME, PASSWORD);
grantPage.assertCurrent();
}

private String consentFormAction() {
String action = driver.findElement(By.xpath("//input[@name='session_code']/ancestor::form")).getAttribute("action");
return URI.create(driver.getCurrentUrl()).resolve(action).toString();
}

/**
* Submits a POST form from the browser, so that the request carries the browser cookies like a real form submission.
*/
private void submitForm(String action, Map<String, String> params) {
WebElement page = driver.findElement(By.tagName("html"));
((JavascriptExecutor) driver.driver()).executeScript(
"var params = arguments[1];" +
"var form = document.createElement('form');" +
"form.method = 'POST';" +
"form.action = arguments[0];" +
"Object.keys(params).forEach(function (name) {" +
" var input = document.createElement('input');" +
" input.type = 'hidden';" +
" input.name = name;" +
" input.value = params[name];" +
" form.appendChild(input);" +
"});" +
"document.body.appendChild(form);" +
"form.submit();",
action, params);
driver.waiting().waitUntilStale(page);
}

private static String queryParam(String uri, String name) {
return URLEncodedUtils.parse(URI.create(uri), StandardCharsets.UTF_8).stream()
.filter(param -> name.equals(param.getName()))
.map(NameValuePair::getValue)
.findFirst()
.orElseThrow();
}

private UserResource user() {
return AdminApiUtil.findUserByUsernameId(realm.admin(), USERNAME);
}

public static class ConsentRealmConfig implements RealmConfig {
@Override
public RealmBuilder configure(RealmBuilder realm) {
return realm.users(UserBuilder.create(USERNAME)
.email(USERNAME)
.name("Test", "User")
.emailVerified(true)
.password(PASSWORD)
.enabled(true));
}
}

public static class ThirdPartyClientConfig implements ClientConfig {
@Override
public ClientBuilder configure(ClientBuilder client) {
return client.clientId(THIRD_PARTY_APP)
.protocol(OIDCLoginProtocol.LOGIN_PROTOCOL)
.consentRequired(Boolean.TRUE)
.redirectUris("*")
.publicClient(Boolean.FALSE)
.secret(THIRD_PARTY_SECRET);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
</#if>

<form class="${properties.kcFormClass!} ${properties.kcMarginTopClass!}" action="${url.oauthAction}" method="POST">
<input type="hidden" name="code" value="${oauth.code}">
<input type="hidden" name="session_code" value="${oauth.code}">
<@buttons.actionGroup horizontal=true>
<@buttons.button id="kc-login" name="accept" label="doYes"/>
<@buttons.button id="kc-cancel" name="cancel" label="doNo" type="secondary"/>
Expand Down
Loading
0