Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;

Expand All @@ -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);
Expand All @@ -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.
*
Expand Down
30 changes: 20 additions & 10 deletions core/src/main/java/org/codelibs/saml2/core/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -1012,7 +1014,8 @@ public static boolean validateSign(final Document doc, final List<X509Certificat
}
}
} 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;
}
Expand Down Expand Up @@ -1076,7 +1079,8 @@ public static boolean validateMetadataSign(final Document doc, final X509Certifi
return true;
}
} 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;
}
Expand Down Expand Up @@ -1123,7 +1127,8 @@ private static Map<String, Object> 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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "<ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:SignedInfo>"
+ "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>"
+ "<ds:SignatureMethod Algorithm=\"" + forgedAlgorithm.replace("\n", "&#10;") + "\"/>"
+ "<ds:Reference URI=\"#a1\"><ds:DigestMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#sha256\"/>"
+ "<ds:DigestValue>AAAA</ds:DigestValue></ds:Reference></ds:SignedInfo>"
+ "<ds:SignatureValue>AAAA</ds:SignatureValue></ds:Signature>";
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 = "<xml><EntityDescriptor>";
Expand Down
Loading