From 760bd7b814836fca58922151abe67207cc0db1a2 Mon Sep 17 00:00:00 2001
From: Ricardo Martin <rmartinc@redhat.com>
Date: Tue, 09 Jan 2024 07:20:14 +0000
Subject: [PATCH] Escape action in the form_post.jwt and only decode path in RedirectUtils (#93) (#25995)

---
 src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java |  159 +++++++++++++++++++++++++++++++++--------------------
 1 files changed, 99 insertions(+), 60 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 9cb314b..1cae012 100644
--- a/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
+++ b/src/main/java/org/keycloak/protocol/cas/utils/RedirectUtils.java
@@ -32,8 +32,8 @@
 
 import java.net.URI;
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.Set;
+import java.util.TreeSet;
 import java.util.stream.Collectors;
 
 /**
@@ -66,15 +66,14 @@
 
     public static Set<String> resolveValidRedirects(KeycloakSession session, String rootUrl, Set<String> validRedirects) {
         // If the valid redirect URI is relative (no scheme, host, port) then use the request's scheme, host, and port
-        Set<String> resolveValidRedirects = new HashSet<>();
+        // the set is ordered by length to get the longest match first
+        Set<String> resolveValidRedirects = new TreeSet<>((String s1, String s2) -> s1.length() == s2.length()? s1.compareTo(s2) : s1.length() < s2.length()? 1 : -1);
         for (String validRedirect : validRedirects) {
             if (validRedirect.startsWith("/")) {
                 validRedirect = relativeToAbsoluteURI(session, rootUrl, validRedirect);
                 logger.debugv("replacing relative valid redirect with: {0}", validRedirect);
-                resolveValidRedirects.add(validRedirect);
-            } else {
-                resolveValidRedirects.add(validRedirect);
             }
+            resolveValidRedirects.add(validRedirect);
         }
         return resolveValidRedirects;
     }
@@ -93,20 +92,6 @@
         KeycloakUriInfo uriInfo = session.getContext().getUri();
         RealmModel realm = session.getContext().getRealm();
 
-        redirectUri = decodeRedirectUri(redirectUri);
-        if (redirectUri != null) {
-            try {
-                URI uri = URI.create(redirectUri);
-                redirectUri = uri.normalize().toString();
-            } catch (IllegalArgumentException cause) {
-                logger.debug("Invalid redirect uri", cause);
-                return null;
-            } catch (Exception cause) {
-                logger.debug("Unexpected error when parsing redirect uri", cause);
-                return null;
-            }
-        }
-
         if (redirectUri == null) {
             if (!requireRedirectUri) {
                 redirectUri = getSingleValidRedirectUri(validRedirects);
@@ -120,14 +105,24 @@
             logger.debug("No Redirect URIs supplied");
             redirectUri = null;
         } else {
-            redirectUri = lowerCaseHostname(redirectUri);
+            URI originalRedirect = toUri(redirectUri);
+            if (originalRedirect == null) {
+                // invalid URI passed as redirectUri
+                return null;
+            }
 
-            String r = redirectUri;
+            // 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);
 
-            boolean valid = matchesRedirects(resolveValidRedirects, r);
+            String valid = matchesRedirects(resolveValidRedirects, r, true);
 
-            if (!valid && (r.startsWith(Constants.INSTALLED_APP_URL) || r.startsWith(Constants.INSTALLED_APP_LOOPBACK)) && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) {
+            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();
@@ -140,12 +135,35 @@
 
                 r = sb.toString();
 
-                valid = matchesRedirects(resolveValidRedirects, r);
+                valid = matchesRedirects(resolveValidRedirects, r, true);
             }
-            if (valid && redirectUri.startsWith("/")) {
+
+            // 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);
+
+            // 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);
+            }
+
+            if (valid != null && !originalRedirect.isAbsolute()) {
+                // return absolute if the original URI is relative
+                if (!redirectUri.startsWith("/")) {
+                    redirectUri = "/" + redirectUri;
+                }
                 redirectUri = relativeToAbsoluteURI(session, rootUrl, redirectUri);
             }
-            redirectUri = valid ? redirectUri : null;
+
+            String scheme = decodedRedirect.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)) {
+                    logger.debugf("Invalid URI because scheme is not allowed: %s", redirectUri);
+                    valid = null;
+                }
+            }
+
+            redirectUri = valid != null ? redirectUri : null;
         }
 
         if (Constants.INSTALLED_APP_URN.equals(redirectUri)) {
@@ -155,33 +173,50 @@
         }
     }
 
-    // Decode redirectUri. We don't decode query and fragment as those can be encoded in the original URL.
+    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);
+            } catch (Exception cause) {
+                logger.debug("Unexpected error when parsing redirect uri", cause);
+            }
+        }
+        return uri;
+    }
+
+    private static String getNormalizedRedirectUri(URI uri) {
+        String redirectUri = null;
+        if (uri != null) {
+            redirectUri = uri.normalize().toString();
+        }
+        return redirectUri;
+    }
+
+    // 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);
-            String origQuery = uriBuilder.getQuery();
-            String origFragment = uriBuilder.getFragment();
-            String encodedRedirectUri = uriBuilder
-                    .replaceQuery(null)
-                    .fragment(null)
-                    .buildAsString();
-            String decodedRedirectUri = null;
+            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++) {
-                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)
-                            .replaceQuery(origQuery)
-                            .fragment(origFragment)
-                            .buildAsString();
+                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
-                    encodedRedirectUri = decodedRedirectUri;
+                    encodedPath = decodedPath;
                 }
             }
         } catch (IllegalArgumentException iae) {
@@ -191,15 +226,6 @@
         return null;
     }
 
-    private static String lowerCaseHostname(String redirectUri) {
-        int n = redirectUri.indexOf('/', 7);
-        if (n == -1) {
-            return redirectUri.toLowerCase();
-        } else {
-            return redirectUri.substring(0, n).toLowerCase() + redirectUri.substring(n);
-        }
-    }
-
     private static String relativeToAbsoluteURI(KeycloakSession session, String rootUrl, String relative) {
         if (rootUrl != null) {
             rootUrl = ResolveRelative.resolveRootUrl(session, rootUrl);
@@ -214,22 +240,35 @@
         return sb.toString();
     }
 
-    private static boolean matchesRedirects(Set<String> validRedirects, String redirect) {
+    // 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("?")) {
-                // 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 (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 true;
+                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 true;
-            } else if (validRedirect.equals(redirect)) return true;
+                if (validRedirect.equals(r)) return validRedirect;
+            } else if (validRedirect.equals(redirect)) return validRedirect;
         }
-        return false;
+        return null;
     }
 
     private static String getSingleValidRedirectUri(Collection<String> validRedirects) {

--
Gitblit v1.10.0