From 3c9bdbd63e0f335e2aa17f640c3afdfa8d541a9a Mon Sep 17 00:00:00 2001
From: Jacek Kowalski <Jacek@jacekk.info>
Date: Tue, 03 Nov 2026 20:58:49 +0000
Subject: [PATCH] Verify target service when issuing proxy tickets

---
 src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java |   61 +++++++++++++++++++++++++-----
 1 files changed, 50 insertions(+), 11 deletions(-)

diff --git a/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java b/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
index 54f05ca..afc9c2c 100644
--- a/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
+++ b/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
@@ -12,14 +12,17 @@
 import org.keycloak.protocol.cas.mappers.CASAttributeMapper;
 import org.keycloak.protocol.cas.representations.CASErrorCode;
 import org.keycloak.protocol.cas.utils.CASValidationException;
+import org.keycloak.protocol.cas.utils.RedirectUtils;
 import org.keycloak.protocol.oidc.utils.OAuth2Code;
-import org.keycloak.protocol.oidc.utils.RedirectUtils;
 import org.keycloak.services.managers.AuthenticationManager;
 import org.keycloak.services.managers.UserSessionCrossDCManager;
 import org.keycloak.services.util.DefaultClientSessionContext;
 
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
+import java.util.HexFormat;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.UUID;
 import java.util.regex.Pattern;
@@ -32,10 +35,12 @@
 public abstract class AbstractValidateEndpoint {
     protected final Logger logger = Logger.getLogger(getClass());
     private static final Pattern DOT = Pattern.compile("\\.");
+    private static final Pattern SEPERATION_PATTERN = Pattern.compile("--");
     protected KeycloakSession session;
     protected RealmModel realm;
     protected EventBuilder event;
     protected ClientModel client;
+    protected String service;
     protected AuthenticatedClientSessionModel clientSession;
     protected String pgtIou;
 
@@ -65,10 +70,7 @@
 
         event.detail(Details.REDIRECT_URI, service);
 
-        client = realm.getClientsStream()
-                .filter(c -> CASLoginProtocol.LOGIN_PROTOCOL.equals(c.getProtocol()))
-                .filter(c -> RedirectUtils.verifyRedirectUri(session, service, c) != null)
-                .findFirst().orElse(null);
+        client = findClient(service);
         if (client == null) {
             event.error(Errors.CLIENT_NOT_FOUND);
             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Client not found", Response.Status.BAD_REQUEST);
@@ -79,11 +81,20 @@
             throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Client disabled", Response.Status.BAD_REQUEST);
         }
 
+        this.service = RedirectUtils.verifyRedirectUri(session, service, client);
+
         event.client(client.getClientId());
 
         session.getContext().setClient(client);
     }
 
+    protected ClientModel findClient(String service) {
+        return realm.getClientsStream()
+                .filter(c -> CASLoginProtocol.LOGIN_PROTOCOL.equals(c.getProtocol()))
+                .filter(c -> RedirectUtils.verifyRedirectUri(session, service, c) != null)
+                .findFirst().orElse(null);
+    }
+
     protected void checkTicket(String ticket, String prefix, boolean requireReauth) {
         if (ticket == null) {
             event.error(Errors.INVALID_CODE);
@@ -95,16 +106,23 @@
             throw new CASValidationException(CASErrorCode.INVALID_TICKET_SPEC, "Malformed service ticket", Response.Status.BAD_REQUEST);
         }
 
-        boolean isReusable = ticket.startsWith(CASLoginProtocol.PROXY_GRANTING_TICKET_PREFIX);
+        String ticketValue = ticket.substring(prefix.length());
 
-        String[] parsed = DOT.split(ticket.substring(prefix.length()), 3);
+        boolean isReusable = ticket.startsWith(CASLoginProtocol.PROXY_GRANTING_TICKET_PREFIX);
+        // Check if the ticket is hex encoded or using old method
+        String[] parsed;
+        if (ticketValue.contains(".")) {
+            parsed = DOT.split(ticketValue, 3);
+        } else {
+            parsed = SEPERATION_PATTERN.split(ticketValue, 3);
+        }
         if (parsed.length != 3) {
             event.error(Errors.INVALID_CODE);
             throw new CASValidationException(CASErrorCode.INVALID_TICKET_SPEC, "Invalid format of the code", Response.Status.BAD_REQUEST);
         }
 
         String codeUUID = parsed[0];
-        String userSessionId = parsed[1];
+        String userSessionId = ticketValue.contains(".") ? parsed[1] : hexDecode(parsed[1]);
         String clientUUID = parsed[2];
 
         event.detail(Details.CODE_ID, userSessionId);
@@ -151,6 +169,12 @@
             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Code is expired", Response.Status.BAD_REQUEST);
         }
 
+        // Service and proxy tickets are valid only for the service they were issued for
+        if (!isReusable && (service == null || !service.equals(codeData.getRedirectUriParam()))) {
+            event.error(Errors.INVALID_REDIRECT_URI);
+            throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Ticket was not issued for this service", Response.Status.BAD_REQUEST);
+        }
+
         clientSession.setNote(CASLoginProtocol.SESSION_TICKET, ticket);
 
         if (requireReauth && AuthenticationManager.isSSOAuthentication(clientSession)) {
@@ -173,13 +197,19 @@
 
         if (client == null) {
             client = clientSession.getClient();
-        } else {
+        } else if (!prefix.equals(CASLoginProtocol.PROXY_TICKET_PREFIX)) {
+            // Proxy tickets are issued from the proxying client's session for a (possibly) different target service
             if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
                 event.error(Errors.INVALID_CODE);
                 throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Invalid service", Response.Status.BAD_REQUEST);
             }
         }
 
+        if (codeData.getClientUUID() != null && !codeData.getClientUUID().equals(clientUUID)) {
+            event.error(Errors.INVALID_CODE);
+            throw new CASValidationException(CASErrorCode.INVALID_SERVICE, "Invalid client", Response.Status.BAD_REQUEST);
+        }
+
         if (!AuthenticationManager.isSessionValid(realm, userSession)) {
             event.error(Errors.USER_SESSION_NOT_FOUND);
             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
@@ -260,8 +290,17 @@
     {
         String key = UUID.randomUUID().toString();
         UserSessionModel userSession = clientSession.getUserSession();
-        OAuth2Code codeData = new OAuth2Code(key, Time.currentTime() + userSession.getRealm().getAccessCodeLifespan(), null, null, redirectUriParam, null, null, userSession.getId());
+        OAuth2Code codeData = new OAuth2Code(key, clientSession.getClient().getId(), Time.currentTime() + userSession.getRealm().getAccessCodeLifespan(), null, null, null, redirectUriParam, null, null, null, userSession.getId());
         session.singleUseObjects().put(prefix + key, clientSession.getUserSession().getRealm().getAccessCodeLifespan(), codeData.serializeCode());
-        return prefix + key + "." + clientSession.getUserSession().getId() + "." + clientSession.getClient().getId();
+        return prefix + key + "--" + hexEncode(clientSession.getUserSession().getId()) + "--" + clientSession.getClient().getId();
+    }
+
+    private String hexEncode(String value) {
+        return HexFormat.of().formatHex(value.getBytes(StandardCharsets.US_ASCII));
+    }
+
+    private String hexDecode(String hex) {
+        byte[] bytes = HexFormat.of().parseHex(hex);
+        return new String(bytes, StandardCharsets.US_ASCII);
     }
 }

--
Gitblit v1.10.0