8000 Reject redirect_uri OIDC params with leading query delimiters by edewit · Pull Request #55739 · 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
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,7 @@ public KeycloakUriBuilder resolveTemplates(Map<String, Object> templateValues) t
public KeycloakUriBuilder removeQueryParamByDecodedName(String name) {
if (name == null) throw new IllegalArgumentException("name parameter is null");
if (query == null || query.isEmpty()) return this;
query = removeParams(query, rawName -> name.equals(Encode.decode(rawName)));
query = removeParams(query, rawName -> name.equals(UriUtils.stripLeadingQueryDelimiters(Encode.decode(rawName))));
return this;
}

Expand All @@ -872,7 +872,7 @@ public KeycloakUriBuilder removeQueryParamByDecodedName(String name) {
public KeycloakUriBuilder removeFragmentParamByDecodedName(String name) {
if (name == null) throw new IllegalArgumentException("name parameter is null");
if (fragment == null || fragment.isEmpty()) return this;
fragment = removeParams(fragment, rawName -> name.equals(Encode.decode(rawName)));
fragment = removeParams(fragment, rawName -> name.equals(UriUtils.stripLeadingQueryDelimiters(Encode.decode(rawName))));
return this;
}

Expand Down
27 changes: 27 additions & 0 deletions common/src/main/java/org/keycloak/common/util/UriUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,33 @@ public static MultivaluedHashMap<String, String> decodeQueryString(String queryS
return parseQueryParameters(queryString, true);
}

/**
* Strips leading {@code '?'} and {@code '#'} characters from a decoded query or fragment parameter name.
* <p>
* A doubled delimiter in a redirect URI (for example {@code ??code=} or {@code #?code=}) or a
* percent-encoded delimiter ({@code %3Fcode=}) leaves those characters on the parameter name.
* Some clients treat the leading delimiter as separators and then read the bare name, so callers
* that match OIDC response parameter names should normalize first.
*
* @param name decoded parameter name, may be {@code null}
* @return {@code name} without leading {@code '?'} / {@code '#'}, or {@code name} itself when none
*/
public static String stripLeadingQueryDelimiters(String name) {
if (name == null || name.isEmpty()) {
return name;
}
int i = 0;
while (i < name.length()) {
char c = name.charAt(i);
if (c == '?' || c == '#') {
i++;
} else {
break;
}
}
return i == 0 ? name : name.substring(i);
}

public static String stripQueryParam(String url, String name){
return url.replaceFirst("[\\?&]"+name+"=[^&]*$|"+name+"=[^&]*&", "");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@ public void testRemoveQueryParamByDecodedName() {
Assertions.assertEquals("http://localhost/path?state=val",
KeycloakUriBuilder.fromUri("http://localhost/path?state=val", false)
.removeQueryParamByDecodedName("other").buildAsString());

Assertions.assertEquals("http://localhost/path?other=keep",
KeycloakUriBuilder.fromUri("http://localhost/path??code=evil&other=keep", false)
.removeQueryParamByDecodedName("code").buildAsString());

Assertions.assertEquals("http://localhost/path?other=keep",
KeycloakUriBuilder.fromUri("http://localhost/path?%3Fcode=evil&other=keep", false)
.removeQueryParamByDecodedName("code").buildAsString());
}

@Test
Expand All @@ -144,5 +152,20 @@ public void testRemoveFragmentParamByDecodedName() {
Assertions.assertEquals("http://localhost/path#state=val",
KeycloakUriBuilder.fromUri("http://localhost/path#state=val", false)
.removeFragmentParamByDecodedName("other").buildAsString());

Assertions.assertEquals("http://localhost/path#other=keep",
KeycloakUriBuilder.fromUri("http://localhost/path#?code=evil&other=keep", false)
.removeFragmentParamByDecodedName("code").buildAsString());
}

@Test
public void testStripLeadingQueryDelimiters() {
Assertions.assertNull(UriUtils.stripLeadingQueryDelimiters(null));
Assertions.assertEquals("", UriUtils.stripLeadingQueryDelimiters(""));
Assertions.assertEquals("code", UriUtils.stripLeadingQueryDelimiters("code"));
Assertions.assertEquals("code", UriUtils.stripLeadingQueryDelimiters("?code"));
Assertions.assertEquals("code", UriUtils.stripLeadingQueryDelimiters("??code"));
Assertions.assertEquals("code", UriUtils.stripLeadingQueryDelimiters("#?code"));
Assertions.assertEquals("state", UriUtils.stripLeadingQueryDelimiters("##state"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.keycloak.common.util.HtmlUtils;
import org.keycloak.common.util.KeycloakUriBuilder;
import org.keycloak.common.util.Time;
import org.keycloak.common.util.UriUtils;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakContext;
Expand Down Expand Up @@ -136,7 +137,7 @@ private void removeFragmentParamByDecodedName(String name) {
for (String param : fragment.toString().split("&")) {
int eqPos = param.indexOf('=');
String rawName = eqPos >= 0 ? param.substring(0, eqPos) : param;
if (name.equals(Encode.decode(rawName))) continue;
if (name.equals(UriUtils.stripLeadingQueryDelimiters(Encode.decode(rawName)))) continue;
if (!cleaned.isEmpty()) cleaned.append("&");
cleaned.append(param);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,9 @@ private static boolean hasForbiddenParams(String paramString, Set<String> forbid
}
MultivaluedHashMap<String, String> params = UriUtils.decodeQueryString(paramString);
for (String paramName : params.keySet()) {
String normalizedName = UriUtils.stripLeadingQueryDelimiters(paramName).toLowerCase(Locale.ROOT);
if (forbiddenParams.stream().map(param -> param.toLowerCase(Locale.ROOT))
.anyMatch(paramName.toLowerCase(Locale.ROOT)::equals)) {
.anyMatch(normalizedName::equals)) {
logger.warnf("Redirect URI rejected: contains forbidden OIDC parameter '%s' in %s: scheme=%s, host=%s, path=%s",
paramName, component, originalRedirect.getScheme(), originalRedirect.getHost(), originalRedirect.getPath());
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,30 @@ public void testCleanUriPassesThroughUnchanged() {
Assertions.assertTrue(url.contains("tab=profile"), "Non-forbidden query param should survive");
Assertions.assertTrue(url.contains("code=real_code"), "Added param should be present");
}

@Test
public void testQueryModeStripsLeadingQuestionMarkForbiddenParams() {
OIDCRedirectUriBuilder builder = OIDCRedirectUriBuilder.fromUri("https://client.com/callback??code=evil&legit=keep",
OIDCResponseMode.QUERY, null, null);
builder.addParam("code", "real_code");
Response response = builder.build();
String url = response.getLocation().toString();

Assertions.assertFalse(url.contains("code=evil"), "Attacker's ?code param should be stripped");
Assertions.assertTrue(url.contains("code=real_code"), "Legitimate code param should be present");
Assertions.assertTrue(url.contains("legit=keep"), "Non-forbidden param should survive");
}

@Test
public void testFragmentModeStripsLeadingQuestionMarkForbiddenParams() {
OIDCRedirectUriBuilder builder = OIDCRedirectUriBuilder.fromUri("https://client.com/callback#?code=evil&custom=keep",
OIDCResponseMode.FRAGMENT, null, null);
builder.addParam("code", "real_code");
Response response = builder.build();
String url = response.getLocation().toString();

Assertions.assertFalse(url.contains("code=evil"), "Attacker's #?code param should be stripped");
Assertions.assertTrue(url.contains("code=real_code"), "Legitimate code param should be present");
Assertions.assertTrue(url.contains("custom=keep"), "Non-forbidden fragment param should survive");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -477,8 +477,11 @@ public void testWildcards() {

@Test
public void testVerifyRedirectUriWithPollutedParameters() {
// Use callback* (not callback/*): matchesRedirects truncates at the first '?', so
// URIs like callback#?code=… become callback# and would fail allowlist matching
// before the forbidden-parameter check without a prefix wildcard.
Set<String> set = Stream.of(
"https://example.com/callback/*"
"https://example.com/callback*"
).collect(Collectors.toSet());

Assert.assertNull("Should reject URL-encoded 'code' parameter", RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback?c%6Fde=attack", set, false));
Expand All @@ -505,6 +508,20 @@ public void testVerifyRedirectUriWithPollutedParameters() {
// URL-encoded variants of forbidden params in query
Assert.assertNull("Should reject URL-encoded 'state' (st%61te)", RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback?st%61te=evil", set, false));

// Leading '?' delimiter pollution (CVE-2026-137431 incomplete fix of CVE-2026-9689 / CVE-2026-18209)
Assert.assertNull("Should reject doubled query delimiter before forbidden param",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback??code=EVIL", set, false));
Assert.assertNull("Should reject tripled query delimiter before forbidden param",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback???code=EVIL", set, false));
Assert.assertNull("Should reject percent-encoded leading '?' on forbidden param name",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback?%3Fcode=EVIL", set, false));
Assert.assertNull("Should reject fragment starting with '?' before forbidden param",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback#?code=EVIL", set, false));
Assert.assertNull("Should reject percent-encoded leading '#' on forbidden fragment param",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback#%23state=EVIL", set, false));
Assert.assertNull("Should reject mixed-case forbidden param after leading '?'",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback??STATE=EVIL", set, false));

// Backward compat: empty forbidden set allows everything (query and fragment)
Assert.assertEquals("Empty forbidden set should allow forbidden params in query", "https://example.com/callback?state=val",
RedirectUtils.verifyRedirectUri(session, null, "https://example.com/callback?state=val", set, false, Collections.emptySet()));
Expand Down
Loading
0