From 7c8f7992f07a99aebfdef12455c4526763b32a84 Mon Sep 17 00:00:00 2001
From: Jacek Kowalski <Jacek@jacekk.info>
Date: Sun, 23 Aug 2026 20:51:29 +0000
Subject: [PATCH] Merge RedirectUtils.java from Keycloak repo

---
 src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java |  250 +++++++++++++++++++++++--------------------------
 1 files changed, 119 insertions(+), 131 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 1cae012..ee6739c 100644
--- a/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
+++ b/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
@@ -15,44 +15,44 @@
  * limitations under the License.
  */
 
-package org.keycloak.protocol.oidc.utils;
+package org.keycloak.protocol.cas.utils;
 
-import org.jboss.logging.Logger;
-import org.keycloak.common.util.Encode;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+
 import org.keycloak.common.util.KeycloakUriBuilder;
+import org.keycloak.common.util.MultivaluedHashMap;
 import org.keycloak.common.util.UriUtils;
 import org.keycloak.models.ClientModel;
 import org.keycloak.models.Constants;
 import org.keycloak.models.KeycloakSession;
 import org.keycloak.models.KeycloakUriInfo;
 import org.keycloak.models.RealmModel;
-import org.keycloak.protocol.oidc.OIDCLoginProtocol;
+import org.keycloak.protocol.cas.CASLoginProtocol;
 import org.keycloak.services.Urls;
 import org.keycloak.services.util.ResolveRelative;
 
-import java.net.URI;
-import java.util.Collection;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
+import org.jboss.logging.Logger;
 
 /**
  * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
  */
 public class RedirectUtils {
 
-    private static final Logger logger = Logger.getLogger(RedirectUtils.class);
+    public static final Set<String> LOOPBACK_INTERFACES = new HashSet<>(Arrays.asList("localhost", "127.0.0.1", "[::1]"));
 
-    /**
-     * This method is deprecated for performance and security reasons and it is available just for the
-     * backwards compatibility. It is recommended to use some other methods of this class where the client is given as an argument
-     * to the method, so we know the client, which redirect-uri we are trying to resolve.
-     */
-    @Deprecated
-    public static String verifyRealmRedirectUri(KeycloakSession session, String redirectUri) {
-        Set<String> validRedirects = getValidateRedirectUris(session);
-        return verifyRedirectUri(session, null, redirectUri, validRedirects, true);
-    }
+    private static final Set<String> FORBIDDEN_OIDC_PARAMS = Set.of(
+            CASLoginProtocol.SAMLART_RESPONSE_PARAM.toLowerCase(Locale.ROOT),
+            CASLoginProtocol.TICKET_RESPONSE_PARAM.toLowerCase(Locale.ROOT)
+    );
+
+    private static final Logger logger = Logger.getLogger(RedirectUtils.class);
 
     public static String verifyRedirectUri(KeycloakSession session, String redirectUri, ClientModel client) {
         return verifyRedirectUri(session, redirectUri, client, true);
@@ -78,16 +78,6 @@
         return resolveValidRedirects;
     }
 
-    @Deprecated
-    private static Set<String> getValidateRedirectUris(KeycloakSession session) {
-        RealmModel realm = session.getContext().getRealm();
-        return session.clients().getAllRedirectUrisOfEnabledClients(realm).entrySet().stream()
-          .filter(me -> me.getKey().isEnabled() && OIDCLoginProtocol.LOGIN_PROTOCOL.equals(me.getKey().getProtocol()) && !me.getKey().isBearerOnly() && (me.getKey().isStandardFlowEnabled() || me.getKey().isImplicitFlowEnabled()))
-          .map(me -> resolveValidRedirects(session, me.getKey().getRootUrl(), me.getValue()))
-          .flatMap(Collection::stream)
-          .collect(Collectors.toSet());
-    }
-
     public static String verifyRedirectUri(KeycloakSession session, String rootUrl, String redirectUri, Set<String> validRedirects, boolean requireRedirectUri) {
         KeycloakUriInfo uriInfo = session.getContext().getUri();
         RealmModel realm = session.getContext().getRealm();
@@ -111,39 +101,22 @@
                 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);
-            if (decodedRedirectUri == null) return null;
-
-            String r = decodedRedirectUri;
-            Set<String> resolveValidRedirects = resolveValidRedirects(session, rootUrl, validRedirects);
-
-            String valid = matchesRedirects(resolveValidRedirects, r, true);
-
-            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());
-
-                StringBuilder sb = new StringBuilder();
-                sb.append(r.substring(0, i));
-
-                i = r.indexOf('/', i);
-                if (i >= 0) {
-                    sb.append(r.substring(i));
-                }
-
-                r = sb.toString();
-
-                valid = matchesRedirects(resolveValidRedirects, r, true);
+            // Check for HTTP Parameter Pollution - forbidden OIDC response parameters in redirect URI
+            if (containsForbiddenOidcParameters(originalRedirect)){
+                return null;
             }
 
-            // 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);
+            // check if the passed URI allows wildcards
+            boolean allowWildcards = areWildcardsAllowed(originalRedirect);
 
-            // 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);
+            String r = redirectUri;
+            Set<String> resolveValidRedirects = resolveValidRedirects(session, rootUrl, validRedirects);
+
+            String valid = matchesRedirects(resolveValidRedirects, r, allowWildcards);
+
+            if (valid == null && "http".equals(originalRedirect.getScheme()) && LOOPBACK_INTERFACES.contains(originalRedirect.getHost())) {
+                String redirectWithDefaultPort = KeycloakUriBuilder.fromUri(originalRedirect).port(80).buildAsString();
+                valid = matchesRedirects(resolveValidRedirects, redirectWithDefaultPort, allowWildcards);
             }
 
             if (valid != null && !originalRedirect.isAbsolute()) {
@@ -154,7 +127,7 @@
                 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 + ":") && !"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
@@ -173,57 +146,50 @@
         }
     }
 
+    private static boolean containsForbiddenOidcParameters(URI originalRedirect) {
+        String query = originalRedirect.getRawQuery();
+        if (query != null && !query.isEmpty()) {
+            MultivaluedHashMap<String, String> params =UriUtils.decodeQueryString(query);
+            for (String paramName : params.keySet()) {
+                if (FORBIDDEN_OIDC_PARAMS.contains(paramName.toLowerCase(Locale.ROOT))) {
+                    logger.warnf("Redirect URI rejected: contains forbidden OIDC parameter '%s' in query string: scheme=%s, host=%s, path=%s",
+                            paramName,
+                            originalRedirect.getScheme(),
+                            originalRedirect.getHost(),
+                            originalRedirect.getPath());
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
     private static URI toUri(String redirectUri) {
         URI uri = null;
         if (redirectUri != null) {
             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) {
-        String redirectUri = null;
-        if (uri != null) {
-            redirectUri = uri.normalize().toString();
-        }
-        return redirectUri;
-    }
+    // any access to parent folder /../ is unsafe with or without encoding
+    //   <sep>             = / | %2F | %5C | \
+    //   <dots>            = "..", including %2E and %252E (double-encoded) variants
+    //   <terminator>      = / | %2F | %5C | \ | ; | %3B | %09 | %0A | %0D | %00 | end-of-input
+    private final static Pattern UNSAFE_PATH_PATTERN = Pattern.compile(
+            "(/|%2[fF]|%5[cC]|\\\\)(%2[eE]|%252[eE]|\\.){2}(/|%2[fF]|%5[cC]|\\\\|;|%3[bB]|%09|%0[aAdD]|%00|$)");
 
-    // Decode redirectUri. Only path is decoded as other elements can be encoded in the original URL or cannot be encoded at all.
-    // 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();
-            if (uriBuilder.getPath() == null) {
-                return redirectUri;
-            }
-            String encodedPath = uriBuilder.getPath();
-            String decodedPath;
-
-            for (int i = 0; i < MAX_DECODING_COUNT; i++) {
-                decodedPath = Encode.decode(encodedPath);
-                if (decodedPath.equals(encodedPath)) {
-                    // URL path is decoded. We can return it in the original redirect URI
-                    return uriBuilder.replacePath(decodedPath, false).buildAsString();
-                } else {
-                    // Next attempt
-                    encodedPath = decodedPath;
-                }
-            }
-        } 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 boolean areWildcardsAllowed(URI redirectUri) {
+        // wildcars are only allowed if no user-info and no unparsed authority and no unsafe pattern in path
+        return redirectUri.getRawUserInfo() == null
+                && !(redirectUri.getRawAuthority() != null && redirectUri.getRawUserInfo() == null && redirectUri.getHost() == null && redirectUri.getPort() == -1)
+                && (redirectUri.getRawPath() == null || !UNSAFE_PATH_PATTERN.matcher(redirectUri.getRawPath()).find());
     }
 
     private static String relativeToAbsoluteURI(KeycloakSession session, String rootUrl, String relative) {
@@ -240,33 +206,64 @@
         return sb.toString();
     }
 
-    // removes the queryString, fragment and userInfo from the redirect
-    // to avoid comparing this when wildcards are used
-    private static String stripOffRedirectForWildcard(String redirect) {
-        return KeycloakUriBuilder.fromUri(redirect, false)
-                .preserveDefaultPort()
-                .userInfo(null)
-                .replaceQuery(null)
-                .fragment(null)
-                .buildAsString();
-    }
-
     // return the String that matched the redirect or null if not matched
     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 userInfo, query or fragment components - we don't check them when wildcards are effective
-                String r = stripOffRedirectForWildcard(redirect);
-                // strip off *
-                int length = validRedirect.length() - 1;
-                validRedirect = validRedirect.substring(0, length);
-                if (r.startsWith(validRedirect)) return validRedirect;
-                // strip off trailing '/'
-                if (length - 1 > 0 && validRedirect.charAt(length - 1) == '/') length--;
-                validRedirect = validRedirect.substring(0, length);
-                if (validRedirect.equals(r)) return validRedirect;
-            } else if (validRedirect.equals(redirect)) return validRedirect;
+            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 {
+                String validRedirectWildcard = allowWildcards ? checkValidRedirectWildcard(validRedirect) : null;
+                if (validRedirectWildcard != null) {
+                    // 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 = validRedirectWildcard.length() - 1;
+                    validRedirectWildcard = validRedirectWildcard.substring(0, length);
+                    if (r.startsWith(validRedirectWildcard)) {
+                        return validRedirectWildcard;
+                    }
+                    // strip off trailing '/'
+                    if (length - 1 > 0 && validRedirectWildcard.charAt(length - 1) == '/') {
+                        length--;
+                    }
+                    validRedirectWildcard = validRedirectWildcard.substring(0, length);
+                    if (validRedirectWildcard.equals(r)) {
+                        return validRedirectWildcard;
+                    }
+                } else if (validRedirect.equals(redirect)) {
+                    return validRedirect;
+                }
+            }
+        }
+        return null;
+    }
+
+    private static String checkValidRedirectWildcard(String validRedirect) {
+        if (!validRedirect.endsWith("*") || validRedirect.contains("?") || validRedirect.contains("#")) {
+            return null; // no wildcard as before
+        }
+        KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(validRedirect, false);
+        if (uriBuilder.getPath() != null) {
+            return validRedirect; // wildcard valid on path
+        }
+        if (uriBuilder.getAuthority() != null) {
+            if (uriBuilder.getAuthority().equals("*") || uriBuilder.getAuthority().endsWith(":*")) {
+                return validRedirect; // on authority just full wildcard or on port
+            } else {
+                // treat the wildcard after the authority
+                validRedirect = validRedirect.substring(0, validRedirect.length() - 1);
+                validRedirect = validRedirect + "/*";
+                return validRedirect;
+            }
+        }
+        if (uriBuilder.getSsp() != null) {
+            return validRedirect; // wildcard valid on SSP
         }
         return null;
     }
@@ -287,13 +284,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