7

Everybody, Hello!

This is my request message:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
  <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soap:mustUnderstand="1">
     <wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-A3BCFAE87E12A8813813289737654441">MIICCTCCAXKgAwIBAgIETzVFkDANBgkqhkiG9w0BAQUFADBJMQswCQYDVQQGEwJSVTEKMAgGA1UECBMBMTEKMAgGA1UEBxMBMTEKMAgGA1UEChMBMTEKMAgGA1UECxMBMTEKMAgGA1UEAxMBMTAeFw0xMjAyMTAxNjI4MDBaFw0xMjA1MTAxNjI4MDBaMEkxCzAJBgNVBAYTAlJVMQowCAYDVQQIEwExMQowCAYDVQQHEwExMQowCAYDVQQKEwExMQowCAYDVQQLEwExMQowCAYDVQQDEwExMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdwxyRNYlWADnTtzH9/s/ehhD2iFzvF2xI+tBNyhbBb98EQNiIFdEegwGPhtd3Cfe1lQqtddWdFX2uLqozMAgd1KzSEuH9lI5DPiir3RfVdy+Irs5ZYiD/H4/DcUMUNyVcWspf9oG25wNdwNHKY8Aqz2269uYMCCoIBuWt6POwFQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAGLgTXbn7h2rBjv++6OopDooRifc4e2k+9sSTpLNegs9OvQzR8DpmQ/6Vt0RFprIdXSv+IVMcmL8Q2dmI9v0R61NIhdEjzSVbO2+PF9h1ShUARzMawRC/EOdjwVjDsk1WMxF18+wvH9SQxBSK3H2WpJbDWBxZCOW5CK1N6AKKJiC</wsse:BinarySecurityToken>
     <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-2">
        <ds:SignedInfo>
           <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
              <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="soap" />
           </ds:CanonicalizationMethod>
           <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
           <ds:Reference URI="#id-1">
              <ds:Transforms>
                 <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                    <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="" />
                 </ds:Transform>
              </ds:Transforms>
              <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
              <ds:DigestValue>RJhc1ZVjXdUQEIwLTH356p7H0QY=</ds:DigestValue>
           </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>F0q0NV7kaSbAcsLHxVpYD1bQ1RAJcw6wPapDKAM9PIcs7EuS9S5PlE4cQMfAp1WgsKa91r3op1OQ5UrYmmdj/UneYawdPIYSaoFBGjndTXZnOCKp4YfRTQGZ2EVJRFHJbPsTsqHedPAyJLHhciViguTGeuA0hZAQN97KB/9ZLmY=</ds:SignatureValue>
        <ds:KeyInfo Id="KI-A3BCFAE87E12A8813813289737654452">
           <wsse:SecurityTokenReference wsu:Id="STR-A3BCFAE87E12A8813813289737654483">
              <wsse:Reference URI="#X509-A3BCFAE87E12A8813813289737654441" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" />
           </wsse:SecurityTokenReference>
        </ds:KeyInfo>
     </ds:Signature>
  </wsse:Security>
</soap:Header>
 <soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-1">
  <stubMethod xmlns="http://ws_base.ws.stuff/" />
 </soap:Body>
</soap:Envelope>

I try to validate the <ds:DigestValue>RJhc1ZVjXdUQEIwLTH356p7H0QY=</ds:DigestValue> which is related to the body tag. There are tags like ds:CanonicalizationMethod and ds:Transformswhich are really confusing for me. My question is how to validate the body part? Firstly, what tag should I get to begin validation

<soap:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-1">
  <stubMethod xmlns="http://ws_base.ws.stuff/" />
 </soap:Body>

or just

<stubMethod xmlns="http://ws_base.ws.stuff/" /> 

??? What operations (canonicalization / transformation / encryption) must I perform???

Any help is appreciate. Thanks in advance.

Dmitry
  • 2,878
  • 5
  • 41
  • 63

3 Answers3

6

The solution is:

 private boolean validateSignature(Node signatureNode, Node bodyTag, PublicKey publicKey) {
    boolean signatureIsValid = false;
    try {
        // Create a DOM XMLSignatureFactory that will be used to unmarshal the
        // document containing the XMLSignature
        String providerName = System.getProperty
                ("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
                (Provider) Class.forName(providerName).newInstance());

        // Create a DOMValidateContext and specify a KeyValue KeySelector
        // and document context
        DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(publicKey), signatureNode);
        valContext.setIdAttributeNS((Element) bodyTag, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id");

        // Unmarshal the XMLSignature.
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        // Validate the XMLSignature.
        signatureIsValid = signature.validate(valContext);

    } catch (Exception ex) {
        logger.error("An Error Raised while Signature Validation");
        logger.error("Cause: " + ex.getCause());
        logger.error("Message: " + ex.getMessage());
    }

    return signatureIsValid;
}

where

public class X509KeySelector extends KeySelector {

PublicKey key;

/**
 * Constructor.
 *
 * @param key a public key of a certificate which need to be validated.
 */
public X509KeySelector(PublicKey key) {
    this.key = key;
}

/**
 * @return a KeySelectorResult with a predefined key.
 */
public KeySelectorResult select(KeyInfo keyInfo,
                                KeySelector.Purpose purpose,
                                AlgorithmMethod method,
                                XMLCryptoContext context) throws KeySelectorException {
    return new KeySelectorResult() {
        @Override
        public Key getKey() {
            return key;
        }
    };
}

}

and give to the X509KeySelector a public key you need to validate the signature.

Dmitry
  • 2,878
  • 5
  • 41
  • 63
  • Thank you Dmitry for your complete solution. I am getting `javax.xml.crypto.MarshalException: Document implementation must support DOM Level 2 and be namespace aware` when I call this method with `/Envelope/Header/Security/Signature` and `/Envelope/Body`. Do you know where does it come from ? – Bludwarf Sep 30 '14 at 14:29
  • Why do I get: java.lang.IllegalArgumentException: Id is not an attribute at javax.xml.crypto.dom.DOMCryptoContext.setIdAttributeNS – Dustin Sun Dec 28 '17 at 05:50
  • 1
    @Bludwarf your `DocumentBuilderFactory` implementation is not namespace aware. You'll have to call `documentBuilderFactory.setNamespaceAware(true)` before parsing the document. – Selaron Jan 07 '19 at 15:47
2

Well, I've managed to validate the reference digest: canonicalize -> sha1 -> base64. The problem is I can't validate the signature itself. I've tried:

 TransformerFactory transfac = TransformerFactory.newInstance();
 Transformer trans = transfac.newTransformer();
 StringWriter sw = new StringWriter();
 StreamResult result = new StreamResult(sw);
 DOMSource source = new DOMSource(signedInfoTag);
 trans.transform(source, result);
 String xmlString = sw.toString();

 Signature sig = Signature.getInstance("SHA1withRSA", "BC");

 sig.initVerify(cert.getPublicKey());
 sig.update(xmlString.getBytes());

 byte[] signatureValueDecoded = Translator.base64StringToByteArray(signatureValue);
         sig.verify (signatureValueDecoded);

where xmlString is a < SignedInfo > tag. I've read this. Still I don't know, how to format the xml in such a way. Actually it has to be done in-memory somehow

Community
  • 1
  • 1
Dmitry
  • 2,878
  • 5
  • 41
  • 63
0

I am getting a similar issue while trying to build the Signature inside a wss:Security tag in the Soap Header. I am trying to build a reference. If I add it with empty string as the first parameter:

Reference reference = factory.newReference("", digestMethod, transforms, null, null);

It does not work as I'm getting the following message from the server:

  • "No data found after transforming reference element (). One or more transformations may be missing."

If I add it with an ID like:

Reference reference = factory.newReference("#Body", digestMethod, transforms, null, null);

I am getting the following error:

  • javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID Body

This has been described here as a bug: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8017265

And, as such, I've been trying to use the setIdAttributeNS method to set the ID, instead of setting it directly on the body with body.setAttribute(Id, "Body");

signContext.setIdAttributeNS(soapBody, 
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id");

But I'm getting the same issue as @Dustin Sun. I'm also getting java.lang.IllegalArgumentException:

  • Id is not an attribute at javax.xml.crypto.dom.DOMCryptoContext.setIdAttributeNS.

I'm kind of stuck for the moment. I will come back if I find anything.

Marius
  • 11
  • 2