From 25f78f2c9f9e6985630cb06037b0fa996a9a1a79 Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sun, 15 Nov 2026 20:31:42 +0900 Subject: [PATCH 1/2] fix: keep an unsigned logout message from starting a log line or filling the replay cache An unsigned LogoutRequest or LogoutResponse is accepted from anyone, so the sender controls every value in it. - LogoutRequest and LogoutResponse logged the validation message as it was. The message quotes the Issuer text and other values, so a line break in an Issuer started a new record of the log. Log it through Util.sanitizeForLog, as Util already does for the other warnings. - The ID of every message that passes validation is kept in the replay cache for the validity window, signed or not. With no limit on its length, one small deflated request could pin an ID of about 100 KB. The in-memory cache now keeps an ID longer than 128 characters as its SHA-256 digest, so replay detection is unchanged and an entry costs a digest at most. --- .../saml2/core/logout/LogoutRequest.java | 3 +- .../saml2/core/logout/LogoutResponse.java | 3 +- .../core/replay/InMemoryReplayCache.java | 29 ++++++++++++++++++- .../test/replay/InMemoryReplayCacheTest.java | 27 +++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/org/codelibs/saml2/core/logout/LogoutRequest.java b/core/src/main/java/org/codelibs/saml2/core/logout/LogoutRequest.java index 9d98663..c4b1c59 100644 --- a/core/src/main/java/org/codelibs/saml2/core/logout/LogoutRequest.java +++ b/core/src/main/java/org/codelibs/saml2/core/logout/LogoutRequest.java @@ -542,7 +542,8 @@ public boolean isValid() { } catch (final Exception e) { validationException = e; LOGGER.debug("LogoutRequest invalid --> {}", logoutRequestString, e); - LOGGER.warn(validationException.getMessage()); + // the message quotes values the sender wrote (Issuer, Destination, the ID) + LOGGER.warn("{}", Util.sanitizeForLog(validationException.getMessage())); return false; } } diff --git a/core/src/main/java/org/codelibs/saml2/core/logout/LogoutResponse.java b/core/src/main/java/org/codelibs/saml2/core/logout/LogoutResponse.java index b7f987e..40577a5 100644 --- a/core/src/main/java/org/codelibs/saml2/core/logout/LogoutResponse.java +++ b/core/src/main/java/org/codelibs/saml2/core/logout/LogoutResponse.java @@ -303,7 +303,8 @@ public boolean isValid(final String requestId) { } catch (final Exception e) { validationException = e; LOGGER.debug("LogoutResponse invalid --> {}", logoutResponseString, e); - LOGGER.warn(validationException.getMessage()); + // the message quotes values the sender wrote (Issuer, Destination, the ID) + LOGGER.warn("{}", Util.sanitizeForLog(validationException.getMessage())); return false; } } diff --git a/core/src/main/java/org/codelibs/saml2/core/replay/InMemoryReplayCache.java b/core/src/main/java/org/codelibs/saml2/core/replay/InMemoryReplayCache.java index 1c8071c..01158a4 100644 --- a/core/src/main/java/org/codelibs/saml2/core/replay/InMemoryReplayCache.java +++ b/core/src/main/java/org/codelibs/saml2/core/replay/InMemoryReplayCache.java @@ -1,6 +1,10 @@ package org.codelibs.saml2.core.replay; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.HexFormat; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @@ -12,6 +16,9 @@ */ public class InMemoryReplayCache implements ReplayCache { + /** IDs longer than this are kept as their SHA-256 digest, so an entry never costs more than a digest. */ + private static final int MAX_KEY_LENGTH = 128; + /** Number of registrations between opportunistic sweeps of expired entries. */ private static final long SWEEP_INTERVAL = 1000L; @@ -33,8 +40,9 @@ public InMemoryReplayCache() { public boolean registerAndCheck(final String id, final Instant expiresAt) { final Instant now = Instant.now(); final AtomicBoolean replay = new AtomicBoolean(false); + final String entryKey = toKey(id); - entries.compute(id, (key, previousExpiresAt) -> { + entries.compute(entryKey, (key, previousExpiresAt) -> { if (previousExpiresAt != null && previousExpiresAt.isAfter(now)) { // Still-valid previous entry: this is a replay, keep the existing expiry. replay.set(true); @@ -52,6 +60,25 @@ public boolean registerAndCheck(final String id, final Instant expiresAt) { return replay.get(); } + /** + * Returns the key an ID is stored under. The ID of an unsigned message is whatever the sender wrote, + * and the cache keeps it for the whole validity window, so a long ID is replaced by its digest. + * + * @param id the ID of the message + * @return the ID itself when it is short, otherwise the hex SHA-256 digest of it + */ + private static String toKey(final String id) { + if (id.length() <= MAX_KEY_LENGTH) { + return id; + } + try { + final byte[] digest = MessageDigest.getInstance("SHA-256").digest(id.getBytes(StandardCharsets.UTF_8)); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (final NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available.", e); + } + } + /** * Opportunistically removes entries whose expiry is not after the given instant. * diff --git a/core/src/test/java/org/codelibs/saml2/core/test/replay/InMemoryReplayCacheTest.java b/core/src/test/java/org/codelibs/saml2/core/test/replay/InMemoryReplayCacheTest.java index d26af82..6ae0b4e 100644 --- a/core/src/test/java/org/codelibs/saml2/core/test/replay/InMemoryReplayCacheTest.java +++ b/core/src/test/java/org/codelibs/saml2/core/test/replay/InMemoryReplayCacheTest.java @@ -109,4 +109,31 @@ public void testConcurrentRegistrationSmoke() throws InterruptedException { assertEquals(1, firstUseCount.get()); } + /** + * Tests the registerAndCheck method of InMemoryReplayCache + * Case: a very long id (the id of an unsigned message is whatever the sender wrote) is still + * detected as a replay, two long ids with the same beginning are not mixed up, and the cache + * does not keep the id itself + * + * @throws Exception if the entries cannot be read + * @see org.codelibs.saml2.core.replay.InMemoryReplayCache#registerAndCheck + */ + @Test + public void testLongIdIsKeptAsDigest() throws Exception { + final InMemoryReplayCache cache = new InMemoryReplayCache(); + final Instant expiresAt = Instant.now().plusSeconds(300); + final String prefix = "_" + "a".repeat(100000); + + assertFalse(cache.registerAndCheck(prefix + "1", expiresAt)); + assertTrue(cache.registerAndCheck(prefix + "1", expiresAt)); + assertFalse(cache.registerAndCheck(prefix + "2", expiresAt)); + + final java.lang.reflect.Field field = InMemoryReplayCache.class.getDeclaredField("entries"); + field.setAccessible(true); + final java.util.Map entries = (java.util.Map) field.get(cache); + assertEquals(2, entries.size()); + for (final Object key : entries.keySet()) { + assertTrue(((String) key).length() < 128); + } + } } From 94e357ce19b21cadb3bc5305d342f29165a0a21f Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sun, 15 Nov 2026 23:04:55 +0900 Subject: [PATCH 2/2] fix: keep the exception of a failed signature check from starting a log line The signature helpers in Util logged the caught exception as the throwable argument of a WARN call. The XML security library quotes the SignatureMethod algorithm URI of the message in the exception text, an xs:anyURI accepts a line break, and the default layout prints the throwable text as it is, so an unauthenticated sender could start a new line of the log from the assertion consumer service. Log the exception through sanitizeForLog at WARN and keep the stack trace at DEBUG, as the decryption helpers already do. The same change applies to the other helpers that logged a caught exception at WARN, and to getExpireTime, which logged the message of a DateTimeParseException quoting its input at ERROR. --- .../org/codelibs/saml2/core/util/Util.java | 30 +++++++++++------ .../saml2/core/test/util/UtilsTest.java | 33 +++++++++++++++++++ 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/org/codelibs/saml2/core/util/Util.java b/core/src/main/java/org/codelibs/saml2/core/util/Util.java index 0ccf69e..7f2268f 100644 --- a/core/src/main/java/org/codelibs/saml2/core/util/Util.java +++ b/core/src/main/java/org/codelibs/saml2/core/util/Util.java @@ -339,7 +339,8 @@ public static boolean validateXML(final Document xmlDocument, final URL schemaUr } return isValid; } catch (final Exception e) { - LOGGER.warn("SAMLSevereException executing validateXML: {}", sanitizeForLog(e.getMessage()), e); + LOGGER.warn("SAMLSevereException executing validateXML: {}", sanitizeForLog(e.getMessage())); + LOGGER.debug("SAMLSevereException executing validateXML", e); return false; } } @@ -941,7 +942,8 @@ public static boolean validateSign(final Document doc, final X509Certificate cer final NodeList signatures = query(doc, xpath); return signatures.getLength() == 1 && validateSignNode(signatures.item(0), cert, fingerprint, alg); } catch (final Exception e) { - LOGGER.warn("Failed to find signature nodes", e); + LOGGER.warn("Failed to find signature nodes: {}", sanitizeForLog(e)); + LOGGER.debug("Failed to find signature nodes", e); } return false; } @@ -1012,7 +1014,8 @@ public static boolean validateSign(final Document doc, final List getSignatureData(final Node signNode, final S LOGGER.debug("No KeyInfo or not x509CertificateData"); } } catch (final Exception e) { - LOGGER.warn("Cannot get a signature data.", e); + LOGGER.warn("Cannot get a signature data: {}", sanitizeForLog(e)); + LOGGER.debug("Cannot get a signature data", e); } return signatureData; } @@ -1235,7 +1240,8 @@ public static boolean validateSignNode(final XMLSignature signature, final X509C } } } catch (final Exception e) { - LOGGER.warn("Failed to validate a sign node.", e); + LOGGER.warn("Failed to validate a sign node: {}", sanitizeForLog(e)); + LOGGER.debug("Failed to validate a sign node", e); } return res; } @@ -1693,7 +1699,8 @@ public static boolean validateBinarySignature(final String signedQuery, final by valid = sig.verify(signature); } catch (final Exception e) { - LOGGER.warn("Failed to validate a binary signature.", e); + LOGGER.warn("Failed to validate a binary signature: {}", sanitizeForLog(e)); + LOGGER.debug("Failed to validate a binary signature", e); } return valid; } @@ -1730,7 +1737,8 @@ public static boolean validateBinarySignature(final String signedQuery, final by break; } } catch (final Exception e) { - LOGGER.warn("SAMLSevereException executing validateSign: {}", sanitizeForLog(e.getMessage()), e); + LOGGER.warn("SAMLSevereException executing validateSign: {}", sanitizeForLog(e.getMessage())); + LOGGER.debug("SAMLSevereException executing validateSign", e); } } return valid; @@ -2051,7 +2059,8 @@ public static long getExpireTime(final String cacheDuration, final String validU } } } catch (final Exception e) { - LOGGER.error("SAMLSevereException executing getExpireTime: {}", e.getMessage(), e); + LOGGER.error("SAMLSevereException executing getExpireTime: {}", sanitizeForLog(e.getMessage())); + LOGGER.debug("SAMLSevereException executing getExpireTime", e); } return expireTime; } @@ -2077,7 +2086,8 @@ public static long getExpireTime(final String cacheDuration, final long validUnt expireTime = validUntil; } } catch (final Exception e) { - LOGGER.error("SAMLSevereException executing getExpireTime: {}", e.getMessage(), e); + LOGGER.error("SAMLSevereException executing getExpireTime: {}", sanitizeForLog(e.getMessage())); + LOGGER.debug("SAMLSevereException executing getExpireTime", e); } return expireTime; } diff --git a/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java b/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java index bf8ae3d..b884845 100644 --- a/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java +++ b/core/src/test/java/org/codelibs/saml2/core/test/util/UtilsTest.java @@ -226,6 +226,39 @@ public void testSanitizeForLogOfTheErrorsTheSchemaCheckQuotes() throws Exception assertFalse(Util.validateXML(Util.loadXML(forged), SchemaFactory.SAML_SCHEMA_PROTOCOL_2_0)); } + /** + * Tests the sanitizeForLog method + * Case: the signature algorithm URI the sender wrote is quoted by the XML security library + * + * @see org.codelibs.saml2.core.util.Util#validateSignNode + */ + @Test + public void testSanitizeForLogOfTheSignatureAlgorithmTheSecurityLibraryQuotes() throws Exception { + String forgedAlgorithm = "http://example.com/x\n2026-01-01 00:00:00,000 main ERROR FORGED"; + String xml = "" + + "" + + "" + + "" + + "AAAA" + + "AAAA"; + org.w3c.dom.Element signature = Util.loadXML(xml).getDocumentElement(); + + // the premise: the library quotes the algorithm, line break included + try { + new org.apache.xml.security.signature.XMLSignature(signature, "", true).getSignedInfo().getSignatureMethodURI(); + org.junit.Assert.fail("the library should refuse an unknown signature algorithm"); + } catch (XMLSecurityException e) { + assertThat(String.valueOf(e), containsString("\n2026-01-01 00:00:00,000 main ERROR FORGED")); + String logged = Util.sanitizeForLog(e); + assertThat(logged, containsString("ERROR FORGED")); + assertThat(logged, not(containsString("\n"))); + assertThat(logged, not(containsString("\r"))); + } + + // the refusal itself is unchanged: no data, no exception + assertFalse(Util.validateSignNode(signature, null, "00", "sha256")); + } + @Test public void testValidateXMLBadFormat() throws Exception { String metadataUnloaded = "";