You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by co...@apache.org on 2014/11/05 12:33:43 UTC

svn commit: r1636855 - in /webservices/wss4j/trunk/ws-security-dom/src: main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java

Author: coheigea
Date: Wed Nov  5 11:33:43 2014
New Revision: 1636855

URL: http://svn.apache.org/r1636855
Log:
[WSS-519] - SAML 2.0 - WSS4J is expecting SecurityTokenReference under KeyInfo in EcryptedAssertion element

Modified:
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java?rev=1636855&r1=1636854&r2=1636855&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java Wed Nov  5 11:33:43 2014
@@ -19,6 +19,8 @@
 
 package org.apache.wss4j.dom.processor;
 
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
 import java.security.NoSuchAlgorithmException;
 import java.security.PrivateKey;
 import java.security.cert.X509Certificate;
@@ -40,6 +42,7 @@ import org.w3c.dom.Text;
 import org.apache.wss4j.common.bsp.BSPRule;
 import org.apache.wss4j.common.crypto.AlgorithmSuite;
 import org.apache.wss4j.common.crypto.AlgorithmSuiteValidator;
+import org.apache.wss4j.common.crypto.CryptoType;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.util.KeyUtils;
 import org.apache.wss4j.dom.WSConstants;
@@ -48,6 +51,8 @@ import org.apache.wss4j.dom.WSDocInfo;
 import org.apache.wss4j.dom.WSSecurityEngineResult;
 import org.apache.wss4j.dom.bsp.BSPEnforcer;
 import org.apache.wss4j.dom.handler.RequestData;
+import org.apache.wss4j.dom.message.token.DOMX509IssuerSerial;
+import org.apache.wss4j.dom.message.token.SecurityTokenReference;
 import org.apache.wss4j.dom.str.EncryptedKeySTRParser;
 import org.apache.wss4j.dom.str.STRParser;
 import org.apache.wss4j.dom.util.WSSecurityUtil;
@@ -376,9 +381,40 @@ public class EncryptedKeyProcessor imple
                     WSSecurityException.ErrorCode.INVALID_SECURITY, "noSecTokRef"
                 );
             }
-            strParser.parseSecurityTokenReference(strElement, data, wsDocInfo, null);
             
-            X509Certificate[] certs = strParser.getCertificates();
+            X509Certificate[] certs = null;
+            if (SecurityTokenReference.SECURITY_TOKEN_REFERENCE.equals(strElement.getLocalName()) 
+                && WSConstants.WSSE_NS.equals(strElement.getNamespaceURI())) {
+                strParser.parseSecurityTokenReference(strElement, data, wsDocInfo, null);
+                
+                certs = strParser.getCertificates();
+            } else if (WSConstants.SIG_NS.equals(strElement.getNamespaceURI())
+                && WSConstants.X509_DATA_LN.equals(strElement.getLocalName())) {
+                data.getBSPEnforcer().handleBSPRule(BSPRule.R5426);
+                
+                Element x509Child = getFirstElement(strElement);
+                
+                if (x509Child != null && WSConstants.SIG_NS.equals(x509Child.getNamespaceURI())) {
+                    if (WSConstants.X509_ISSUER_SERIAL_LN.equals(x509Child.getLocalName())) {
+                        DOMX509IssuerSerial issuerSerial = new DOMX509IssuerSerial(x509Child);
+                        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL);
+                        cryptoType.setIssuerSerial(issuerSerial.getIssuer(), issuerSerial.getSerialNumber());
+                        certs = data.getDecCrypto().getX509Certificates(cryptoType);
+                    } else if (WSConstants.X509_CERT_LN.equals(x509Child.getLocalName())) {
+                        byte[] token = getToken(x509Child);
+                        if (token == null) {
+                            throw new WSSecurityException(
+                                WSSecurityException.ErrorCode.FAILURE, "invalidCertData", 0);
+                        }
+                        InputStream in = new ByteArrayInputStream(token);
+                        X509Certificate cert = data.getDecCrypto().loadCertificate(in);
+                        if (cert != null) {
+                            certs = new X509Certificate[]{cert};
+                        }
+                    }
+                }
+            }
+            
             if (certs == null || certs.length < 1 || certs[0] == null) {
                 throw new WSSecurityException(
                     WSSecurityException.ErrorCode.FAILURE,
@@ -390,6 +426,38 @@ public class EncryptedKeyProcessor imple
         }
     }
     
+    private Element getFirstElement(Element element) {
+        for (Node currentChild = element.getFirstChild();
+             currentChild != null;
+             currentChild = currentChild.getNextSibling()
+        ) {
+            if (Node.ELEMENT_NODE == currentChild.getNodeType()) {
+                return (Element) currentChild;
+            }
+        }
+        return null;
+    }
+    
+    private byte[] getToken(Element element) {
+        Node node = element.getFirstChild();
+        StringBuilder builder = new StringBuilder();
+        while (node != null) {
+            if (Node.TEXT_NODE == node.getNodeType()) {
+                builder.append(((Text)node).getData());
+            }
+            node = node.getNextSibling();
+        }
+                
+        try {
+            return Base64.decode(builder.toString());
+        } catch (Exception ex) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(ex.getMessage(), ex);
+            }
+            return null;
+        }
+    }
+    
     /**
      * Find the list of all URIs that this encrypted Key references
      */

Modified: webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java?rev=1636855&r1=1636854&r2=1636855&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenTest.java Wed Nov  5 11:33:43 2014
@@ -31,6 +31,7 @@ import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 import javax.xml.parsers.DocumentBuilderFactory;
 
+import org.apache.wss4j.common.bsp.BSPRule;
 import org.apache.wss4j.common.crypto.Crypto;
 import org.apache.wss4j.common.crypto.CryptoFactory;
 import org.apache.wss4j.common.crypto.CryptoType;
@@ -66,6 +67,7 @@ import org.apache.xml.security.encryptio
 import org.apache.xml.security.encryption.EncryptedKey;
 import org.apache.xml.security.encryption.XMLCipher;
 import org.apache.xml.security.keys.KeyInfo;
+import org.apache.xml.security.keys.content.X509Data;
 import org.joda.time.DateTime;
 import org.opensaml.Configuration;
 import org.opensaml.common.SAMLObjectBuilder;
@@ -912,7 +914,7 @@ public class SamlTokenTest extends org.j
         assertTrue(certs != null && certs.length > 0 && certs[0] != null);
         
         encryptElement(doc, assertionElement, WSConstants.AES_128, secretKey,
-                WSConstants.KEYTRANSPORT_RSAOEP, certs[0], false);
+                WSConstants.KEYTRANSPORT_RSAOEP, certs[0], false, true);
         
         if (LOG.isDebugEnabled()) {
             String outputString = 
@@ -936,6 +938,79 @@ public class SamlTokenTest extends org.j
     }
     
     @org.junit.Test
+    public void testSAML2EncryptedAssertionNoSTR() throws Exception {
+        SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
+        callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
+        callbackHandler.setIssuer("www.example.com");
+        
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
+
+        WSSecSAMLToken wsSign = new WSSecSAMLToken();
+
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        
+        wsSign.prepare(doc, samlAssertion);
+        
+        // Get the Element + add it to the security header as an EncryptedAssertion
+        Element assertionElement = wsSign.getElement();
+        Element encryptedAssertionElement = 
+            doc.createElementNS(WSConstants.SAML2_NS, WSConstants.ENCRYPED_ASSERTION_LN);
+        encryptedAssertionElement.appendChild(assertionElement);
+        secHeader.getSecurityHeader().appendChild(encryptedAssertionElement);
+        
+        // Encrypt the Assertion
+        KeyGenerator keygen = KeyGenerator.getInstance("AES");
+        keygen.init(128);
+        SecretKey secretKey = keygen.generateKey();
+        Crypto crypto = CryptoFactory.getInstance("wss40.properties");
+        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+        cryptoType.setAlias("wss40");
+        X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
+        assertTrue(certs != null && certs.length > 0 && certs[0] != null);
+        
+        encryptElement(doc, assertionElement, WSConstants.AES_128, secretKey,
+                WSConstants.KEYTRANSPORT_RSAOEP, certs[0], false, false);
+        
+        if (LOG.isDebugEnabled()) {
+            String outputString = 
+                XMLUtils.PrettyDocumentToString(doc);
+            LOG.debug(outputString);
+        }
+        
+        RequestData data = new RequestData();
+        data.setDecCrypto(crypto);
+        List<BSPRule> ignoredRules = new ArrayList<BSPRule>();
+        ignoredRules.add(BSPRule.R5426);
+        data.setIgnoredBSPRules(ignoredRules);
+        data.setCallbackHandler(new KeystoreCallbackHandler());
+        WSSecurityEngine newEngine = new WSSecurityEngine();
+        
+        WSSConfig config = WSSConfig.getNewInstance();
+        config.setValidator(WSSecurityEngine.SAML_TOKEN, new CustomSamlAssertionValidator());
+        config.setValidator(WSSecurityEngine.SAML2_TOKEN, new CustomSamlAssertionValidator());
+        config.setValidateSamlSubjectConfirmation(false);
+        newEngine.setWssConfig(config);
+        
+        List<WSSecurityEngineResult> results = 
+            newEngine.processSecurityHeader(doc, "", data);
+        
+        WSSecurityEngineResult actionResult =
+            WSSecurityUtil.fetchActionResult(results, WSConstants.ST_UNSIGNED);
+        SamlAssertionWrapper receivedSamlAssertion =
+            (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
+        assertTrue(receivedSamlAssertion != null);
+        assertTrue(receivedSamlAssertion.getElement() != null);
+        assertTrue("Assertion".equals(receivedSamlAssertion.getElement().getLocalName()));
+        
+        actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
+        assertTrue(actionResult != null);
+    }
+    
+    @org.junit.Test
     public void testAssertionWrapper() throws Exception {
         SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler();
         callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN);
@@ -1142,7 +1217,8 @@ public class SamlTokenTest extends org.j
         Key encryptingKey,
         String keyTransportAlgorithm,
         X509Certificate wrappingCert,
-        boolean content
+        boolean content,
+        boolean useSecurityTokenReference
     ) throws Exception {
         XMLCipher cipher = XMLCipher.getInstance(algorithm);
         cipher.init(XMLCipher.ENCRYPT_MODE, encryptingKey);
@@ -1162,10 +1238,18 @@ public class SamlTokenTest extends org.j
                 encryptedKey.setKeyInfo(encryptedKeyKeyInfo);
             }
             
-            SecurityTokenReference securityTokenReference = new SecurityTokenReference(document);
-            securityTokenReference.addWSSENamespace();
-            securityTokenReference.setKeyIdentifierSKI(wrappingCert, null);
-            encryptedKeyKeyInfo.addUnknownElement(securityTokenReference.getElement());
+            if (useSecurityTokenReference) {
+                SecurityTokenReference securityTokenReference = new SecurityTokenReference(document);
+                securityTokenReference.addWSSENamespace();
+                securityTokenReference.setKeyIdentifierSKI(wrappingCert, null);
+                encryptedKeyKeyInfo.addUnknownElement(securityTokenReference.getElement());
+            } else {
+                X509Data x509Data = new X509Data(document);
+                // x509Data.addCertificate(wrappingCert);
+                x509Data.addIssuerSerial(wrappingCert.getIssuerX500Principal().getName(), 
+                                         wrappingCert.getSerialNumber());
+                encryptedKeyKeyInfo.add(x509Data);
+            }
 
             // Create a KeyInfo for the EncryptedData
             EncryptedData builder = cipher.getEncryptedData();