From fc40907a5866310f620d22c7f76ba5c148fafc07 Mon Sep 17 00:00:00 2001
From: Jacek Kowalski <Jacek@jacekk.info>
Date: Tue, 03 Nov 2026 21:04:42 +0000
Subject: [PATCH] Return CAS error instead of HTTP 500 on malformed tickets

---
 src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java |   15 +++++++++++----
 1 files changed, 11 insertions(+), 4 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 422c760..c517572 100644
--- a/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
+++ b/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
@@ -186,8 +186,6 @@
             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)) {
             event.error(Errors.SESSION_EXPIRED);
             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Interactive authentication was requested but not performed", Response.Status.BAD_REQUEST);
@@ -226,6 +224,10 @@
             throw new CASValidationException(CASErrorCode.INVALID_TICKET, "Session not active", Response.Status.BAD_REQUEST);
         }
 
+        // Single logout refers to the service ticket the client session was established with
+        if (prefix.equals(CASLoginProtocol.SERVICE_TICKET_PREFIX)) {
+            clientSession.setNote(CASLoginProtocol.SESSION_TICKET, ticket);
+        }
     }
 
     protected void createProxyGrant(String pgtUrl) {
@@ -328,7 +330,12 @@
     }
 
     private String hexDecode(String hex) {
-        byte[] bytes = HexFormat.of().parseHex(hex);
-        return new String(bytes, StandardCharsets.US_ASCII);
+        try {
+            byte[] bytes = HexFormat.of().parseHex(hex);
+            return new String(bytes, StandardCharsets.US_ASCII);
+        } catch (IllegalArgumentException e) {
+            event.error(Errors.INVALID_CODE);
+            throw new CASValidationException(CASErrorCode.INVALID_TICKET_SPEC, "Invalid format of the code", Response.Status.BAD_REQUEST);
+        }
     }
 }

--
Gitblit v1.10.0