From 9aa92ee9a213ebd78e12a22cf93b60ce9eb7b3f7 Mon Sep 17 00:00:00 2001
From: Ricardo Martin <rmartinc@redhat.com>
Date: Thu, 18 Apr 2024 14:02:24 +0000
Subject: [PATCH] Perform exact string match if redirect URI contains userinfo, encoded slashes or parent access (#131) (#28872)

---
 src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java |  122 +++++++++-------------------------------
 1 files changed, 28 insertions(+), 94 deletions(-)

diff --git a/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java b/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
index 2bca7fe..de8fd84 100644
--- a/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
+++ b/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
@@ -18,8 +18,6 @@
 package org.keycloak.protocol.oidc.utils;
 
 import org.jboss.logging.Logger;
-import org.keycloak.common.util.Encode;
-import org.keycloak.common.util.KeycloakUriBuilder;
 import org.keycloak.common.util.UriUtils;
 import org.keycloak.models.ClientModel;
 import org.keycloak.models.Constants;
@@ -34,6 +32,7 @@
 import java.util.Collection;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 /**
@@ -73,7 +72,7 @@
                 validRedirect = relativeToAbsoluteURI(session, rootUrl, validRedirect);
                 logger.debugv("replacing relative valid redirect with: {0}", validRedirect);
             }
-            resolveValidRedirects.add(lowerCaseHostname(validRedirect));
+            resolveValidRedirects.add(validRedirect);
         }
         return resolveValidRedirects;
     }
@@ -111,16 +110,13 @@
                 return null;
             }
 
-            // Make the validations against fully decoded and normalized redirect-url. This also allows wildcards (case when client configured "Valid redirect-urls" contain wildcards)
-            String decodedRedirectUri = decodeRedirectUri(redirectUri);
-            URI decodedRedirect = toUri(decodedRedirectUri);
-            decodedRedirectUri = getNormalizedRedirectUri(decodedRedirect, true);
-            if (decodedRedirectUri == null) return null;
+            // check if the passed URI allows wildcards
+            boolean allowWildcards = areWildcardsAllowed(originalRedirect);
 
-            String r = decodedRedirectUri;
+            String r = redirectUri;
             Set<String> resolveValidRedirects = resolveValidRedirects(session, rootUrl, validRedirects);
 
-            String valid = matchesRedirects(resolveValidRedirects, r, true);
+            String valid = matchesRedirects(resolveValidRedirects, r, allowWildcards);
 
             if (valid == null && (r.startsWith(Constants.INSTALLED_APP_URL) || r.startsWith(Constants.INSTALLED_APP_LOOPBACK)) && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) {
                 int i = r.indexOf(':', Constants.INSTALLED_APP_URL.length());
@@ -135,15 +131,7 @@
 
                 r = sb.toString();
 
-                valid = matchesRedirects(resolveValidRedirects, r, true);
-            }
-
-            // Return the original redirectUri, which can be partially encoded - for example http://localhost:8280/foo/bar%20bar%2092%2F72/3 . Just make sure it is normalized
-            redirectUri = getNormalizedRedirectUri(originalRedirect, false);
-
-            // We try to check validity also for original (encoded) redirectUrl, but just in case it exactly matches some "Valid Redirect URL" specified for client (not wildcards allowed)
-            if (valid == null) {
-                valid = matchesRedirects(resolveValidRedirects, redirectUri, false);
+                valid = matchesRedirects(resolveValidRedirects, r, allowWildcards);
             }
 
             if (valid != null && !originalRedirect.isAbsolute()) {
@@ -154,10 +142,10 @@
                 redirectUri = relativeToAbsoluteURI(session, rootUrl, redirectUri);
             }
 
-            String scheme = decodedRedirect.getScheme();
+            String scheme = originalRedirect.getScheme();
             if (valid != null && scheme != null) {
                 // check the scheme is valid, it should be http(s) or explicitly allowed by the validation
-                if (!valid.startsWith(scheme.toLowerCase() + ":") && !"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
+                if (!valid.startsWith(scheme + ":") && !"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
                     logger.debugf("Invalid URI because scheme is not allowed: %s", redirectUri);
                     valid = null;
                 }
@@ -179,74 +167,22 @@
             try {
                 uri = URI.create(redirectUri);
             } catch (IllegalArgumentException cause) {
-                logger.debug("Invalid redirect uri", cause);
+                logger.debugf(cause, "Invalid redirect uri %s", redirectUri);
             } catch (Exception cause) {
-                logger.debug("Unexpected error when parsing redirect uri", cause);
+                logger.debugf(cause, "Unexpected error when parsing redirect uri %s", redirectUri);
             }
         }
         return uri;
     }
 
-    private static String getNormalizedRedirectUri(URI uri, boolean lower) {
-        String redirectUri = null;
-        if (uri != null) {
-            redirectUri = uri.normalize().toString();
-            if (lower) {
-                redirectUri = lowerCaseHostname(redirectUri);
-            }
-        }
-        return redirectUri;
-    }
+    // any access to parent folder /../ is unsafe with or without encoding
+    private final static Pattern UNSAFE_PATH_PATTERN = Pattern.compile(
+            "(/|%2[fF]|%5[cC]|\\\\)(%2[eE]|\\.){2}(/|%2[fF]|%5[cC]|\\\\)|(/|%2[fF]|%5[cC]|\\\\)(%2[eE]|\\.){2}$");
 
-    // Decode redirectUri. We don't decode query and fragment as those can be encoded in the original URL.
-    // URL can be decoded multiple times (in case it was encoded multiple times, or some of it's parts were encoded multiple times)
-    private static String decodeRedirectUri(String redirectUri) {
-        if (redirectUri == null) return null;
-        int MAX_DECODING_COUNT = 5; // Max count of attempts for decoding URL (in case it was encoded multiple times)
-
-        try {
-            KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(redirectUri, false).preserveDefaultPort();
-            String origQuery = uriBuilder.getQuery();
-            String origFragment = uriBuilder.getFragment();
-            String origUserInfo = uriBuilder.getUserInfo();
-            String encodedRedirectUri = uriBuilder
-                    .replaceQuery(null)
-                    .fragment(null)
-                    .userInfo(null)
-                    .buildAsString();
-            String decodedRedirectUri = null;
-
-            for (int i = 0; i < MAX_DECODING_COUNT; i++) {
-                decodedRedirectUri = Encode.decode(encodedRedirectUri);
-                if (decodedRedirectUri.equals(encodedRedirectUri)) {
-                    // URL is decoded. We can return it (after attach original query and fragment)
-                    return KeycloakUriBuilder.fromUri(decodedRedirectUri, false).preserveDefaultPort()
-                            .replaceQuery(origQuery)
-                            .fragment(origFragment)
-                            .userInfo(origUserInfo)
-                            .buildAsString();
-                } else {
-                    // Next attempt
-                    encodedRedirectUri = decodedRedirectUri;
-                }
-            }
-        } catch (IllegalArgumentException iae) {
-            logger.debugf("Illegal redirect URI used: %s, Details: %s", redirectUri, iae.getMessage());
-        }
-        logger.debugf("Was not able to decode redirect URI: %s", redirectUri);
-        return null;
-    }
-
-    private static String lowerCaseHostname(String redirectUri) {
-        // lower case host and scheme which are case-insensitive by spec
-        KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(redirectUri, false).preserveDefaultPort();
-        if (uriBuilder.getScheme() != null) {
-            uriBuilder.scheme(uriBuilder.getScheme().toLowerCase());
-        }
-        if (uriBuilder.getHost() != null) {
-            uriBuilder.host(uriBuilder.getHost().toLowerCase());
-        }
-        return uriBuilder.buildAsString();
+    private static boolean areWildcardsAllowed(URI redirectUri) {
+        // wildcars are only allowed if no user-info and no unsafe pattern in path
+        return redirectUri.getRawUserInfo() == null
+                && (redirectUri.getRawPath() == null || !UNSAFE_PATH_PATTERN.matcher(redirectUri.getRawPath()).find());
     }
 
     private static String relativeToAbsoluteURI(KeycloakSession session, String rootUrl, String relative) {
@@ -267,9 +203,16 @@
     private static String matchesRedirects(Set<String> validRedirects, String redirect, boolean allowWildcards) {
         logger.tracef("matchesRedirects: redirect URL to check: %s, allow wildcards: %b, Configured valid redirect URLs: %s", redirect, allowWildcards, validRedirects);
         for (String validRedirect : validRedirects) {
-            if (validRedirect.endsWith("*") && !validRedirect.contains("?") && allowWildcards) {
-                // strip off the query component - we don't check them when wildcards are effective
-                String r = redirect.contains("?") ? redirect.substring(0, redirect.indexOf("?")) : redirect;
+            if ("*".equals(validRedirect)) {
+                // the valid redirect * is a full wildcard for http(s) even if the redirect URI does not allow wildcards
+                return validRedirect;
+            } else if (validRedirect.endsWith("*") && !validRedirect.contains("?") && allowWildcards) {
+                // strip off the query or fragment components - we don't check them when wildcards are effective
+                int idx = redirect.indexOf('?');
+                if (idx == -1) {
+                    idx = redirect.indexOf('#');
+                }
+                String r = idx == -1 ? redirect : redirect.substring(0, idx);
                 // strip off *
                 int length = validRedirect.length() - 1;
                 validRedirect = validRedirect.substring(0, length);
@@ -299,13 +242,4 @@
         }
         return redirectUri;
     }
-
-    private static String getFirstValidRedirectUri(Collection<String> validRedirects) {
-        final String redirectUri = validRedirects.stream().findFirst().orElse(null);
-        return (redirectUri != null) ? validateRedirectUriWildcard(redirectUri) : null;
-    }
-
-    public static String getFirstValidRedirectUri(KeycloakSession session, String rootUrl, Set<String> validRedirects) {
-        return getFirstValidRedirectUri(resolveValidRedirects(session, rootUrl, validRedirects));
-    }
 }

--
Gitblit v1.10.0