Search in sources :

Example 6 with BasicX509Credential

use of org.opensaml.xml.security.x509.BasicX509Credential in project cloudstack by apache.

the class GetServiceProviderMetaDataCmd method authenticate.

@Override
public String authenticate(String command, Map<String, Object[]> params, HttpSession session, InetAddress remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    SAMLMetaDataResponse response = new SAMLMetaDataResponse();
    response.setResponseName(getCommandName());
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException | FactoryConfigurationError e) {
        s_logger.error("OpenSAML Bootstrapping error: " + e.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "OpenSAML Bootstrapping error while creating SP MetaData", params, responseType));
    }
    final SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
    EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
    spEntityDescriptor.setEntityID(spMetadata.getEntityId());
    SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
    spSSODescriptor.setWantAssertionsSigned(true);
    spSSODescriptor.setAuthnRequestsSigned(true);
    X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
    KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject();
    signKeyDescriptor.setUse(UsageType.SIGNING);
    KeyDescriptor encKeyDescriptor = new KeyDescriptorBuilder().buildObject();
    encKeyDescriptor.setUse(UsageType.ENCRYPTION);
    BasicX509Credential signingCredential = new BasicX509Credential();
    signingCredential.setEntityCertificate(spMetadata.getSigningCertificate());
    BasicX509Credential encryptionCredential = new BasicX509Credential();
    encryptionCredential.setEntityCertificate(spMetadata.getEncryptionCertificate());
    try {
        signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingCredential));
        encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(encryptionCredential));
        spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);
        spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor);
    } catch (SecurityException e) {
        s_logger.warn("Unable to add SP X509 descriptors:" + e.getMessage());
    }
    NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject();
    nameIDFormat.setFormat(NameIDType.PERSISTENT);
    spSSODescriptor.getNameIDFormats().add(nameIDFormat);
    NameIDFormat emailNameIDFormat = new NameIDFormatBuilder().buildObject();
    emailNameIDFormat.setFormat(NameIDType.EMAIL);
    spSSODescriptor.getNameIDFormats().add(emailNameIDFormat);
    NameIDFormat transientNameIDFormat = new NameIDFormatBuilder().buildObject();
    transientNameIDFormat.setFormat(NameIDType.TRANSIENT);
    spSSODescriptor.getNameIDFormats().add(transientNameIDFormat);
    AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
    assertionConsumerService.setIndex(1);
    assertionConsumerService.setIsDefault(true);
    assertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    assertionConsumerService.setLocation(spMetadata.getSsoUrl());
    spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
    AssertionConsumerService assertionConsumerService2 = new AssertionConsumerServiceBuilder().buildObject();
    assertionConsumerService2.setIndex(2);
    assertionConsumerService2.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    assertionConsumerService2.setLocation(spMetadata.getSsoUrl());
    spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService2);
    SingleLogoutService ssoService = new SingleLogoutServiceBuilder().buildObject();
    ssoService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    ssoService.setLocation(spMetadata.getSloUrl());
    spSSODescriptor.getSingleLogoutServices().add(ssoService);
    SingleLogoutService ssoService2 = new SingleLogoutServiceBuilder().buildObject();
    ssoService2.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    ssoService2.setLocation(spMetadata.getSloUrl());
    spSSODescriptor.getSingleLogoutServices().add(ssoService2);
    spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);
    spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
    // Add technical contact
    GivenName givenName = new GivenNameBuilder().buildObject();
    givenName.setName(spMetadata.getContactPersonName());
    EmailAddress emailAddress = new EmailAddressBuilder().buildObject();
    emailAddress.setAddress(spMetadata.getContactPersonEmail());
    ContactPerson contactPerson = new ContactPersonBuilder().buildObject();
    contactPerson.setType(ContactPersonTypeEnumeration.TECHNICAL);
    contactPerson.setGivenName(givenName);
    contactPerson.getEmailAddresses().add(emailAddress);
    spEntityDescriptor.getContactPersons().add(contactPerson);
    // Add administrative/support contact
    GivenName givenNameAdmin = new GivenNameBuilder().buildObject();
    givenNameAdmin.setName(spMetadata.getContactPersonName());
    EmailAddress emailAddressAdmin = new EmailAddressBuilder().buildObject();
    emailAddressAdmin.setAddress(spMetadata.getContactPersonEmail());
    ContactPerson contactPersonAdmin = new ContactPersonBuilder().buildObject();
    contactPersonAdmin.setType(ContactPersonTypeEnumeration.ADMINISTRATIVE);
    contactPersonAdmin.setGivenName(givenNameAdmin);
    contactPersonAdmin.getEmailAddresses().add(emailAddressAdmin);
    spEntityDescriptor.getContactPersons().add(contactPersonAdmin);
    Organization organization = new OrganizationBuilder().buildObject();
    OrganizationName organizationName = new OrganizationNameBuilder().buildObject();
    organizationName.setName(new LocalizedString(spMetadata.getOrganizationName(), Locale.getDefault().getLanguage()));
    OrganizationURL organizationURL = new OrganizationURLBuilder().buildObject();
    organizationURL.setURL(new LocalizedString(spMetadata.getOrganizationUrl(), Locale.getDefault().getLanguage()));
    organization.getOrganizationNames().add(organizationName);
    organization.getURLs().add(organizationURL);
    spEntityDescriptor.setOrganization(organization);
    StringWriter stringWriter = new StringWriter();
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(spEntityDescriptor);
        out.marshall(spEntityDescriptor, document);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult streamResult = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
        stringWriter.close();
        response.setMetadata(stringWriter.toString());
    } catch (ParserConfigurationException | IOException | MarshallingException | TransformerException e) {
        if (responseType.equals(HttpUtils.JSON_CONTENT_TYPE)) {
            response.setMetadata("Error creating Service Provider MetaData XML: " + e.getMessage());
        } else {
            return "Error creating Service Provider MetaData XML: " + e.getMessage();
        }
    }
    // For JSON type return serialized response object
    if (responseType.equals(HttpUtils.RESPONSE_TYPE_JSON)) {
        return ApiResponseSerializer.toSerializedString(response, responseType);
    }
    // For other response types return XML
    return stringWriter.toString();
}
Also used : OrganizationName(org.opensaml.saml2.metadata.OrganizationName) EmailAddressBuilder(org.opensaml.saml2.metadata.impl.EmailAddressBuilder) DOMSource(javax.xml.transform.dom.DOMSource) SAMLMetaDataResponse(org.apache.cloudstack.api.response.SAMLMetaDataResponse) Organization(org.opensaml.saml2.metadata.Organization) OrganizationNameBuilder(org.opensaml.saml2.metadata.impl.OrganizationNameBuilder) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) SPSSODescriptorBuilder(org.opensaml.saml2.metadata.impl.SPSSODescriptorBuilder) KeyDescriptor(org.opensaml.saml2.metadata.KeyDescriptor) GivenName(org.opensaml.saml2.metadata.GivenName) NameIDFormatBuilder(org.opensaml.saml2.metadata.impl.NameIDFormatBuilder) LocalizedString(org.opensaml.saml2.metadata.LocalizedString) Document(org.w3c.dom.Document) EntityDescriptorBuilder(org.opensaml.saml2.metadata.impl.EntityDescriptorBuilder) ContactPerson(org.opensaml.saml2.metadata.ContactPerson) SPSSODescriptor(org.opensaml.saml2.metadata.SPSSODescriptor) KeyInfoGenerator(org.opensaml.xml.security.keyinfo.KeyInfoGenerator) ServerApiException(org.apache.cloudstack.api.ServerApiException) StringWriter(java.io.StringWriter) MarshallingException(org.opensaml.xml.io.MarshallingException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ConfigurationException(org.opensaml.xml.ConfigurationException) SingleLogoutServiceBuilder(org.opensaml.saml2.metadata.impl.SingleLogoutServiceBuilder) AssertionConsumerService(org.opensaml.saml2.metadata.AssertionConsumerService) OrganizationBuilder(org.opensaml.saml2.metadata.impl.OrganizationBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAMLProviderMetadata(org.apache.cloudstack.saml.SAMLProviderMetadata) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) GivenNameBuilder(org.opensaml.saml2.metadata.impl.GivenNameBuilder) TransformerException(javax.xml.transform.TransformerException) X509KeyInfoGeneratorFactory(org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory) Marshaller(org.opensaml.xml.io.Marshaller) OrganizationURLBuilder(org.opensaml.saml2.metadata.impl.OrganizationURLBuilder) StreamResult(javax.xml.transform.stream.StreamResult) SingleLogoutService(org.opensaml.saml2.metadata.SingleLogoutService) AssertionConsumerServiceBuilder(org.opensaml.saml2.metadata.impl.AssertionConsumerServiceBuilder) SecurityException(org.opensaml.xml.security.SecurityException) IOException(java.io.IOException) EmailAddress(org.opensaml.saml2.metadata.EmailAddress) ContactPersonBuilder(org.opensaml.saml2.metadata.impl.ContactPersonBuilder) EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) NameIDFormat(org.opensaml.saml2.metadata.NameIDFormat) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) DocumentBuilder(javax.xml.parsers.DocumentBuilder) KeyDescriptorBuilder(org.opensaml.saml2.metadata.impl.KeyDescriptorBuilder) OrganizationURL(org.opensaml.saml2.metadata.OrganizationURL)

Example 7 with BasicX509Credential

use of org.opensaml.xml.security.x509.BasicX509Credential in project ddf by codice.

the class SimpleSign method validateSignatureAndSamlKey.

private void validateSignatureAndSamlKey(Signature signature, SAMLKeyInfo samlKeyInfo) throws SignatureException {
    SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
    try {
        validator.validate(signature);
    } catch (org.opensaml.xmlsec.signature.support.SignatureException e) {
        throw new SignatureException("Error validating the SAMLKey signature", e);
    }
    BasicX509Credential credential = null;
    if (samlKeyInfo.getCerts() != null) {
        credential = new BasicX509Credential(samlKeyInfo.getCerts()[0]);
    } else {
        throw new SignatureException("Can't get X509Certificate or PublicKey to verify signature.");
    }
    ClassLoader threadLoader = null;
    try {
        threadLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(ApacheSantuarioSignatureValidationProviderImpl.class.getClassLoader());
        SignatureValidator.validate(signature, credential);
    } catch (org.opensaml.xmlsec.signature.support.SignatureException e) {
        throw new SignatureException("Error validating the XML signature", e);
    } finally {
        if (threadLoader != null) {
            Thread.currentThread().setContextClassLoader(threadLoader);
        }
    }
}
Also used : BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) ApacheSantuarioSignatureValidationProviderImpl(org.opensaml.xmlsec.signature.support.provider.ApacheSantuarioSignatureValidationProviderImpl)

Example 8 with BasicX509Credential

use of org.opensaml.xml.security.x509.BasicX509Credential in project ddf by codice.

the class SimpleSign method signSamlObject.

public void signSamlObject(SignableSAMLObject samlObject) throws SignatureException {
    X509Certificate[] certificates = getSignatureCertificates();
    String sigAlgo = getSignatureAlgorithm(certificates[0]);
    PrivateKey privateKey = getSignaturePrivateKey();
    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    if (signature == null) {
        throw new SignatureException("Unable to build signature.");
    }
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);
    BasicX509Credential signingCredential = new BasicX509Credential(certificates[0]);
    signingCredential.setPrivateKey(privateKey);
    signature.setSigningCredential(signingCredential);
    X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true);
    try {
        KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException e) {
        throw new SignatureException("Error generating KeyInfo from signing credential", e);
    }
    if (samlObject instanceof Response) {
        List<Assertion> assertions = ((Response) samlObject).getAssertions();
        for (Assertion assertion : assertions) {
            assertion.getSignature().setSigningCredential(signingCredential);
        }
    }
    samlObject.setSignature(signature);
    SAMLObjectContentReference contentRef = (SAMLObjectContentReference) signature.getContentReferences().get(0);
    contentRef.setDigestAlgorithm(SignatureConstants.ALGO_ID_DIGEST_SHA1);
    samlObject.releaseDOM();
    samlObject.releaseChildrenDOM(true);
}
Also used : PrivateKey(java.security.PrivateKey) Assertion(org.opensaml.saml.saml2.core.Assertion) X509Certificate(java.security.cert.X509Certificate) Response(org.opensaml.saml.saml2.core.Response) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) Signature(org.opensaml.xmlsec.signature.Signature) SAMLObjectContentReference(org.opensaml.saml.common.SAMLObjectContentReference) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)

Example 9 with BasicX509Credential

use of org.opensaml.xml.security.x509.BasicX509Credential in project cas by apereo.

the class WsFederationConfiguration method getSigningCredential.

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential
 */
private static Credential getSigningCredential(final Resource resource) {
    try (InputStream inputStream = resource.getInputStream()) {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
        final Credential publicCredential = new BasicX509Credential(certificate);
        LOGGER.debug("Signing credential key retrieved from [{}].", resource);
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return null;
}
Also used : Credential(org.opensaml.security.credential.Credential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) InputStream(java.io.InputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 10 with BasicX509Credential

use of org.opensaml.xml.security.x509.BasicX509Credential in project cas by apereo.

the class WsFederationHelper method getEncryptionCredential.

@SneakyThrows
private static Credential getEncryptionCredential(final WsFederationConfiguration config) {
    // This will need to contain the private keypair in PEM format
    LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey());
    final BufferedReader br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8));
    Security.addProvider(new BouncyCastleProvider());
    LOGGER.debug("Parsing credential private key");
    final PEMParser pemParser = new PEMParser(br);
    final Object privateKeyPemObject = pemParser.readObject();
    final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());
    final KeyPair kp;
    if (privateKeyPemObject instanceof PEMEncryptedKeyPair) {
        LOGGER.debug("Encryption private key is an encrypted keypair");
        final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
        final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(config.getEncryptionPrivateKeyPassword().toCharArray());
        LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password");
        kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
    } else {
        LOGGER.debug("Extracting a keypair from the private key");
        kp = converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
    }
    final X509CertParser certParser = new X509CertParser();
    // This is the certificate shared with ADFS in DER format, i.e certificate.crt
    LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate());
    certParser.engineInit(config.getEncryptionCertificate().getInputStream());
    LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate());
    final X509CertificateObject cert = (X509CertificateObject) certParser.engineRead();
    LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN());
    return new BasicX509Credential(cert, kp.getPrivate());
}
Also used : KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) InputStreamReader(java.io.InputStreamReader) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) X509CertParser(org.bouncycastle.jce.provider.X509CertParser) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) BufferedReader(java.io.BufferedReader) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) SneakyThrows(lombok.SneakyThrows)

Aggregations

BasicX509Credential (org.opensaml.security.x509.BasicX509Credential)12 X509Certificate (java.security.cert.X509Certificate)8 PrivateKey (java.security.PrivateKey)6 X509KeyInfoGeneratorFactory (org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)5 KeyInfo (org.opensaml.xmlsec.signature.KeyInfo)5 Signature (org.opensaml.xmlsec.signature.Signature)5 CryptoType (org.apache.wss4j.common.crypto.CryptoType)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 SignableSAMLObject (org.opensaml.saml.common.SignableSAMLObject)4 IOException (java.io.IOException)3 ServerApiException (org.apache.cloudstack.api.ServerApiException)2 SAMLProviderMetadata (org.apache.cloudstack.saml.SAMLProviderMetadata)2 SamlIdPProperties (org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties)2 Response (org.opensaml.saml.saml2.core.Response)2 SAMLSignatureProfileValidator (org.opensaml.saml.security.impl.SAMLSignatureProfileValidator)2 ApacheSantuarioSignatureValidationProviderImpl (org.opensaml.xmlsec.signature.support.provider.ApacheSantuarioSignatureValidationProviderImpl)2 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)1 UserAccount (com.cloud.user.UserAccount)1 UserAccountVO (com.cloud.user.UserAccountVO)1 BufferedReader (java.io.BufferedReader)1