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 e7240f2..0ccf69e 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
@@ -190,7 +190,7 @@ public static Document loadXML(final String xml) {
// input is whatever was posted to a service provider's assertion consumer service,
// which is anonymous, so an unauthenticated client could otherwise fill the log with
// a full trace per request.
- LOGGER.warn("Load XML error: {}", e.getMessage());
+ LOGGER.warn("Load XML error: {}", sanitizeForLog(e.getMessage()));
LOGGER.debug("Load XML error.", e);
}
@@ -271,6 +271,36 @@ public static NodeList query(final Document dom, final String query) {
return query(dom, query, null);
}
+ /** The longest piece of a message that is copied into one log line. */
+ private static final int MAX_LOGGED_LENGTH = 1000;
+
+ /**
+ * Makes text that came from a SAML message safe to write into a log line.
+ *
+ *
A service provider's assertion consumer service is anonymous, and the schema check, the
+ * algorithm check and the parser all quote what the sender wrote. A line break in an attribute or
+ * an element value would otherwise end the log record and let the sender start another one.
+ *
+ * @param value the text, which may be {@code null}
+ * @return the text with every control character, and the Unicode line and paragraph separators,
+ * replaced by a space and with a length of at most 1000 characters
+ */
+ public static String sanitizeForLog(final Object value) {
+ if (value == null) {
+ return null;
+ }
+ final String text = String.valueOf(value);
+ final StringBuilder sb = new StringBuilder(Math.min(text.length(), MAX_LOGGED_LENGTH) + 3);
+ for (int i = 0; i < text.length() && sb.length() < MAX_LOGGED_LENGTH; i++) {
+ final char c = text.charAt(i);
+ sb.append(Character.isISOControl(c) || c == '\u2028' || c == '\u2029' ? ' ' : c);
+ }
+ if (text.length() > MAX_LOGGED_LENGTH) {
+ sb.append("...");
+ }
+ return sb.toString();
+ }
+
/**
* This function attempts to validate an XML against the specified schema.
*
@@ -305,11 +335,11 @@ public static boolean validateXML(final Document xmlDocument, final URL schemaUr
final boolean isValid = !errorAccumulator.hasError();
if (!isValid) {
- LOGGER.warn("Errors found when validating SAML response with schema: {}", errorAccumulator.getErrorXML());
+ LOGGER.warn("Errors found when validating SAML response with schema: {}", sanitizeForLog(errorAccumulator.getErrorXML()));
}
return isValid;
} catch (final Exception e) {
- LOGGER.warn("SAMLSevereException executing validateXML: {}", e.getMessage(), e);
+ LOGGER.warn("SAMLSevereException executing validateXML: {}", sanitizeForLog(e.getMessage()), e);
return false;
}
}
@@ -1107,7 +1137,7 @@ private static Map getSignatureData(final Node signNode, final S
*/
public static boolean mustRejectDeprecatedSignatureAlgo(final String signAlg, final boolean rejectDeprecatedAlg) {
if (DEPRECATED_ALGOS.contains(signAlg)) {
- final String errorMsg = "Found a deprecated algorithm " + signAlg + " related to the Signature element,";
+ final String errorMsg = "Found a deprecated algorithm " + sanitizeForLog(signAlg) + " related to the Signature element,";
if (rejectDeprecatedAlg) {
LOGGER.warn("{} rejecting it", errorMsg);
return true;
@@ -1267,7 +1297,11 @@ public static void decryptElement(final Element encryptedDataElement, final Priv
xmlCipher.setKEK(inputKey);
xmlCipher.doFinal(encryptedDataElement.getOwnerDocument(), encryptedDataElement, false);
} catch (final Exception e) {
- LOGGER.warn("Failed to decrypt an element.", e);
+ // One line at warn, the trace at debug: the encrypted element is whatever was posted to a
+ // service provider's assertion consumer service, which is anonymous, so a trace per
+ // request would let an unauthenticated client fill the log.
+ LOGGER.warn("Failed to decrypt an element: {}", sanitizeForLog(e));
+ LOGGER.debug("Failed to decrypt an element.", e);
}
}
@@ -1325,7 +1359,8 @@ public static void decryptUsingHsm(final Element encryptedDataElement, final HSM
xmlCipher.setKEK(encryptionKey);
xmlCipher.doFinal(encryptedDataElement.getOwnerDocument(), encryptedDataElement, false);
} catch (final Exception e) {
- LOGGER.warn("Failed to decrypt an element using HSM.", e);
+ LOGGER.warn("Failed to decrypt an element using HSM: {}", sanitizeForLog(e));
+ LOGGER.debug("Failed to decrypt an element using HSM.", e);
}
}
@@ -1695,7 +1730,7 @@ public static boolean validateBinarySignature(final String signedQuery, final by
break;
}
} catch (final Exception e) {
- LOGGER.warn("SAMLSevereException executing validateSign: {}", e.getMessage(), e);
+ LOGGER.warn("SAMLSevereException executing validateSign: {}", sanitizeForLog(e.getMessage()), e);
}
}
return valid;
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 967d23d..bf8ae3d 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
@@ -181,6 +181,51 @@ public void testValidateXMLEncryptionMethodFromXmlEnc11() throws Exception {
assertFalse(Util.validateXML(Util.loadXML(bogus), SchemaFactory.SAML_SCHEMA_PROTOCOL_2_0));
}
+
+ /**
+ * Tests the sanitizeForLog method
+ *
+ * @see org.codelibs.saml2.core.util.Util#sanitizeForLog
+ */
+ @Test
+ public void testSanitizeForLog() {
+ assertNull(Util.sanitizeForLog(null));
+ assertEquals("plain text", Util.sanitizeForLog("plain text"));
+ assertEquals("a b c d e f g", Util.sanitizeForLog("a\nb\rc\td\u0085e\u2028f\u2029g"));
+ assertEquals("[a b]", Util.sanitizeForLog(Arrays.asList("a\nb")).replace("]", "]"));
+ String longText = String.join("", Collections.nCopies(2000, "x"));
+ String cut = Util.sanitizeForLog(longText);
+ assertEquals(1003, cut.length());
+ assertTrue(cut.endsWith("..."));
+ }
+
+ /**
+ * Tests the sanitizeForLog method
+ * Case: what the schema check quotes from a message the sender wrote
+ *
+ * @see org.codelibs.saml2.core.util.Util#validateXML
+ */
+ @Test
+ public void testSanitizeForLogOfTheErrorsTheSchemaCheckQuotes() throws Exception {
+ String response = new String(Base64.decodeBase64(Util.getFileAsString("data/responses/valid_response.xml.base64")));
+ String forged = response.replace("http://localhost:8080/java-saml-jspsample/metadata.jsp",
+ "evil\n2026-01-01 00:00:00,000 [main] ERROR FORGED");
+
+ javax.xml.validation.Validator validator = SchemaFactory.loadFromUrl(SchemaFactory.SAML_SCHEMA_PROTOCOL_2_0).newValidator();
+ org.codelibs.saml2.core.util.XMLErrorAccumulatorHandler errors = new org.codelibs.saml2.core.util.XMLErrorAccumulatorHandler();
+ validator.setErrorHandler(errors);
+ validator.validate(new javax.xml.transform.dom.DOMSource(Util.loadXML(forged)));
+
+ assertTrue(errors.hasError());
+ // the premise: the parser quotes the value, line break included
+ assertThat(String.valueOf(errors.getErrorXML()), containsString("\n2026-01-01 00:00:00,000 [main] ERROR FORGED"));
+ String logged = Util.sanitizeForLog(errors.getErrorXML());
+ assertThat(logged, containsString("ERROR FORGED"));
+ assertThat(logged, not(containsString("\n")));
+ assertThat(logged, not(containsString("\r")));
+ assertFalse(Util.validateXML(Util.loadXML(forged), SchemaFactory.SAML_SCHEMA_PROTOCOL_2_0));
+ }
+
@Test
public void testValidateXMLBadFormat() throws Exception {
String metadataUnloaded = "";