Search in sources :

Example 26 with KeyDescriptor

use of org.opensaml.saml2.metadata.KeyDescriptor 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 27 with KeyDescriptor

use of org.opensaml.saml2.metadata.KeyDescriptor in project spring-security by spring-projects.

the class OpenSamlMetadataResolver method buildKeys.

private List<KeyDescriptor> buildKeys(Collection<Saml2X509Credential> credentials, UsageType usageType) {
    List<KeyDescriptor> list = new ArrayList<>();
    for (Saml2X509Credential credential : credentials) {
        KeyDescriptor keyDescriptor = buildKeyDescriptor(usageType, credential.getCertificate());
        list.add(keyDescriptor);
    }
    return list;
}
Also used : KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) ArrayList(java.util.ArrayList) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential)

Example 28 with KeyDescriptor

use of org.opensaml.saml2.metadata.KeyDescriptor in project spring-security by spring-projects.

the class OpenSamlMetadataResolver method buildKeyDescriptor.

private KeyDescriptor buildKeyDescriptor(UsageType usageType, java.security.cert.X509Certificate certificate) {
    KeyDescriptor keyDescriptor = build(KeyDescriptor.DEFAULT_ELEMENT_NAME);
    KeyInfo keyInfo = build(KeyInfo.DEFAULT_ELEMENT_NAME);
    X509Certificate x509Certificate = build(X509Certificate.DEFAULT_ELEMENT_NAME);
    X509Data x509Data = build(X509Data.DEFAULT_ELEMENT_NAME);
    try {
        x509Certificate.setValue(new String(Base64.getEncoder().encode(certificate.getEncoded())));
    } catch (CertificateEncodingException ex) {
        throw new Saml2Exception("Cannot encode certificate " + certificate.toString());
    }
    x509Data.getX509Certificates().add(x509Certificate);
    keyInfo.getX509Datas().add(x509Data);
    keyDescriptor.setUse(usageType);
    keyDescriptor.setKeyInfo(keyInfo);
    return keyDescriptor;
}
Also used : KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) CertificateEncodingException(java.security.cert.CertificateEncodingException) Saml2Exception(org.springframework.security.saml2.Saml2Exception) X509Data(org.opensaml.xmlsec.signature.X509Data) X509Certificate(org.opensaml.xmlsec.signature.X509Certificate)

Example 29 with KeyDescriptor

use of org.opensaml.saml2.metadata.KeyDescriptor in project spring-security by spring-projects.

the class OpenSamlMetadataAssertingPartyDetailsConverter method convert.

RelyingPartyRegistration.AssertingPartyDetails.Builder convert(EntityDescriptor descriptor) {
    IDPSSODescriptor idpssoDescriptor = descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
    if (idpssoDescriptor == null) {
        throw new Saml2Exception("Metadata response is missing the necessary IDPSSODescriptor element");
    }
    List<Saml2X509Credential> verification = new ArrayList<>();
    List<Saml2X509Credential> encryption = new ArrayList<>();
    for (KeyDescriptor keyDescriptor : idpssoDescriptor.getKeyDescriptors()) {
        if (keyDescriptor.getUse().equals(UsageType.SIGNING)) {
            List<X509Certificate> certificates = certificates(keyDescriptor);
            for (X509Certificate certificate : certificates) {
                verification.add(Saml2X509Credential.verification(certificate));
            }
        }
        if (keyDescriptor.getUse().equals(UsageType.ENCRYPTION)) {
            List<X509Certificate> certificates = certificates(keyDescriptor);
            for (X509Certificate certificate : certificates) {
                encryption.add(Saml2X509Credential.encryption(certificate));
            }
        }
        if (keyDescriptor.getUse().equals(UsageType.UNSPECIFIED)) {
            List<X509Certificate> certificates = certificates(keyDescriptor);
            for (X509Certificate certificate : certificates) {
                verification.add(Saml2X509Credential.verification(certificate));
                encryption.add(Saml2X509Credential.encryption(certificate));
            }
        }
    }
    if (verification.isEmpty()) {
        throw new Saml2Exception("Metadata response is missing verification certificates, necessary for verifying SAML assertions");
    }
    RelyingPartyRegistration.AssertingPartyDetails.Builder party = OpenSamlAssertingPartyDetails.withEntityDescriptor(descriptor).entityId(descriptor.getEntityID()).wantAuthnRequestsSigned(Boolean.TRUE.equals(idpssoDescriptor.getWantAuthnRequestsSigned())).verificationX509Credentials((c) -> c.addAll(verification)).encryptionX509Credentials((c) -> c.addAll(encryption));
    List<SigningMethod> signingMethods = signingMethods(idpssoDescriptor);
    for (SigningMethod method : signingMethods) {
        party.signingAlgorithms((algorithms) -> algorithms.add(method.getAlgorithm()));
    }
    if (idpssoDescriptor.getSingleSignOnServices().isEmpty()) {
        throw new Saml2Exception("Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests");
    }
    for (SingleSignOnService singleSignOnService : idpssoDescriptor.getSingleSignOnServices()) {
        Saml2MessageBinding binding;
        if (singleSignOnService.getBinding().equals(Saml2MessageBinding.POST.getUrn())) {
            binding = Saml2MessageBinding.POST;
        } else if (singleSignOnService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn())) {
            binding = Saml2MessageBinding.REDIRECT;
        } else {
            continue;
        }
        party.singleSignOnServiceLocation(singleSignOnService.getLocation()).singleSignOnServiceBinding(binding);
        break;
    }
    for (SingleLogoutService singleLogoutService : idpssoDescriptor.getSingleLogoutServices()) {
        Saml2MessageBinding binding;
        if (singleLogoutService.getBinding().equals(Saml2MessageBinding.POST.getUrn())) {
            binding = Saml2MessageBinding.POST;
        } else if (singleLogoutService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn())) {
            binding = Saml2MessageBinding.REDIRECT;
        } else {
            continue;
        }
        String responseLocation = (singleLogoutService.getResponseLocation() == null) ? singleLogoutService.getLocation() : singleLogoutService.getResponseLocation();
        party.singleLogoutServiceLocation(singleLogoutService.getLocation()).singleLogoutServiceResponseLocation(responseLocation).singleLogoutServiceBinding(binding);
        break;
    }
    return party;
}
Also used : X509Certificate(java.security.cert.X509Certificate) Arrays(java.util.Arrays) OpenSamlInitializationService(org.springframework.security.saml2.core.OpenSamlInitializationService) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) XMLObjectProviderRegistry(org.opensaml.core.xml.config.XMLObjectProviderRegistry) Extensions(org.opensaml.saml.saml2.metadata.Extensions) ArrayList(java.util.ArrayList) SigningMethod(org.opensaml.saml.ext.saml2alg.SigningMethod) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) Document(org.w3c.dom.Document) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) XMLObject(org.opensaml.core.xml.XMLObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) EntitiesDescriptor(org.opensaml.saml.saml2.metadata.EntitiesDescriptor) UsageType(org.opensaml.security.credential.UsageType) SingleLogoutService(org.opensaml.saml.saml2.metadata.SingleLogoutService) Collection(java.util.Collection) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) Saml2Exception(org.springframework.security.saml2.Saml2Exception) ConfigurationService(org.opensaml.core.config.ConfigurationService) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) CertificateException(java.security.cert.CertificateException) KeyInfoSupport(org.opensaml.xmlsec.keyinfo.KeyInfoSupport) ParserPool(net.shibboleth.utilities.java.support.xml.ParserPool) List(java.util.List) Element(org.w3c.dom.Element) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) InputStream(java.io.InputStream) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) SingleLogoutService(org.opensaml.saml.saml2.metadata.SingleLogoutService) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) ArrayList(java.util.ArrayList) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) Saml2Exception(org.springframework.security.saml2.Saml2Exception) X509Certificate(java.security.cert.X509Certificate) SigningMethod(org.opensaml.saml.ext.saml2alg.SigningMethod)

Aggregations

KeyDescriptor (org.opensaml.saml.saml2.metadata.KeyDescriptor)27 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)11 Test (org.junit.jupiter.api.Test)9 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)8 X509Certificate (org.opensaml.xmlsec.signature.X509Certificate)8 KeyInfo (org.opensaml.xmlsec.signature.KeyInfo)5 X509Data (org.opensaml.xmlsec.signature.X509Data)5 SingleLogoutService (org.opensaml.saml.saml2.metadata.SingleLogoutService)4 MarshallingException (org.opensaml.core.xml.io.MarshallingException)3 NameIDFormat (org.opensaml.saml.saml2.metadata.NameIDFormat)3 SingleSignOnService (org.opensaml.saml.saml2.metadata.SingleSignOnService)3 SignatureException (org.opensaml.xmlsec.signature.support.SignatureException)3 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 ArrayList (java.util.ArrayList)2 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)2 SPSSODescriptor (org.opensaml.saml.saml2.metadata.SPSSODescriptor)2 Signature (org.opensaml.xmlsec.signature.Signature)2 Saml2Exception (org.springframework.security.saml2.Saml2Exception)2 Saml2X509Credential (org.springframework.security.saml2.core.Saml2X509Credential)2