8000 [26.8] Prevent kcSanitize bypass that reactivates URLs with JavaScript scheme on the login page by michalvavrik · Pull Request #53969 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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 @@ -24,6 +24,7 @@
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.owasp.html.Encoding;
import org.owasp.html.FilterUrlByProtocolAttributePolicy;

/**
* Allows sanitizing of html that uses Freemarker ?no_esc. This way, html
Expand All @@ -33,7 +34,12 @@
public class KeycloakSanitizerMethod implements TemplateMethodModelEx {

private static final Pattern HREF_PATTERN = Pattern.compile("\\s+href=\"([^\"]*)\"");


private static final Pattern NUMERIC_ENTITY = Pattern.compile("&#([xX][0-9a-fA-F]+|[0-9]+);?");

private static final FilterUrlByProtocolAttributePolicy URL_PROTOCOL_POLICY =
new FilterUrlByProtocolAttributePolicy(List.of("http", "https", "mailto"));

@Override
public Object exec(List list) throws TemplateModelException {
if ((list.isEmpty()) || (list.get(0) == null)) {
Expand Down Expand Up @@ -80,6 +86,9 @@ private String fixURLs(String msg) {
String href = matcher.group(1).replaceAll("=", "=")
.replaceAll("\\.\\.", ".")
.replaceAll("&", "&");
if (hasDisallowedScheme(href)) {
href = "";
}
result.append(msg.substring(last, matcher.start(1))).append(href);
last = matcher.end(1);
} while (matcher.find());
Expand All @@ -88,5 +97,34 @@ private String fixURLs(String msg) {
}
return msg;
}


private boolean hasDisallowedScheme(String href) {
return URL_PROTOCOL_POLICY.apply("a", "href", decodeNumericEntities(href)) == null;
}

private String decodeNumericEntities(String value) {
Matcher matcher = NUMERIC_ENTITY.matcher(value);
StringBuilder result = new StringBuilder(value.length());
int last = 0;
while (matcher.find()) {
result.append(value, last, matcher.start());
String digits = matcher.group(1);
try {
int codePoint = (digits.charAt(0) == 'x' || digits.charAt(0) == 'X')
? Integer.parseInt(digits.substring(1), 16)
: Integer.parseInt(digits);
if (Character.isValidCodePoint(codePoint)) {
result.appendCodePoint(codePoint);
} else {
result.append(matcher.group());
}
} catch (NumberFormatException e) {
result.append(matcher.group());
}
last = matcher.end();
}
result.append(value, last, value.length());
return result.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,61 @@ public void testUrls() throws Exception {
assertResult("<p><a href=\"https://localhost?key=123&msg=abc\" rel=\"nofollow\">link1</a><a href=\"https://localhost?key=abc&msg=123\" rel=\"nofollow\">link2</a></p>", html);
}

@Test
public void testJavascriptUrlViaNumericCharacterReferenceIsNeutralized() throws Exception {
List<String> html = new ArrayList<>();

html.add("<a href=\"javascript&#58alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"javascript&#x3aprompt(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"javascript&#X3Aprompt(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"javascript&#0000058alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"JaVaScRiPt&#58alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"java&#115cript&#58alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"java&#10script&#58alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"java&#9script&#58alert(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"vbscript&#58msgbox(xss)\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"data&#58text/plain,hello\">link</a>");
assertResult("<a href=\"\" rel=\"nofollow\">link</a>", html);

html.set(0, "<a href=\"javascript&#58;alert(xss)\">link</a>");
assertResult("link", html);

html.set(0, "<a href=\"javascript&colon;alert(xss)\">link</a>");
assertResult("link", html);
}

@Test
public void testLegitimateMarkupAndLinksArePreserved() throws Exception {
List<String> html = new ArrayList<>();

html.add("<b>ACME Corp</b>");
assertResult("<b>ACME Corp</b>", html);

html.set(0, "<a href=\"https://www.example.org/welcome\">Welcome</a>");
assertResult("<a href=\"https://www.example.org/welcome\" rel=\"nofollow\">Welcome</a>", html);

html.set(0, "<a href=\"https://kc.example.org/realms/r/login-actions/action-token?key=abc.def&client_id=account&tab_id=x1\">verify</a>");
assertResult("<a href=\"https://kc.example.org/realms/r/login-actions/action-token?key=abc.def&client_id=account&tab_id=x1\" rel=\"nofollow\">verify</a>", html);
}

private void assertResult(String expectedResult, List<String> html) throws Exception {
String result = kcEscape.exec(html).toString();
assertEquals(expectedResult, result);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package org.keycloak.tests.forms;

import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.ui.annotations.InjectPage;
import org.keycloak.testframework.ui.annotations.InjectWebDriver;
import org.keycloak.testframework.ui.page.LoginPage;
import org.keycloak.testframework.ui.webdriver.ManagedWebDriver;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.JavascriptExecutor;

@KeycloakIntegrationTest
public class LoginPageDisplayNameHtmlSanitizationTest {

@InjectRealm
ManagedRealm managedRealm;

@InjectOAuthClient
OAuthClient oauth;

@InjectWebDriver
ManagedWebDriver driver;

@InjectPage
LoginPage loginPage;

@Test
public void decimalNumericCharacterReferenceJavascriptUrlIsNeutralized() {
String page = renderLoginPageWithDisplayNameHtml("<a href=\"javascript&#58alert(xss53813)\">pwn</a>");
assertNoExecutableScheme(page);
}

@Test
public void hexNumericCharacterReferenceJavascriptUrlIsNeutralized() {
String page = renderLoginPageWithDisplayNameHtml("<a href=\"javascript&#x3aprompt(xss53813)\">pwn</a>");
assertNoExecutableScheme(page);
}

@Test
public void legitimateDisplayNameHtmlIsPreserved() {
String page = renderLoginPageWithDisplayNameHtml("<b>ACME53813</b>");
Assertions.assertTrue(page.contains("<b>ACME53813</b>"), "benign display name markup must render");
}

@Test
public void httpLinkIsPreserved() {
String page = renderLoginPageWithDisplayNameHtml("<a href=\"http://acme53813.example.com/help?topic=sso&lang=en\">Help</a>");
Assertions.assertTrue(page.contains("<a href=\"http://acme53813.example.com/help?topic=sso&lang=en\" rel=\"nofollow\">Help</a>"),
"http link must be preserved");
}

@Test
public void httpsLinkIsPreserved() {
String page = renderLoginPageWithDisplayNameHtml("<a href=\"https://acme53813.example.com/help?topic=sso&lang=en\">Help</a>");
Assertions.assertTrue(page.contains("<a href=\"https://acme53813.example.com/help?topic=sso&lang=en\" rel=\"nofollow\">Help</a>"),
"https link must be preserved");
}

@Test
public void mailtoLinkIsPreserved() {
String page = renderLoginPageWithDisplayNameHtml("<a href=\"mailto:support@acme53813.example.com\">Mail</a>");
Assertions.assertTrue(page.contains("<a href=\"mailto:support&#64;acme53813.example.com\" rel=\"nofollow\">Mail</a>"),
"mailto link must be preserved");
}

private String renderLoginPageWithDisplayNameHtml(String displayNameHtml) {
managedRealm.updateWithCleanup(r -> r.update(realm -> realm.setDisplayNameHtml(displayNameHtml)));
oauth.openLoginForm();
loginPage.assertCurrent();
String loginPageUrl = driver.getCurrentUrl();
return (String) ((JavascriptExecutor) driver.driver()).executeScript(
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', arguments[0], false);" +
"xhr.send();" +
"return xhr.responseText;", loginPageUrl);
}

private void assertNoExecutableScheme(String pageSource) {
String lower = pageSource.toLowerCase();
Assertions.assertFalse(lower.contains("javascript&#"),
"login page must not emit a reactivated javascript URL");
Assertions.assertFalse(lower.contains("javascript:alert") || lower.contains("javascript:prompt"),
"login page must not emit a live javascript URL");
}
}
Loading
0