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();
}
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);
}
}
}
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);
}
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;
}
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());
}
Aggregations