This is an automated email from the ASF dual-hosted git repository. coheigea pushed a commit to branch coheigea/signed-cache in repository https://gitbox.apache.org/repos/asf/ws-wss4j.git
commit 05fd27b1b38cd664c01ae2220ed58ec66936fcc7 Author: Colm O hEigeartaigh <[email protected]> AuthorDate: Mon Nov 9 07:41:58 2026 +0000 Don't key the signature replay cache on the SignatureValue --- .../wss4j/dom/processor/SignatureProcessor.java | 43 ++++++----- .../org/apache/wss4j/dom/message/ReplayTest.java | 83 ++++++++++++++++++++++ .../WSSSignatureReferenceVerifyInputProcessor.java | 24 +++++-- 3 files changed, 127 insertions(+), 23 deletions(-) diff --git a/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java b/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java index c3672467b..72bd05b53 100644 --- a/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java +++ b/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java @@ -407,7 +407,7 @@ public class SignatureProcessor implements Processor { // Test for replay attacks ReplayCacheEntry replayCacheEntry = - testMessageReplay(elem, xmlSignature.getSignatureValue().getValue(), key, data, wsDocInfo); + testMessageReplay(elem, xmlSignature.getSignedInfo(), key, data, wsDocInfo); setElementsOnContext(xmlSignature, (DOMValidateContext)context, data, wsDocInfo); @@ -727,10 +727,10 @@ public class SignatureProcessor implements Processor { } /** - * Test for a replayed message. The cache key is the Timestamp Created value, the signature - * value, and the encoded value of the signing key. + * Test for a replayed message. The cache key is the Timestamp Created value, the References + * of the SignedInfo, and the encoded value of the signing key. * @param signatureElement - * @param signatureValue + * @param signedInfo * @param key * @param requestData * @param wsDocInfo @@ -740,7 +740,7 @@ public class SignatureProcessor implements Processor { */ private ReplayCacheEntry testMessageReplay( Element signatureElement, - byte[] signatureValue, + SignedInfo signedInfo, Key key, RequestData requestData, WSDocInfo wsDocInfo @@ -773,8 +773,10 @@ public class SignatureProcessor implements Processor { } // Test for replay attacks. The identifier is a digest over the full Timestamp Created - // value, signature value and encoded signing key, rather than over the 32-bit hashCodes - // of the latter two, which are trivially collidable. + // value, the References of the SignedInfo and the encoded signing key. The SignatureValue + // is not used: it is not covered by the signature, and for ECDSA and DSA a second valid + // value can be computed from the first without the key, which would give a replayed + // message a new identifier. // // The parsed Created value is used rather than the raw element text, so that two Created // Strings denoting the same instant - a trailing ".000", or a "+00:00" offset written in @@ -783,7 +785,7 @@ public class SignatureProcessor implements Processor { // otherwise be enough to slip a replayed message past the cache. Instant created = timeStamp.getCreated(); String identifier = - createIdentifier(created != null ? created.toString() : "", signatureValue, key); + createIdentifier(created != null ? created.toString() : "", signedInfo, key); if (replayCache.contains(identifier)) { throw new WSSecurityException( @@ -800,19 +802,26 @@ public class SignatureProcessor implements Processor { } /** - * Create the replay cache identifier for the given Timestamp Created value, signature value - * and signing key. The values are separated by a '|', which can appear in neither a Created - * value nor Base64, so that they cannot run together into an ambiguous identifier. + * Create the replay cache identifier for the given Timestamp Created value, the URI and + * DigestValue of each Reference of the SignedInfo, and the signing key. The values are + * separated by a '|', which can appear in neither a Created value nor Base64, so that they + * cannot run together into an ambiguous identifier. */ private static String createIdentifier( - String createdString, byte[] signatureValue, Key key + String createdString, SignedInfo signedInfo, Key key ) throws WSSecurityException { + StringBuilder identifierBuilder = new StringBuilder(createdString); + for (Object referenceObject : signedInfo.getReferences()) { + Reference reference = (Reference)referenceObject; + String uri = reference.getURI(); + identifierBuilder.append('|') + .append(encode(uri != null ? uri.getBytes(StandardCharsets.UTF_8) : null)) + .append('|') + .append(encode(reference.getDigestValue())); + } // getEncoded() returns null for a key whose material cannot be extracted, for example one - // held in a hardware token. The signature value alone still identifies the message then. - byte[] keyBytes = key.getEncoded(); - String identifier = createdString - + "|" + encode(signatureValue) - + "|" + encode(keyBytes); + // held in a hardware token. The References alone still identify the message then. + String identifier = identifierBuilder.append('|').append(encode(key.getEncoded())).toString(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java b/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java index 158c15369..f37a9f43f 100644 --- a/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java +++ b/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java @@ -20,9 +20,13 @@ package org.apache.wss4j.dom.message; import java.io.IOException; +import java.math.BigInteger; import java.nio.file.Path; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPublicKey; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Base64; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -43,6 +47,7 @@ import org.apache.wss4j.common.cache.MemoryReplayCache; import org.apache.wss4j.common.cache.ReplayCache; import org.apache.wss4j.common.crypto.Crypto; import org.apache.wss4j.common.crypto.CryptoFactory; +import org.apache.wss4j.common.crypto.CryptoType; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.saml.SAMLCallback; import org.apache.wss4j.common.saml.SAMLUtil; @@ -62,6 +67,7 @@ import org.w3c.dom.Element; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -216,6 +222,83 @@ public class ReplayTest { * rejected as one. Where the Signature does not cover the Timestamp - as here, only the SOAP * Body is signed - that rewriting costs an attacker nothing. */ + /** + * An ECDSA SignatureValue (r, s) can be rewritten as (r, n - s), where n is the order of the + * curve, without the private key, and still verifies. A replayed message rewritten that way + * must still be detected, so the replay cache must not be keyed on the SignatureValue. + */ + @Test + public void testReplayedTimestampRewrittenECDSASignatureValue() throws Exception { + Crypto ecCrypto = CryptoFactory.getInstance("wss40.properties"); + + Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); + WSSecHeader secHeader = new WSSecHeader(doc); + secHeader.insertSecurityHeader(); + + WSSecTimestamp timestamp = new WSSecTimestamp(secHeader); + timestamp.setTimeToLive(300); + Document createdDoc = timestamp.build(); + + WSSecSignature builder = new WSSecSignature(secHeader); + builder.setUserInfo("wss40ec", "security"); + builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); + builder.setSignatureAlgorithm(WSConstants.ECDSA_SHA256); + builder.getParts().add(new WSEncryptionPart("Timestamp", WSConstants.WSU_NS, "")); + builder.prepare(ecCrypto); + List<javax.xml.crypto.dsig.Reference> referenceList = + builder.addReferencesToSign(builder.getParts()); + builder.computeSignature(referenceList, false, null); + // The BinarySecurityToken the Signature refers to is only added to the header by build(), + // so it must be added here too + builder.prependBSTElementToHeader(); + + ReplayCache replayCache = new MemoryReplayCache(); + verify(createdDoc, ecCrypto, replayCache); + + // Rewrite the SignatureValue (r, s) as (r, n - s) + CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); + cryptoType.setAlias("wss40ec"); + X509Certificate[] certs = ecCrypto.getX509Certificates(cryptoType); + BigInteger order = ((ECPublicKey)certs[0].getPublicKey()).getParams().getOrder(); + + Element signatureValueElement = + (Element)createdDoc.getElementsByTagNameNS(WSConstants.SIG_NS, "SignatureValue").item(0); + byte[] signatureValue = Base64.getMimeDecoder().decode(signatureValueElement.getTextContent()); + int half = signatureValue.length / 2; + byte[] s = new byte[half]; + System.arraycopy(signatureValue, half, s, 0, half); + byte[] rewrittenS = order.subtract(new BigInteger(1, s)).toByteArray(); + byte[] rewritten = signatureValue.clone(); + java.util.Arrays.fill(rewritten, half, rewritten.length, (byte)0); + int length = Math.min(rewrittenS.length, half); + System.arraycopy(rewrittenS, rewrittenS.length - length, rewritten, rewritten.length - length, length); + assertFalse(java.util.Arrays.equals(signatureValue, rewritten)); + signatureValueElement.setTextContent(Base64.getEncoder().encodeToString(rewritten)); + + // The rewritten SignatureValue is a valid signature in its own right... + verify(createdDoc, ecCrypto, new MemoryReplayCache()); + + // ...but it is the same message, so it must be detected as a replay + try { + verify(createdDoc, ecCrypto, replayCache); + fail("Expected failure on a replay attack"); + } catch (WSSecurityException ex) { + assertTrue(ex.getErrorCode() == WSSecurityException.ErrorCode.INVALID_SECURITY); + } + } + + private WSHandlerResult verify(Document doc, Crypto sigVerCrypto, ReplayCache replayCache) throws Exception { + WSSConfig wssConfig = WSSConfig.getNewInstance(); + RequestData data = new RequestData(); + data.setWssConfig(wssConfig); + data.setCallbackHandler(callbackHandler); + data.setSigVerCrypto(sigVerCrypto); + data.setTimestampReplayCache(replayCache); + WSSecurityEngine secEngine = new WSSecurityEngine(); + secEngine.setWssConfig(wssConfig); + return secEngine.processSecurityHeader(WSSecurityUtil.getSecurityHeader(doc, null), data); + } + @Test public void testReplayedTimestampWithEquivalentCreatedValue() throws Exception { diff --git a/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/WSSSignatureReferenceVerifyInputProcessor.java b/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/WSSSignatureReferenceVerifyInputProcessor.java index c9b5ee6d8..6f7fd1dbc 100644 --- a/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/WSSSignatureReferenceVerifyInputProcessor.java +++ b/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/WSSSignatureReferenceVerifyInputProcessor.java @@ -426,7 +426,7 @@ public class WSSSignatureReferenceVerifyInputProcessor extends AbstractSignature } final String cacheKey = createIdentifier(timestampSecurityEvent.getCreated(), - getSignatureType().getSignatureValue().getValue()); + getSignatureType().getSignedInfo().getReference()); if (replayCache.contains(cacheKey)) { throw new WSSecurityException(WSSecurityException.ErrorCode.MESSAGE_EXPIRED); } @@ -440,12 +440,24 @@ public class WSSSignatureReferenceVerifyInputProcessor extends AbstractSignature } /** - * Create the replay cache identifier for the given Timestamp Created value and signature - * value. The two are separated by a '|', which can appear in neither a Created value nor - * Base64, so that they cannot run together into an ambiguous identifier. + * Create the replay cache identifier for the given Timestamp Created value and the URI and + * DigestValue of each Reference of the SignedInfo. The SignatureValue is not used: it is not + * covered by the signature, and for ECDSA and DSA a second valid value can be computed from + * the first without the key, which would give a replayed message a new identifier. The values + * are separated by a '|', which can appear in neither a Created value nor Base64, so that they + * cannot run together into an ambiguous identifier. */ - private static String createIdentifier(Instant created, byte[] signatureValue) throws WSSecurityException { - String identifier = (created != null ? created.toString() : "") + "|" + encode(signatureValue); + private static String createIdentifier(Instant created, List<ReferenceType> references) + throws WSSecurityException { + StringBuilder identifierBuilder = new StringBuilder(created != null ? created.toString() : ""); + for (ReferenceType reference : references) { + String uri = reference.getURI(); + identifierBuilder.append('|') + .append(encode(uri != null ? uri.getBytes(StandardCharsets.UTF_8) : null)) + .append('|') + .append(encode(reference.getDigestValue())); + } + String identifier = identifierBuilder.toString(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); return encode(digest.digest(identifier.getBytes(StandardCharsets.UTF_8)));
