You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by co...@apache.org on 2016/03/21 18:03:30 UTC

[1/3] cxf-fediz git commit: Crypto refactor

Repository: cxf-fediz
Updated Branches:
  refs/heads/master 44b61cfae -> d6e13e521


Crypto refactor


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/d86ce5c6
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/d86ce5c6
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/d86ce5c6

Branch: refs/heads/master
Commit: d86ce5c699acb4b032ad3e794811c28fdd05a28d
Parents: 44b61cf
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Mon Mar 21 11:10:03 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Mon Mar 21 11:10:03 2016 +0000

----------------------------------------------------------------------
 .../cxf/fediz/core/config/FedizContext.java     |   2 +-
 .../cxf/fediz/core/metadata/MetadataWriter.java |   2 +-
 .../apache/cxf/fediz/core/util/CertsUtils.java  | 116 ++++++++++++++++---
 .../cxf/fediz/core/util/SignatureUtils.java     |   2 +-
 .../idp/beans/samlsso/SamlResponseCreator.java  |  35 +-----
 .../service/idp/metadata/IdpMetadataWriter.java |   4 +-
 .../idp/metadata/ServiceMetadataWriter.java     |   4 +-
 .../AbstractTrustedIdpProtocolHandler.java      |  72 ------------
 .../TrustedIdpOIDCProtocolHandler.java          |   5 +-
 .../TrustedIdpSAMLProtocolHandler.java          |   6 +-
 .../TrustedIdpWSFedProtocolHandler.java         |   2 +-
 11 files changed, 114 insertions(+), 136 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
index bb352f8..d67d49b 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
@@ -110,7 +110,7 @@ public class FedizContext implements Closeable {
             try {
                 if (manager.getKeyStore().getType().equalsIgnoreCase("PEM")) {
                     X509Certificate[] certificates = new X509Certificate[1];
-                    certificates[0] = CertsUtils.getX509Certificate(tm.getName(), classloader);
+                    certificates[0] = CertsUtils.getX509CertificateFromFile(tm.getName(), classloader);
                     crypto = new CertificateStore(certificates);
                 } else {
                     Properties sigProperties = createCryptoProperties(manager);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
index 228fd59..076f861 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataWriter.java
@@ -295,7 +295,7 @@ public class MetadataWriter {
                 keyAlias = config.getSigningKey().getCrypto().getDefaultX509Identifier();
             }
             X509Certificate cert = 
-                CertsUtils.getX509Certificate(config.getSigningKey().getCrypto(), keyAlias);
+                CertsUtils.getX509CertificateFromCrypto(config.getSigningKey().getCrypto(), keyAlias);
             if (cert == null) {
                 throw new ProcessingException(
                     "No signing certs were found to insert into the metadata using name: " 

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/CertsUtils.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/CertsUtils.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/CertsUtils.java
index 038de09..a1e2848 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/CertsUtils.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/CertsUtils.java
@@ -27,8 +27,11 @@ import java.security.cert.Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
+import java.util.Collections;
 import java.util.Properties;
 
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.wss4j.common.crypto.CertificateStore;
 import org.apache.wss4j.common.crypto.Crypto;
 import org.apache.wss4j.common.crypto.CryptoFactory;
 import org.apache.wss4j.common.crypto.CryptoType;
@@ -47,12 +50,18 @@ public final class CertsUtils {
         super();
     }
     
-    public static X509Certificate getX509Certificate(String filename) throws CertificateException {
-        return getX509Certificate(filename,
+    /**
+     * Load an X.509 Certificate from a certificate file
+     */
+    public static X509Certificate getX509CertificateFromFile(String filename) throws CertificateException {
+        return getX509CertificateFromFile(filename,
                                   Thread.currentThread().getContextClassLoader());
     }
     
-    public static X509Certificate getX509Certificate(String filename, ClassLoader classLoader) 
+    /**
+     * Load an X.509 Certificate from a certificate file
+     */
+    public static X509Certificate getX509CertificateFromFile(String filename, ClassLoader classLoader) 
         throws CertificateException {
         if (filename == null) {
             return null;
@@ -92,7 +101,62 @@ public final class CertsUtils {
         }
     }
     
-    public static Crypto createCrypto(String filename) {
+    /**
+     * Load an X.509 Certificate from a WSS4J Crypto instance using a keystore alias
+     */
+    public static X509Certificate getX509CertificateFromCrypto(Crypto crypto, String keyAlias) 
+        throws WSSecurityException {
+        if (keyAlias == null || "".equals(keyAlias)) {
+            keyAlias = crypto.getDefaultX509Identifier();
+        }
+        
+        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+        cryptoType.setAlias(keyAlias);
+        X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
+        if (issuerCerts == null || issuerCerts.length == 0) {
+            throw new RuntimeException(
+                    "No issuer certs were found to sign the metadata using issuer name: "
+                            + keyAlias);
+        }
+        return issuerCerts[0];
+    }
+    
+    /**
+     * Parse a String parameter into an X.509 Certificate. The parameter can be either the encoded cert, or else
+     * a filename containing the certificate.
+     */
+    public static X509Certificate parseX509Certificate(String certificate) 
+        throws CertificateException, WSSecurityException, ProcessingException, Base64DecodingException, IOException {
+        if (certificate == null) {
+            return null;
+        }
+        
+        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
+        if (isCertificateLocation) {
+            try {
+                return CertsUtils.getX509CertificateFromFile(certificate);
+            } catch (CertificateException ex) {
+                // Maybe it's a WSS4J properties file...
+                Crypto crypto = CertsUtils.getCryptoFromFile(certificate);
+                if (crypto != null) {
+                    return CertsUtils.getX509CertificateFromCrypto(crypto, null);
+                }
+            }
+        } 
+        
+        // Here the certificate is encoded in the configuration file
+        try {
+            return CertsUtils.parseCertificate(certificate);
+        } catch (Exception ex) {
+            LOG.error("Failed to parse trusted certificate", ex);
+            throw new ProcessingException("Failed to parse trusted certificate");
+        }
+    }
+   
+    /**
+     * Get a Crypto instance from a file
+     */
+    public static Crypto getCryptoFromFile(String filename) {
         Crypto crypto = null;
         Properties prop = new Properties();
         try {
@@ -110,26 +174,43 @@ public final class CertsUtils {
         return crypto;
     }
     
-    public static X509Certificate getX509Certificate(Crypto crypto, String keyAlias) throws WSSecurityException {
-        if (keyAlias == null || "".equals(keyAlias)) {
-            keyAlias = crypto.getDefaultX509Identifier();
+    /**
+     * Get a crypto instance using a certificate
+     */
+    public static Crypto getCryptoFromCertificate(String certificate) throws ProcessingException {
+        if (certificate == null) {
+            return null;
         }
         
-        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
-        cryptoType.setAlias(keyAlias);
-        X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
-        if (issuerCerts == null || issuerCerts.length == 0) {
-            throw new RuntimeException(
-                    "No issuer certs were found to sign the metadata using issuer name: "
-                            + keyAlias);
+        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
+        if (isCertificateLocation) {
+            try {
+                X509Certificate cert = CertsUtils.getX509CertificateFromFile(certificate);
+                if (cert == null) {
+                    return null;
+                }
+                return new CertificateStore(new X509Certificate[]{cert});
+            } catch (CertificateException ex) {
+                // Maybe it's a WSS4J properties file...
+                return CertsUtils.getCryptoFromFile(certificate);
+            }
+        } 
+        
+        // Here the certificate is encoded in the configuration file
+        X509Certificate cert;
+        try {
+            cert = CertsUtils.parseCertificate(certificate);
+        } catch (Exception ex) {
+            LOG.error("Failed to parse trusted certificate", ex);
+            throw new ProcessingException("Failed to parse trusted certificate");
         }
-        return issuerCerts[0];
+        return new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
     }
     
-    public static X509Certificate parseCertificate(String certificate)
+    private static X509Certificate parseCertificate(String certificate)
         throws CertificateException, Base64DecodingException, IOException {
         
-        //before decoding we need to get rod off the prefix and suffix
+        //before decoding we need to get rid off the prefix and suffix
         byte[] decoded = Base64.decode(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "").
                                         replaceAll("-----END CERTIFICATE-----", ""));
 
@@ -137,4 +218,5 @@ public final class CertsUtils {
             return (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(is);
         }
     }
+    
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
index c7b55dd..5ea2b12 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/util/SignatureUtils.java
@@ -60,7 +60,7 @@ public final class SignatureUtils {
         if (keyAlias == null || "".equals(keyAlias)) {
             keyAlias = crypto.getDefaultX509Identifier();
         }
-        X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias);
+        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
 //    }
     
 /*    public static ByteArrayOutputStream signMetaInfo(FederationContext config, InputStream metaInfo,

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
index 2d8da15..9e27a3a 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
@@ -19,8 +19,6 @@
 package org.apache.cxf.fediz.service.idp.beans.samlsso;
 
 import java.io.IOException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
 import java.util.Collections;
 import java.util.List;
 
@@ -40,7 +38,6 @@ import org.apache.cxf.fediz.service.idp.samlsso.SAML2PResponseComponentBuilder;
 import org.apache.cxf.fediz.service.idp.util.WebUtils;
 import org.apache.cxf.helpers.DOMUtils;
 import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
-import org.apache.wss4j.common.crypto.CertificateStore;
 import org.apache.wss4j.common.crypto.Crypto;
 import org.apache.wss4j.common.saml.OpenSAMLUtil;
 import org.apache.wss4j.common.saml.SAMLCallback;
@@ -138,7 +135,7 @@ public class SamlResponseCreator {
         SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
         SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
         
-        Crypto issuerCrypto = getCrypto(idp.getCertificate());
+        Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
         assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
                                 issuerCrypto, false);
         
@@ -164,36 +161,6 @@ public class SamlResponseCreator {
         return Base64Utility.encode(responseMessage.getBytes());
     }
     
-    private Crypto getCrypto(String certificate) throws ProcessingException {
-        if (certificate == null) {
-            return null;
-        }
-        
-        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
-        if (isCertificateLocation) {
-            try {
-                X509Certificate cert = CertsUtils.getX509Certificate(certificate);
-                if (cert == null) {
-                    return null;
-                }
-                return new CertificateStore(new X509Certificate[]{cert});
-            } catch (CertificateException ex) {
-                // Maybe it's a WSS4J properties file...
-                return CertsUtils.createCrypto(certificate);
-            }
-        } 
-        
-        // Here the certificate is encoded in the configuration file
-        X509Certificate cert;
-        try {
-            cert = CertsUtils.parseCertificate(certificate);
-        } catch (Exception ex) {
-            LOG.error("Failed to parse trusted certificate", ex);
-            throw new ProcessingException("Failed to parse trusted certificate");
-        }
-        return new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
-    }
-
     public boolean isSupportDeflateEncoding() {
         return supportDeflateEncoding;
     }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
index 0d9b0b1..7c5baec 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
@@ -50,7 +50,7 @@ public class IdpMetadataWriter {
     public Document getMetaData(Idp config) throws RuntimeException {
         try {
             //Return as text/xml
-            Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
 
             W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
 
@@ -123,7 +123,7 @@ public class IdpMetadataWriter {
 
         try {
             String keyAlias = crypto.getDefaultX509Identifier();
-            X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias);
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
             writer.writeCharacters(Base64.encode(cert.getEncoded()));
         } catch (Exception ex) {
             LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
index 5eb794c..3118d8f 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
@@ -53,7 +53,7 @@ public class ServiceMetadataWriter {
     public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException {
 
         try {
-            Crypto crypto = CertsUtils.createCrypto(config.getCertificate());
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
             
             W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
 
@@ -180,7 +180,7 @@ public class ServiceMetadataWriter {
             // Write the Base-64 encoded certificate
             
             String keyAlias = crypto.getDefaultX509Identifier();
-            X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias);
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
             
             if (cert == null) {
                 throw new ProcessingException(

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
index fb3ec72..2329eb2 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
@@ -19,93 +19,21 @@
 
 package org.apache.cxf.fediz.service.idp.protocols;
 
-import java.io.IOException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
 import java.util.Map;
 
 import javax.servlet.http.HttpServletRequest;
 
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.util.CertsUtils;
 import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
 import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
-import org.apache.wss4j.common.crypto.CertificateStore;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.xml.security.exceptions.Base64DecodingException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public abstract class AbstractTrustedIdpProtocolHandler implements TrustedIdpProtocolHandler {
     
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractTrustedIdpProtocolHandler.class);
-    
     @Override
     public boolean canHandleRequest(HttpServletRequest request) {
         // TODO Auto-generated method stub
         return false;
     }
 
-    protected Crypto getCrypto(String certificate) throws ProcessingException {
-        if (certificate == null) {
-            return null;
-        }
-        
-        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
-        if (isCertificateLocation) {
-            try {
-                X509Certificate cert = CertsUtils.getX509Certificate(certificate);
-                if (cert == null) {
-                    return null;
-                }
-                return new CertificateStore(new X509Certificate[]{cert});
-            } catch (CertificateException ex) {
-                // Maybe it's a WSS4J properties file...
-                return CertsUtils.createCrypto(certificate);
-            }
-        } 
-        
-        // Here the certificate is encoded in the configuration file
-        X509Certificate cert;
-        try {
-            cert = CertsUtils.parseCertificate(certificate);
-        } catch (Exception ex) {
-            LOG.error("Failed to parse trusted certificate", ex);
-            throw new ProcessingException("Failed to parse trusted certificate");
-        }
-        return new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
-    }
-    
-    protected X509Certificate getCertificate(String certificate) 
-        throws CertificateException, WSSecurityException, ProcessingException, Base64DecodingException, IOException {
-        if (certificate == null) {
-            return null;
-        }
-        
-        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
-        if (isCertificateLocation) {
-            try {
-                return CertsUtils.getX509Certificate(certificate);
-            } catch (CertificateException ex) {
-                // Maybe it's a WSS4J properties file...
-                Crypto crypto = CertsUtils.createCrypto(certificate);
-                if (crypto != null) {
-                    return CertsUtils.getX509Certificate(crypto, null);
-                }
-            }
-        } 
-        
-        // Here the certificate is encoded in the configuration file
-        try {
-            return CertsUtils.parseCertificate(certificate);
-        } catch (Exception ex) {
-            LOG.error("Failed to parse trusted certificate", ex);
-            throw new ProcessingException("Failed to parse trusted certificate");
-        }
-    }
-    
     protected String getProperty(TrustedIdp trustedIdp, String property) {
         Map<String, String> parameters = trustedIdp.getParameters();
         

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
index 0f40056..1359a8b 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
@@ -42,6 +42,7 @@ import org.w3c.dom.Element;
 
 import org.apache.cxf.fediz.core.FederationConstants;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.util.CertsUtils;
 import org.apache.cxf.fediz.core.util.DOMUtils;
 import org.apache.cxf.fediz.service.idp.IdpConstants;
 import org.apache.cxf.fediz.service.idp.domain.Idp;
@@ -364,7 +365,7 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpProtocolHan
             return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
         }
         
-        X509Certificate validatingCert = getCertificate(trustedIdp.getCertificate());
+        X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
         if (validatingCert != null) {
             return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
         }
@@ -421,7 +422,7 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpProtocolHan
         
         SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
         
-        Crypto crypto = getCrypto(idp.getCertificate());
+        Crypto crypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
         assertion.signAssertion(crypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
                                 crypto, false);
         

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
index 00df355..3f5c0a2 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
@@ -187,7 +187,7 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
             org.opensaml.saml.saml2.core.Response samlResponse = 
                 readSAMLResponse(encodedSAMLResponse, trustedIdp);
             
-            Crypto crypto = getCrypto(trustedIdp.getCertificate());
+            Crypto crypto = CertsUtils.getCryptoFromCertificate(trustedIdp.getCertificate());
             validateSamlResponseProtocol(samlResponse, crypto, trustedIdp);
             // Validate the Response
             SSOValidatorResponse validatorResponse = 
@@ -241,14 +241,14 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
         Idp config,
         UriBuilder ub
     ) throws Exception {
-        Crypto crypto = getCrypto(config.getCertificate());
+        Crypto crypto = CertsUtils.getCryptoFromCertificate(config.getCertificate());
         if (crypto == null) {
             LOG.error("No crypto instance of properties file configured for signature");
             throw new IllegalStateException("Invalid IdP configuration");
         }
         
         String alias = crypto.getDefaultX509Identifier();
-        X509Certificate cert = CertsUtils.getX509Certificate(crypto, alias);
+        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias);
         if (cert == null) {
             LOG.error("No cert was found to sign the request using alias: " + alias);
             throw new IllegalStateException("Invalid IdP configuration");

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d86ce5c6/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
index c823e32..25a5e9c 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
@@ -214,7 +214,7 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
             
             X509Certificate cert;
             try {
-                cert = CertsUtils.parseCertificate(trustedIdpConfig.getCertificate());
+                cert = CertsUtils.parseX509Certificate(trustedIdpConfig.getCertificate());
             } catch (Exception ex) {
                 LOG.error("Failed to parse trusted certificate", ex);
                 throw new ProcessingException("Failed to parse trusted certificate");


[3/3] cxf-fediz git commit: Added AuthnRequest signature validation for POST

Posted by co...@apache.org.
Added AuthnRequest signature validation for POST


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/d6e13e52
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/d6e13e52
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/d6e13e52

Branch: refs/heads/master
Commit: d6e13e5210f82cef8510a8c9a06f76da72b996a0
Parents: 6f06a08
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Mon Mar 21 17:03:14 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Mon Mar 21 17:03:14 2016 +0000

----------------------------------------------------------------------
 .../idp/beans/samlsso/AuthnRequestParser.java   |  19 ++-
 .../idp/samlsso/AuthnRequestValidator.java      | 164 +++++++++++++++++++
 .../WEB-INF/flows/saml-validate-request.xml     |   7 +-
 .../apache/cxf/fediz/systests/idp/IdpTest.java  | 142 ++++++++++++++++
 .../src/test/resources/stsKeystoreA.properties  |   6 +
 .../samlsso/src/test/resources/stsrealm_a.jks   | Bin 0 -> 2061 bytes
 6 files changed, 333 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
index db8a013..737425f 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
@@ -24,7 +24,11 @@ import java.io.InputStreamReader;
 import org.w3c.dom.Document;
 
 import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
 import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.samlsso.AuthnRequestValidator;
 import org.apache.cxf.fediz.service.idp.util.WebUtils;
 import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
 import org.apache.cxf.rs.security.saml.sso.SSOConstants;
@@ -45,21 +49,32 @@ public class AuthnRequestParser {
 
     private static final Logger LOG = LoggerFactory.getLogger(AuthnRequestParser.class);
 
-    public void parseSAMLRequest(RequestContext context) {
+    public void parseSAMLRequest(RequestContext context, Idp idp) throws ProcessingException {
         String samlRequest = context.getFlowScope().getString(SSOConstants.SAML_REQUEST);
         LOG.debug("Received SAML Request: {}", samlRequest);
 
+        AuthnRequest parsedRequest = null;
         if (samlRequest == null) {
             WebUtils.removeAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
         } else {
             try {
-                AuthnRequest parsedRequest = extractRequest(samlRequest);
+                parsedRequest = extractRequest(samlRequest);
                 WebUtils.putAttributeInFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST, parsedRequest);
                 LOG.debug("SAML Request with id '{}' successfully parsed", parsedRequest.getID());
             } catch (Exception ex) {
                 LOG.warn("Error parsing request: {}", ex.getMessage());
             }
         }
+        
+        if (parsedRequest != null) {
+            try {
+                AuthnRequestValidator validator = new AuthnRequestValidator();
+                validator.validateAuthnRequest(context, parsedRequest, idp);
+            } catch (Exception ex) {
+                LOG.warn("Error validating request {}", ex.getMessage(), ex);
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+        }
     }
     
     public String retrieveRealm(RequestContext context) {

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/AuthnRequestValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/AuthnRequestValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/AuthnRequestValidator.java
new file mode 100644
index 0000000..ebb48dc
--- /dev/null
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/AuthnRequestValidator.java
@@ -0,0 +1,164 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.fediz.service.idp.samlsso;
+
+import org.w3c.dom.Document;
+
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SAMLKeyInfo;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.dom.WSDocInfo;
+import org.apache.wss4j.dom.engine.WSSConfig;
+import org.apache.wss4j.dom.handler.RequestData;
+import org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor;
+import org.apache.wss4j.dom.validate.Credential;
+import org.apache.wss4j.dom.validate.SignatureTrustValidator;
+import org.apache.wss4j.dom.validate.Validator;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
+import org.opensaml.security.credential.BasicCredential;
+import org.opensaml.security.x509.BasicX509Credential;
+import org.opensaml.xmlsec.signature.KeyInfo;
+import org.opensaml.xmlsec.signature.Signature;
+import org.opensaml.xmlsec.signature.support.SignatureException;
+import org.opensaml.xmlsec.signature.support.SignatureValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Validate the received AuthnRequest
+ */
+public class AuthnRequestValidator {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AuthnRequestValidator.class);
+
+    public void validateAuthnRequest(RequestContext context, AuthnRequest authnRequest, Idp idp) 
+        throws ProcessingException, WSSecurityException {
+        if (authnRequest.isSigned()) {
+            // Check destination
+            String destination = authnRequest.getDestination();
+            LOG.debug("Validating destination: {}", destination);
+            
+            String localAddr = WebUtils.getHttpServletRequest(context).getRequestURL().toString();
+            if (!localAddr.startsWith(destination)) {
+                LOG.debug("The destination {} does not match the local address {}", destination, localAddr);
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+            
+            // Check signature
+            Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
+            validateAuthnRequestSignature(authnRequest.getSignature(), issuerCrypto);
+        } else {
+            LOG.debug("No signature is present, therefore the request is rejected");
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+    
+    /**
+     * Validate the AuthnRequest signature
+     */
+    private void validateAuthnRequestSignature(
+        Signature signature,
+        Crypto sigCrypto
+    ) throws WSSecurityException {
+        RequestData requestData = new RequestData();
+        requestData.setSigVerCrypto(sigCrypto);
+        WSSConfig wssConfig = WSSConfig.getNewInstance();
+        requestData.setWssConfig(wssConfig);
+        // requestData.setCallbackHandler(callbackHandler);
+
+        SAMLKeyInfo samlKeyInfo = null;
+
+        KeyInfo keyInfo = signature.getKeyInfo();
+        if (keyInfo != null) {
+            try {
+                Document doc = signature.getDOM().getOwnerDocument();
+                samlKeyInfo =
+                    SAMLUtil.getCredentialFromKeyInfo(
+                        keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(doc)), sigCrypto
+                    );
+            } catch (WSSecurityException ex) {
+                LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
+                throw ex;
+            }
+        }
+        
+        if (samlKeyInfo == null) {
+            LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+
+        // Validate Signature against profiles
+        validateSignatureAgainstProfiles(signature, samlKeyInfo);
+
+        // Now verify trust on the signature
+        Credential trustCredential = new Credential();
+        trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
+        trustCredential.setCertificates(samlKeyInfo.getCerts());
+
+        try {
+            Validator signatureValidator = new SignatureTrustValidator();
+            signatureValidator.validate(trustCredential, requestData);
+        } catch (WSSecurityException e) {
+            LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+    }
+
+    /**
+     * Validate a signature against the profiles
+     */
+    private void validateSignatureAgainstProfiles(
+        Signature signature,
+        SAMLKeyInfo samlKeyInfo
+    ) throws WSSecurityException {
+        // Validate Signature against profiles
+        SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
+        try {
+            validator.validate(signature);
+        } catch (SignatureException ex) {
+            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+
+        BasicCredential credential = null;
+        if (samlKeyInfo.getCerts() != null) {
+            credential = new BasicX509Credential(samlKeyInfo.getCerts()[0]);
+        } else if (samlKeyInfo.getPublicKey() != null) {
+            credential = new BasicCredential(samlKeyInfo.getPublicKey());
+        } else {
+            LOG.debug("Can't get X509Certificate or PublicKey to verify signature");
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+        try {
+            SignatureValidator.validate(signature, credential);
+        } catch (SignatureException ex) {
+            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml b/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
index 9014030..b97d020 100644
--- a/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
+++ b/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
@@ -32,12 +32,13 @@
         <if test="requestParameters.RelayState == null or requestParameters.RelayState.length() == 0"
             then="viewBadRequest" />
         <if test="requestParameters.SAMLRequest != null and !requestParameters.SAMLRequest.isEmpty()"
-            then="parseSAMLRequest" else="viewBadRequest" />
+            then="parseAndValidateSAMLRequest" else="viewBadRequest" />
     </decision-state>
     
-    <action-state id="parseSAMLRequest">
-        <evaluate expression="authnRequestParser.parseSAMLRequest(flowRequestContext)" />
+    <action-state id="parseAndValidateSAMLRequest">
+        <evaluate expression="authnRequestParser.parseSAMLRequest(flowRequestContext, flowScope.idpConfig)" />
         <transition to="signinSAMLRequest"/>
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
     </action-state>
 
     <subflow-state id="signinSAMLRequest" subflow="signinSAMLRequest">

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
----------------------------------------------------------------------
diff --git a/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java b/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
index b0f2bea..441ca2c 100644
--- a/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
+++ b/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
@@ -25,6 +25,8 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URLEncoder;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
 import java.util.UUID;
 
 import org.w3c.dom.Document;
@@ -48,6 +50,9 @@ import org.apache.cxf.rs.security.saml.sso.SSOConstants;
 import org.apache.cxf.staxutils.StaxUtils;
 import org.apache.http.auth.AuthScope;
 import org.apache.http.auth.UsernamePasswordCredentials;
+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.saml.OpenSAMLUtil;
 import org.apache.wss4j.common.util.DOM2Writer;
 import org.apache.wss4j.dom.engine.WSSConfig;
@@ -55,7 +60,13 @@ import org.junit.AfterClass;
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.opensaml.core.xml.XMLObject;
+import org.opensaml.saml.common.SignableSAMLObject;
 import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.security.x509.BasicX509Credential;
+import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory;
+import org.opensaml.xmlsec.signature.KeyInfo;
+import org.opensaml.xmlsec.signature.Signature;
+import org.opensaml.xmlsec.signature.support.SignatureConstants;
 
 /**
  * Some tests invoking directly on the IdP for SAML SSO
@@ -164,6 +175,8 @@ public class IdpTest {
             new DefaultAuthnRequestBuilder().createAuthnRequest(
                 null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
             );
+        authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
+        signAuthnRequest(authnRequest);
         
         Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
         String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
@@ -251,6 +264,8 @@ public class IdpTest {
             new DefaultAuthnRequestBuilder().createAuthnRequest(
                 null, "urn:org:apache:cxf:fediz:fedizhelloworld-xyz", "https://localhost/acsa"
             );
+        authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
+        signAuthnRequest(authnRequest);
         
         Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
         String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
@@ -282,6 +297,94 @@ public class IdpTest {
         webClient.close();
     }
     
+    @org.junit.Test
+    public void testMissingDestination() throws Exception {
+        OpenSAMLUtil.initSamlEngine();
+        
+        // Create SAML AuthnRequest
+        Document doc = DOMUtils.createDocument();
+        doc.appendChild(doc.createElement("root"));
+        // Create the AuthnRequest
+        AuthnRequest authnRequest = 
+            new DefaultAuthnRequestBuilder().createAuthnRequest(
+                null, "urn:org:apache:cxf:fediz:fedizhelloworld", "https://localhost/acsa"
+            );
+        signAuthnRequest(authnRequest);
+        
+        Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
+        String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
+
+        String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");
+
+        String relayState = UUID.randomUUID().toString();
+        String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?";
+        url += SSOConstants.RELAY_STATE + "=" + relayState;
+        url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
+
+        String user = "alice";
+        String password = "ecila";
+
+        final WebClient webClient = new WebClient();
+        webClient.getOptions().setUseInsecureSSL(true);
+        webClient.getCredentialsProvider().setCredentials(
+            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
+            new UsernamePasswordCredentials(user, password));
+
+        webClient.getOptions().setJavaScriptEnabled(false);
+        try {
+            webClient.getPage(url);
+            Assert.fail("Failure expected on no destination value");
+        } catch (FailingHttpStatusCodeException ex) {
+            Assert.assertEquals(ex.getStatusCode(), 400);
+        }
+        
+        webClient.close();
+    }
+    
+    @org.junit.Test
+    public void testUnsignedRequest() throws Exception {
+        OpenSAMLUtil.initSamlEngine();
+        
+        // Create SAML AuthnRequest
+        Document doc = DOMUtils.createDocument();
+        doc.appendChild(doc.createElement("root"));
+        // Create the AuthnRequest
+        AuthnRequest authnRequest = 
+            new DefaultAuthnRequestBuilder().createAuthnRequest(
+                null, "urn:org:apache:cxf:fediz:fedizhelloworld", "https://localhost/acsa"
+            );
+        authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
+        
+        Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
+        String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
+
+        String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");
+
+        String relayState = UUID.randomUUID().toString();
+        String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?";
+        url += SSOConstants.RELAY_STATE + "=" + relayState;
+        url += "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest;
+
+        String user = "alice";
+        String password = "ecila";
+
+        final WebClient webClient = new WebClient();
+        webClient.getOptions().setUseInsecureSSL(true);
+        webClient.getCredentialsProvider().setCredentials(
+            new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
+            new UsernamePasswordCredentials(user, password));
+
+        webClient.getOptions().setJavaScriptEnabled(false);
+        try {
+            webClient.getPage(url);
+            Assert.fail("Failure expected on an unsigned request");
+        } catch (FailingHttpStatusCodeException ex) {
+            Assert.assertEquals(ex.getStatusCode(), 400);
+        }
+        
+        webClient.close();
+    }
+    
     private String encodeAuthnRequest(Element authnRequest) throws IOException {
         String requestMessage = DOM2Writer.nodeToString(authnRequest);
         
@@ -290,4 +393,43 @@ public class IdpTest {
 
         return Base64Utility.encode(deflatedBytes);
     }
+    
+    private void signAuthnRequest(AuthnRequest authnRequest) throws Exception {
+        Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");
+        
+        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+        cryptoType.setAlias("realma");
+        X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
+
+        String sigAlgo = SSOConstants.RSA_SHA1;
+        
+        // Get the private key
+        PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");
+        
+        // Create the signature
+        Signature signature = OpenSAMLUtil.buildSignature();
+        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
+        signature.setSignatureAlgorithm(sigAlgo);
+        
+        BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);
+
+        signature.setSigningCredential(signingCredential);
+
+        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
+        kiFactory.setEmitEntityCertificate(true);
+        
+        try {
+            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
+            signature.setKeyInfo(keyInfo);
+        } catch (org.opensaml.security.SecurityException ex) {
+            throw new Exception(
+                    "Error generating KeyInfo from signing credential", ex);
+        }
+        
+        SignableSAMLObject signableObject = (SignableSAMLObject) authnRequest;
+        signableObject.setSignature(signature);
+        signableObject.releaseDOM();
+        signableObject.releaseChildrenDOM(true);
+        
+    }
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/systests/samlsso/src/test/resources/stsKeystoreA.properties
----------------------------------------------------------------------
diff --git a/systests/samlsso/src/test/resources/stsKeystoreA.properties b/systests/samlsso/src/test/resources/stsKeystoreA.properties
new file mode 100644
index 0000000..bd9fb1b
--- /dev/null
+++ b/systests/samlsso/src/test/resources/stsKeystoreA.properties
@@ -0,0 +1,6 @@
+org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
+org.apache.ws.security.crypto.merlin.keystore.type=jks
+org.apache.ws.security.crypto.merlin.keystore.password=storepass
+org.apache.ws.security.crypto.merlin.keystore.alias=realma
+org.apache.ws.security.crypto.merlin.keystore.file=stsrealm_a.jks
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d6e13e52/systests/samlsso/src/test/resources/stsrealm_a.jks
----------------------------------------------------------------------
diff --git a/systests/samlsso/src/test/resources/stsrealm_a.jks b/systests/samlsso/src/test/resources/stsrealm_a.jks
new file mode 100644
index 0000000..fde2928
Binary files /dev/null and b/systests/samlsso/src/test/resources/stsrealm_a.jks differ


[2/3] cxf-fediz git commit: SAML Response refactoring

Posted by co...@apache.org.
SAML Response refactoring


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/6f06a082
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/6f06a082
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/6f06a082

Branch: refs/heads/master
Commit: 6f06a082e2c09f1dbc35e1ca42888f29d8d727f1
Parents: d86ce5c
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Mon Mar 21 12:09:48 2016 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Mon Mar 21 12:09:48 2016 +0000

----------------------------------------------------------------------
 .../idp/beans/samlsso/SamlResponseCreator.java  | 61 ++++++++++----------
 .../idp/samlsso/SAML2CallbackHandler.java       | 46 +++++++++++----
 .../WEB-INF/flows/saml-validate-request.xml     | 10 ++--
 .../apache/cxf/fediz/systests/idp/IdpTest.java  | 12 +++-
 4 files changed, 81 insertions(+), 48 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/6f06a082/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
index 9e27a3a..a12f257 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
@@ -22,9 +22,6 @@ import java.io.IOException;
 import java.util.Collections;
 import java.util.List;
 
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -49,10 +46,9 @@ import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
 import org.apache.wss4j.common.util.DOM2Writer;
 import org.apache.wss4j.dom.WSConstants;
 import org.joda.time.DateTime;
-import org.opensaml.saml.saml2.core.AttributeStatement;
+import org.opensaml.saml.saml2.core.Assertion;
 import org.opensaml.saml.saml2.core.Response;
 import org.opensaml.saml.saml2.core.Status;
-import org.opensaml.saml.saml2.core.Subject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
@@ -78,11 +74,15 @@ public class SamlResponseCreator {
         
         try {
             SamlAssertionWrapper wrapper = new SamlAssertionWrapper(samlTokens.get(0));
-            Subject subject = wrapper.getSaml2().getSubject();
-            List<AttributeStatement> attributeStatements = wrapper.getSaml2().getAttributeStatements();
+            if (wrapper.getSaml2() == null) {
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+            
+            String remoteAddr = WebUtils.getHttpServletRequest(context).getRemoteAddr();
+            Assertion saml2Assertion = 
+                createSAML2Assertion(idp, wrapper, requestId, requestIssuer, remoteAddr, consumerURL);
             
-            Element response = createResponse(context, idp, requestId, consumerURL, requestIssuer,
-                                              subject, attributeStatements);
+            Element response = createResponse(idp, requestId, saml2Assertion);
             return encodeResponse(response);
         } catch (Exception ex) {
             ex.printStackTrace();
@@ -91,32 +91,17 @@ public class SamlResponseCreator {
         }
     }
     
-    protected Element createResponse(RequestContext context, Idp idp, String requestID, 
-                                     String racs, String requestIssuer,
-                                     Subject subject,
-                                     List<AttributeStatement> attributeStatements) throws Exception {
-        DocumentBuilderFactory docBuilderFactory;
-        docBuilderFactory = DocumentBuilderFactory.newInstance();
-        docBuilderFactory.setNamespaceAware(true);
-        
-        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
-        Document doc = docBuilder.newDocument();
-        
-        Status status = 
-            SAML2PResponseComponentBuilder.createStatus(
-                "urn:oasis:names:tc:SAML:2.0:status:Success", null
-            );
-        Response response = 
-            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
-        
+    private Assertion createSAML2Assertion(Idp idp, SamlAssertionWrapper receivedToken,
+                                           String requestID, String requestIssuer, 
+                                           String remoteAddr, String racs) throws Exception {
         // Create an AuthenticationAssertion
         SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
         callbackHandler.setIssuer(idp.getRealm());
-        callbackHandler.setSubject(subject);
+        callbackHandler.setSubject(receivedToken.getSaml2().getSubject());
         
         // Subject Confirmation Data
         SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
-        subjectConfirmationData.setAddress(WebUtils.getHttpServletRequest(context).getRemoteAddr());
+        subjectConfirmationData.setAddress(remoteAddr);
         subjectConfirmationData.setInResponseTo(requestID);
         subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
         subjectConfirmationData.setRecipient(racs);
@@ -131,6 +116,9 @@ public class SamlResponseCreator {
         conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
         callbackHandler.setConditions(conditions);
         
+        // Attributes
+        callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());
+        
         SAMLCallback samlCallback = new SAMLCallback();
         SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
         SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
@@ -139,7 +127,20 @@ public class SamlResponseCreator {
         assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
                                 issuerCrypto, false);
         
-        response.getAssertions().add(assertion.getSaml2());
+        return assertion.getSaml2();
+    }
+    
+    protected Element createResponse(Idp idp, String requestID, Assertion assertion) throws Exception {
+        Document doc = DOMUtils.newDocument();
+        
+        Status status = 
+            SAML2PResponseComponentBuilder.createStatus(
+                "urn:oasis:names:tc:SAML:2.0:status:Success", null
+            );
+        Response response = 
+            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
+        
+        response.getAssertions().add(assertion);
         
         Element policyElement = OpenSAMLUtil.toDom(response, doc);
         doc.appendChild(policyElement);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/6f06a082/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
index 1475dd4..9981253 100644
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
+++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
@@ -37,12 +37,15 @@ import org.apache.wss4j.common.saml.bean.SubjectBean;
 import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
 import org.apache.wss4j.common.saml.bean.Version;
 import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.saml.saml2.core.Attribute;
+import org.opensaml.saml.saml2.core.AttributeStatement;
 import org.opensaml.saml.saml2.core.Subject;
 
 /**
  * A Callback Handler implementation for a SAML 2 assertion. By default it creates a SAML 2.0 Assertion with
- * an AuthenticationStatement. If a list of roles are also supplied, it will insert them as part of an 
- * AttributeStatement.
+ * an AuthenticationStatement. If a list of AttributeStatements are also supplied it will insert them into the
+ * Assertion.
  */
 public class SAML2CallbackHandler implements CallbackHandler {
     
@@ -51,22 +54,35 @@ public class SAML2CallbackHandler implements CallbackHandler {
     private String issuer;
     private ConditionsBean conditions;
     private SubjectConfirmationDataBean subjectConfirmationData;
-    private List<Object> roles = new ArrayList<>();
+    private List<AttributeStatement> attributeStatements;
     
     private void createAndSetStatement(SAMLCallback callback) {
         AuthenticationStatementBean authBean = new AuthenticationStatementBean();
         authBean.setAuthenticationMethod("Password");
         callback.setAuthenticationStatementData(Collections.singletonList(authBean));
 
-        if (!roles.isEmpty()) {
-            AttributeStatementBean attrBean = new AttributeStatementBean();
-            AttributeBean attributeBean = new AttributeBean();
-            attributeBean.setQualifiedName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
-            attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
-            attributeBean.setAttributeValues(roles);
+        if (attributeStatements != null && !attributeStatements.isEmpty()) {
+            List<AttributeStatementBean> attrStatementBeans = new ArrayList<>();
+            
+            for (AttributeStatement attrStatement : attributeStatements) {
+                AttributeStatementBean attrStatementBean = new AttributeStatementBean();
+                List<AttributeBean> attrBeans = new ArrayList<>();
                 
-            attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
-            callback.setAttributeStatementData(Collections.singletonList(attrBean));
+                for (Attribute attribute : attrStatement.getAttributes()) {
+                    AttributeBean attributeBean = new AttributeBean();
+                    attributeBean.setQualifiedName(attribute.getName());
+                    attributeBean.setNameFormat(attribute.getNameFormat());
+                    List<Object> attributeValues = new ArrayList<>();
+                    for (XMLObject attrVal : attribute.getAttributeValues()) {
+                        attributeValues.add(attrVal.getDOM().getTextContent());
+                    }
+                    attributeBean.setAttributeValues(attributeValues);
+                    attrBeans.add(attributeBean);
+                }
+                attrStatementBean.setSamlAttributes(attrBeans);
+                attrStatementBeans.add(attrStatementBean);
+            }
+            callback.setAttributeStatementData(attrStatementBeans);
         }
     }
     
@@ -119,6 +135,14 @@ public class SAML2CallbackHandler implements CallbackHandler {
     public void setSubject(Subject subject) {
         this.subject = subject;
     }
+
+    public List<AttributeStatement> getAttributeStatements() {
+        return attributeStatements;
+    }
+
+    public void setAttributeStatements(List<AttributeStatement> attributeStatements) {
+        this.attributeStatements = attributeStatements;
+    }
     
     
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/6f06a082/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml b/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
index 701db0b..9014030 100644
--- a/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
+++ b/services/idp/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
@@ -65,10 +65,6 @@
                       result="flowScope.realm"/>
             <evaluate expression="stsClientForRpAction.submit(flowRequestContext, flowScope.realm, flowScope.homerealm)"
                       result="flowScope.rpTokenElement"/>
-            <evaluate expression="tokenSerializer.serialize(flowRequestContext, flowScope.rpTokenElement)"
-                      result="flowScope.rpToken"/>
-            <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
-                      result="flowScope.consumerURL"/>
         </on-entry>
         <evaluate expression="signinParametersCacheAction.storeRPConfigInSession(flowRequestContext)"/>
         <transition to="produceSAMLResponse" />
@@ -80,12 +76,14 @@
         <on-entry>
             <evaluate expression="authnRequestParser.retrieveRequestId(flowRequestContext)" 
                       result="flowScope.requestId"/>
-           <evaluate expression="authnRequestParser.retrieveRequestIssuer(flowRequestContext)" 
+            <evaluate expression="authnRequestParser.retrieveRequestIssuer(flowRequestContext)" 
                       result="flowScope.requestIssuer"/>
+            <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
+                      result="flowScope.consumerURL"/>
         </on-entry>
         <evaluate expression="samlResponseCreator.createSAMLResponse(flowRequestContext, flowScope.idpConfig, flowScope.rpTokenElement,
                                                                      flowScope.consumerURL, flowScope.requestId, flowScope.requestIssuer)"
-                      result="flowScope.rpResponse"/>                                               
+                  result="flowScope.rpResponse"/>                                               
         <transition to="formResponseView" />
     </action-state>
     

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/6f06a082/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
----------------------------------------------------------------------
diff --git a/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java b/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
index 7acad0a..b0f2bea 100644
--- a/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
+++ b/systests/samlsso/src/test/java/org/apache/cxf/fediz/systests/idp/IdpTest.java
@@ -40,6 +40,7 @@ import org.apache.catalina.LifecycleState;
 import org.apache.catalina.connector.Connector;
 import org.apache.catalina.startup.Tomcat;
 import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.fediz.core.ClaimTypes;
 import org.apache.cxf.fediz.core.util.DOMUtils;
 import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
 import org.apache.cxf.rs.security.saml.sso.DefaultAuthnRequestBuilder;
@@ -225,6 +226,15 @@ public class IdpTest {
         org.opensaml.saml.saml2.core.Response samlResponseObject = 
             (org.opensaml.saml.saml2.core.Response)responseObject;
         Assert.assertTrue(authnRequest.getID().equals(samlResponseObject.getInResponseTo()));
+        
+        // Check claims
+        String parsedResponse = DOM2Writer.nodeToString(responseDoc);
+        String claim = ClaimTypes.FIRSTNAME.toString();
+        Assert.assertTrue(parsedResponse.contains(claim));
+        claim = ClaimTypes.LASTNAME.toString();
+        Assert.assertTrue(parsedResponse.contains(claim));
+        claim = ClaimTypes.EMAILADDRESS.toString();
+        Assert.assertTrue(parsedResponse.contains(claim));
 
         webClient.close();
     }
@@ -271,7 +281,7 @@ public class IdpTest {
         
         webClient.close();
     }
-        
+    
     private String encodeAuthnRequest(Element authnRequest) throws IOException {
         String requestMessage = DOM2Writer.nodeToString(authnRequest);