Search in sources :

Example 1 with EntityDescriptorMarshaller

use of org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method exportSPMetaData.

private static void exportSPMetaData(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateEncodingException, MarshallingException {
    logger.info("Finding mechanism...");
    String mechanismName = loadOption(cmd, "mechanismName", options);
    MechanismType saml2Mech = loadMechanismType(mechanismName, tt);
    logger.info("...found");
    logger.info("Finding chain...");
    String chainName = loadOption(cmd, "chainName", options);
    AuthChainType act = loadChainType(chainName, tt);
    logger.info("Looking for correct mechanism on the chain...");
    AuthMechType currentMechanism = null;
    for (AuthMechType amt : act.getAuthMech()) {
        if (amt.getName().equalsIgnoreCase(mechanismName)) {
            currentMechanism = amt;
            break;
        }
    }
    if (currentMechanism == null) {
        System.err.println("Unknown chain on mechanism");
        System.exit(1);
    }
    InitializationService.initialize();
    logger.info("loading url base");
    String urlBase = loadOption(cmd, "urlBase", options);
    String url = urlBase + saml2Mech.getUri();
    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);
    String id = "f" + Hex.encodeHexString(idBytes);
    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptorImpl ed = (EntityDescriptorImpl) edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);
    SPSSODescriptorBuilder spb = new SPSSODescriptorBuilder();
    SPSSODescriptorImpl sp = (SPSSODescriptorImpl) spb.buildObject();
    ed.getRoleDescriptors().add(sp);
    HashMap<String, ParamWithValueType> params = new HashMap<String, ParamWithValueType>();
    for (ParamWithValueType pt : currentMechanism.getParams().getParam()) {
        params.put(pt.getName(), pt);
    }
    boolean assertionsSigned = params.get("assertionsSigned") != null && params.get("assertionsSigned").getValue().equalsIgnoreCase("true");
    sp.setWantAssertionsSigned(assertionsSigned);
    sp.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    SingleLogoutServiceBuilder slsb = new SingleLogoutServiceBuilder();
    SingleLogoutService sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sp.getSingleLogoutServices().add(sls);
    sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sp.getSingleLogoutServices().add(sls);
    AssertionConsumerServiceBuilder acsb = new AssertionConsumerServiceBuilder();
    AssertionConsumerService acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    acs.setIndex(0);
    acs.setIsDefault(true);
    sp.getAssertionConsumerServices().add(acs);
    acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    acs.setIndex(1);
    sp.getAssertionConsumerServices().add(acs);
    if (params.get("spSigKey") != null && !params.get("spSigKey").getValue().isEmpty()) {
        String alias = params.get("spSigKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);
        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spSigKey").getValue() + "' not found");
        }
        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);
    }
    if (params.get("spEncKey") != null && !params.get("spEncKey").getValue().isEmpty()) {
        String alias = params.get("spEncKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);
        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spEncKey").getValue() + "' not found");
        }
        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);
    }
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);
    String xml = net.shibboleth.utilities.java.support.xml.SerializeSupport.prettyPrintXML(assertionElement);
    logger.info(xml);
}
Also used : PrivateKey(java.security.PrivateKey) SPSSODescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.SPSSODescriptorBuilder) HashMap(java.util.HashMap) KeyInfoBuilder(org.opensaml.xmlsec.signature.impl.KeyInfoBuilder) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) EntityDescriptorMarshaller(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller) X509Data(org.opensaml.xmlsec.signature.X509Data) EntityDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder) X509DataBuilder(org.opensaml.xmlsec.signature.impl.X509DataBuilder) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SingleLogoutServiceBuilder(org.opensaml.saml.saml2.metadata.impl.SingleLogoutServiceBuilder) MechanismType(com.tremolosecurity.config.xml.MechanismType) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) ParamWithValueType(com.tremolosecurity.config.xml.ParamWithValueType) AuthChainType(com.tremolosecurity.config.xml.AuthChainType) EntityDescriptorImpl(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorImpl) SingleLogoutService(org.opensaml.saml.saml2.metadata.SingleLogoutService) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) X509CertificateBuilder(org.opensaml.xmlsec.signature.impl.X509CertificateBuilder) AuthMechType(com.tremolosecurity.config.xml.AuthMechType) SecureRandom(java.security.SecureRandom) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) IOException(java.io.IOException) Base64DecodingException(org.apache.xml.security.exceptions.Base64DecodingException) ServletException(javax.servlet.ServletException) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SPSSODescriptorImpl(org.opensaml.saml.saml2.metadata.impl.SPSSODescriptorImpl) KeyDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.KeyDescriptorBuilder)

Example 2 with EntityDescriptorMarshaller

use of org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method exportIdPMetadata.

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException, UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {
    InitializationService.initialize();
    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);
    ApplicationType idp = null;
    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }
    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }
    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);
    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();
    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);
    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();
    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);
    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    // ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    IDPSSODescriptor sd = idpssdb.buildObject();
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);
    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }
    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn") && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));
    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
    if (params.get("encKey") != null && !params.get("encKey").isEmpty() && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);
    }
    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty() && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();
        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);
    }
    HashSet<String> nameids = new HashSet<String>();
    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }
    NameIDFormatBuilder nifb = new NameIDFormatBuilder();
    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }
    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);
    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);
    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);
    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential((X509Certificate) ks.getCertificate(signingKey), (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));
        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);
        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }
    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);
    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}
Also used : IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) HashMap(java.util.HashMap) KeyInfoBuilder(org.opensaml.xmlsec.signature.impl.KeyInfoBuilder) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) NameIDFormatBuilder(org.opensaml.saml.saml2.metadata.impl.NameIDFormatBuilder) EntityDescriptorMarshaller(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller) X509Data(org.opensaml.xmlsec.signature.X509Data) SingleSignOnServiceBuilder(org.opensaml.saml.saml2.metadata.impl.SingleSignOnServiceBuilder) EntityDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder) X509DataBuilder(org.opensaml.xmlsec.signature.impl.X509DataBuilder) MarshallingException(org.opensaml.core.xml.io.MarshallingException) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) X509CertificateBuilder(org.opensaml.xmlsec.signature.impl.X509CertificateBuilder) SecureRandom(java.security.SecureRandom) TrustType(com.tremolosecurity.config.xml.TrustType) KeyStoreException(java.security.KeyStoreException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) IOException(java.io.IOException) Base64DecodingException(org.apache.xml.security.exceptions.Base64DecodingException) ServletException(javax.servlet.ServletException) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NameIDFormat(org.opensaml.saml.saml2.metadata.NameIDFormat) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) Signature(org.opensaml.xmlsec.signature.Signature) KeyDescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.KeyDescriptorBuilder) IDPSSODescriptorBuilder(org.opensaml.saml.saml2.metadata.impl.IDPSSODescriptorBuilder)

Aggregations

FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SecureRandom (java.security.SecureRandom)2 UnrecoverableKeyException (java.security.UnrecoverableKeyException)2 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 CertificateException (java.security.cert.CertificateException)2 HashMap (java.util.HashMap)2 ServletException (javax.servlet.ServletException)2 JAXBElement (javax.xml.bind.JAXBElement)2 JAXBException (javax.xml.bind.JAXBException)2 PropertyException (javax.xml.bind.PropertyException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Base64DecodingException (org.apache.xml.security.exceptions.Base64DecodingException)2 MarshallingException (org.opensaml.core.xml.io.MarshallingException)2 UnmarshallingException (org.opensaml.core.xml.io.UnmarshallingException)2 KeyDescriptor (org.opensaml.saml.saml2.metadata.KeyDescriptor)2 EntityDescriptorBuilder (org.opensaml.saml.saml2.metadata.impl.EntityDescriptorBuilder)2 EntityDescriptorMarshaller (org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller)2