aboutsummaryrefslogtreecommitdiff
path: root/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java
diff options
context:
space:
mode:
Diffstat (limited to 'id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java')
-rw-r--r--id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java309
1 files changed, 119 insertions, 190 deletions
diff --git a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java
index 06e80dc14..d5f01a4cc 100644
--- a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java
+++ b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignP12.java
@@ -41,6 +41,7 @@ import eu.stork.peps.auth.engine.X509PrincipalUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.NotImplementedException;
import org.bouncycastle.jce.X509Principal;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.SignableSAMLObject;
@@ -74,26 +75,21 @@ import eu.stork.peps.auth.engine.core.SAMLEngineSignI;
import eu.stork.peps.exceptions.SAMLEngineException;
/**
- * The Class SWSign. Class responsible for signing and validating of messages
- * SAML with a certificate store software.
+ * The Class SWSign. Class responsible for signing and validating of messages SAML with a certificate store software.
*
* @author fjquevedo
*/
public final class SignP12 implements SAMLEngineSignI {
/** The logger. */
- private static final Logger LOG = LoggerFactory.getLogger(SignP12.class
- .getName());
-
+ private static final Logger LOG = LoggerFactory.getLogger(SignP12.class.getName());
/** The p12 store. */
private KeyStore p12Store = null;
-
/** The trust store. */
private KeyStore trustStore = null;
-
/**
* Gets the trust store.
*
@@ -107,7 +103,8 @@ public final class SignP12 implements SAMLEngineSignI {
/**
* Sets the trust store.
*
- * @param newTrustStore the new trust store
+ * @param newTrustStore
+ * the new trust store
*/
public void setTrustStore(final KeyStore newTrustStore) {
this.trustStore = newTrustStore;
@@ -123,8 +120,6 @@ public final class SignP12 implements SAMLEngineSignI {
return properties;
}
-
-
/**
* Gets the p12 store.
*
@@ -134,23 +129,21 @@ public final class SignP12 implements SAMLEngineSignI {
return p12Store;
}
-
-
/**
* Sets the p12 store.
*
- * @param newP12Store the new p12 store
+ * @param newP12Store
+ * the new p12 store
*/
public void setP12Store(final KeyStore newP12Store) {
this.p12Store = newP12Store;
}
-
-
/**
* Sets the properties.
*
- * @param newProperties the new properties
+ * @param newProperties
+ * the new properties
*/
public void setProperties(final Properties newProperties) {
this.properties = newProperties;
@@ -159,13 +152,14 @@ public final class SignP12 implements SAMLEngineSignI {
/** The SW sign prop. */
private Properties properties = null;
-
/**
* Initialize the file configuration.
*
- * @param fileConf name of the file configuration
+ * @param fileConf
+ * name of the file configuration
*
- * @throws SAMLEngineException error at the load from file configuration
+ * @throws SAMLEngineException
+ * error at the load from file configuration
*/
@Override
public void init(final String fileConf) throws SAMLEngineException {
@@ -173,25 +167,25 @@ public final class SignP12 implements SAMLEngineSignI {
properties = new Properties();
try {
try {
- LOG.debug("Fichero a cargar " + fileConf);
+ LOG.debug("Loading " + fileConf);
fileProperties = new FileInputStream(fileConf);
properties.loadFromXML(fileProperties);
} catch (Exception e) {
- LOG.error("Fallo al cargar el recurso externo. Se reintenta como fichero interno.");
+ LOG.error("Failed to load external resource. Retrieving internal file.");
fileProperties = SignP12.class.getResourceAsStream("/" + fileConf);
if (fileProperties == null) {
fileProperties = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileConf);
if (fileProperties == null) {
Enumeration<URL> files = ClassLoader.getSystemClassLoader().getResources(fileConf);
if (files != null && files.hasMoreElements()) {
- LOG.info("Se han encontrado recurso/s. Se toma el primero.");
+ LOG.info("Found /s.");
fileProperties = ClassLoader.getSystemClassLoader().getResourceAsStream(files.nextElement().getFile());
} else {
- throw new IOException("No se pudo recuperar el fichero: " + fileConf, e);
+ throw new IOException("Could not load file: " + fileConf, e);
}
}
}
- LOG.debug("Recuperados " + fileProperties.available() + " bytes");
+ LOG.debug("Recovered " + fileProperties.available() + " bytes");
properties.loadFromXML(fileProperties);
}
} catch (InvalidPropertiesFormatException e) {
@@ -209,7 +203,7 @@ public final class SignP12 implements SAMLEngineSignI {
* Gets the certificate.
*
* @return the X509Certificate
- *
+ *
*/
@Override
public X509Certificate getCertificate() {
@@ -219,16 +213,17 @@ public final class SignP12 implements SAMLEngineSignI {
/**
* Sign the token SAML.
*
- * @param tokenSaml token SAML
+ * @param tokenSaml
+ * token SAML
*
* @return the X509Certificate signed.
*
- * @throws SAMLEngineException error at sign SAML token
+ * @throws SAMLEngineException
+ * error at sign SAML token
*
*/
@Override
- public SAMLObject sign(final SignableSAMLObject tokenSaml)
- throws SAMLEngineException {
+ public SAMLObject sign(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
LOG.info("Start Sign process");
try {
@@ -240,30 +235,24 @@ public final class SignP12 implements SAMLEngineSignI {
X509Certificate certificate;
boolean find = false;
- for (final Enumeration<String> e = p12Store.aliases(); e
- .hasMoreElements() && !find;) {
+ for (final Enumeration<String> e = p12Store.aliases(); e.hasMoreElements() && !find;) {
aliasCert = e.nextElement();
- certificate = (X509Certificate) p12Store
- .getCertificate(aliasCert);
+ certificate = (X509Certificate) p12Store.getCertificate(aliasCert);
- final String serialNum = certificate.getSerialNumber()
- .toString(16);
+ final String serialNum = certificate.getSerialNumber().toString(16);
X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName());
X509Principal issuerDNConf = new X509Principal(issuer);
- if(serialNum.equalsIgnoreCase(serialNumber)
- && X509PrincipalUtil.equals(issuerDN, issuerDNConf)){
+ if (serialNum.equalsIgnoreCase(serialNumber) && X509PrincipalUtil.X509equals(issuerDN, issuerDNConf)) {
alias = aliasCert;
find = true;
}
}
- certificate = (X509Certificate) p12Store
- .getCertificate(alias);
- final PrivateKey privateKey = (PrivateKey) p12Store.getKey(
- alias, properties.getProperty("keyPassword").toCharArray());
+ certificate = (X509Certificate) p12Store.getCertificate(alias);
+ final PrivateKey privateKey = (PrivateKey) p12Store.getKey(alias, properties.getProperty("keyPassword").toCharArray());
LOG.info("Recover BasicX509Credential.");
final BasicX509Credential credential = new BasicX509Credential();
@@ -275,102 +264,73 @@ public final class SignP12 implements SAMLEngineSignI {
credential.setPrivateKey(privateKey);
LOG.debug("Begin signature with openSaml");
- final Signature signature = (Signature) org.opensaml.xml.Configuration
- .getBuilderFactory().getBuilder(
- Signature.DEFAULT_ELEMENT_NAME).buildObject(
- Signature.DEFAULT_ELEMENT_NAME);
+ final Signature signature = (Signature) org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME);
signature.setSigningCredential(credential);
- /*signature.setSignatureAlgorithm(
- SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);*/
- signature.setSignatureAlgorithm(
- SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
-
- final SecurityConfiguration secConfiguration = org.opensaml.xml.Configuration
- .getGlobalSecurityConfiguration();
- final NamedKeyInfoGeneratorManager keyInfoManager = secConfiguration
- .getKeyInfoGeneratorManager();
- final KeyInfoGeneratorManager keyInfoGenManager = keyInfoManager
- .getDefaultManager();
- final KeyInfoGeneratorFactory keyInfoGenFac = keyInfoGenManager
- .getFactory(credential);
- final KeyInfoGenerator keyInfoGenerator = keyInfoGenFac
- .newInstance();
+ /*
+ * signature.setSignatureAlgorithm( SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
+ */
+ signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
+
+ final SecurityConfiguration secConfiguration = org.opensaml.xml.Configuration.getGlobalSecurityConfiguration();
+ final NamedKeyInfoGeneratorManager keyInfoManager = secConfiguration.getKeyInfoGeneratorManager();
+ final KeyInfoGeneratorManager keyInfoGenManager = keyInfoManager.getDefaultManager();
+ final KeyInfoGeneratorFactory keyInfoGenFac = keyInfoGenManager.getFactory(credential);
+ final KeyInfoGenerator keyInfoGenerator = keyInfoGenFac.newInstance();
final KeyInfo keyInfo = keyInfoGenerator.generate(credential);
signature.setKeyInfo(keyInfo);
- signature.setCanonicalizationAlgorithm(
- SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
-
- //Create a second signature which will be used when signing assertion and response
- final Signature signature2 = (Signature) org.opensaml.xml.Configuration
- .getBuilderFactory().getBuilder(
- Signature.DEFAULT_ELEMENT_NAME).buildObject(
- Signature.DEFAULT_ELEMENT_NAME);
- final SecurityConfiguration secConfiguration2 = org.opensaml.xml.Configuration
- .getGlobalSecurityConfiguration();
- final NamedKeyInfoGeneratorManager keyInfoManager2 = secConfiguration2
- .getKeyInfoGeneratorManager();
- final KeyInfoGeneratorManager keyInfoGenManager2 = keyInfoManager2
- .getDefaultManager();
- final KeyInfoGeneratorFactory keyInfoGenFac2 = keyInfoGenManager2
- .getFactory(credential);
- final KeyInfoGenerator keyInfoGenerator2 = keyInfoGenFac2
- .newInstance();
+ signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
+
+ // Create a second signature which will be used when signing assertion and response
+ final Signature signature2 = (Signature) org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME);
+ final SecurityConfiguration secConfiguration2 = org.opensaml.xml.Configuration.getGlobalSecurityConfiguration();
+ final NamedKeyInfoGeneratorManager keyInfoManager2 = secConfiguration2.getKeyInfoGeneratorManager();
+ final KeyInfoGeneratorManager keyInfoGenManager2 = keyInfoManager2.getDefaultManager();
+ final KeyInfoGeneratorFactory keyInfoGenFac2 = keyInfoGenManager2.getFactory(credential);
+ final KeyInfoGenerator keyInfoGenerator2 = keyInfoGenFac2.newInstance();
KeyInfo keyInfo2 = keyInfoGenerator2.generate(credential);
signature2.setSigningCredential(credential);
- signature2.setSignatureAlgorithm(
- SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
+ signature2.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
signature2.setKeyInfo(keyInfo2);
- signature2.setCanonicalizationAlgorithm(
- SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
-
+ signature2.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
LOG.info("Marshall samlToken.");
String qn = tokenSaml.getElementQName().toString();
- if (qn.endsWith(CustomAttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME))
- {
+ if (qn.endsWith(CustomAttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME)) {
tokenSaml.setSignature(signature);
CustomAttributeQueryMarshaller mars = new CustomAttributeQueryMarshaller();
mars.marshall(tokenSaml);
Signer.signObject(signature);
- }
- else if (qn.endsWith(Response.DEFAULT_ELEMENT_LOCAL_NAME) && !qn.contains(LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME))
- {
- Response res = (Response)tokenSaml;
+ } else if (qn.endsWith(Response.DEFAULT_ELEMENT_LOCAL_NAME) && !qn.contains(LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME)) {
+ Response res = (Response) tokenSaml;
List<Assertion> asserts = res.getAssertions();
- //If multiple assertions we just sign the response and not the assertion
- if (asserts.size() > 1)
- {
+ // If multiple assertions we just sign the response and not the assertion
+ if (asserts.size() > 1) {
tokenSaml.setSignature(signature);
- org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml)
- .marshall(tokenSaml);
+ org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml);
LOG.info("Sign samlToken.");
Signer.signObject(signature);
}
- //If single assertion we sign the assertion and response
- else
- {
+ // If single assertion we sign the assertion and response
+ else {
Assertion assertion = asserts.get(0);
- assertion.setSignature(signature);
+ assertion.setSignature(signature);
tokenSaml.setSignature(signature2);
- org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml)
- .marshall(tokenSaml);
+ org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml);
LOG.info("Sign samlToken.");
Signer.signObject(signature);
Signer.signObject(signature2);
}
}
- //Normally we just sign the total saml response
- else
- {
+ // Normally we just sign the total saml response
+ else {
tokenSaml.setSignature(signature);
- org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml)
- .marshall(tokenSaml);
+ org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml);
LOG.info("Sign samlToken.");
Signer.signObject(signature);
}
@@ -401,22 +361,22 @@ public final class SignP12 implements SAMLEngineSignI {
/**
* Validate signature.
*
- * @param tokenSaml token SAML
+ * @param tokenSaml
+ * token SAML
*
* @return the SAMLObject validated.
*
- * @throws SAMLEngineException error validate signature
+ * @throws SAMLEngineException
+ * error validate signature
*
*/
@Override
- public SAMLObject validateSignature(final SignableSAMLObject tokenSaml)
- throws SAMLEngineException {
+ public SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
LOG.info("Start signature validation.");
try {
// Validate structure signature
- final SAMLSignatureProfileValidator sigProfValidator =
- new SAMLSignatureProfileValidator();
+ final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
try {
// Indicates signature id conform to SAML Signature profile
sigProfValidator.validate(tokenSaml.getSignature());
@@ -430,64 +390,43 @@ public final class SignP12 implements SAMLEngineSignI {
final List<Credential> trustCred = new ArrayList<Credential>();
- for (final Enumeration<String> e = trustStore.aliases(); e
- .hasMoreElements();)
- {
+ for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) {
aliasCert = e.nextElement();
final BasicX509Credential credential = new BasicX509Credential();
- certificate = (X509Certificate) trustStore
- .getCertificate(aliasCert);
+ certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
credential.setEntityCertificate(certificate);
trustCred.add(credential);
}
final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();
- final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo
- .getX509Datas().get(0).getX509Certificates().get(0);
+ final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0).getX509Certificates().get(0);
- final CertificateFactory certFact = CertificateFactory
- .getInstance("X.509");
- final ByteArrayInputStream bis = new ByteArrayInputStream(Base64
- .decode(xmlCert.getValue()));
- final X509Certificate cert = (X509Certificate) certFact
- .generateCertificate(bis);
+ final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
+ final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
+ final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);
// Exist only one certificate
final BasicX509Credential entityX509Cred = new BasicX509Credential();
entityX509Cred.setEntityCertificate(cert);
- /* A better use of PKI based validation but not wanted for STORK...
- boolean trusted = false;
-
- for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();)
- {
- aliasCert = e.nextElement();
- certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
- try {
- cert.verify(certificate.getPublicKey());
- trusted = true;
- break;
- }
- catch (Exception ex) {
- //Do nothing - cert not trusted yet
- }
- }
-
- if (!trusted)
- throw new SAMLEngineException("Certificate is not trusted.");*/
+ /*
+ * A better use of PKI based validation but not wanted for STORK... boolean trusted = false;
+ *
+ * for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) { aliasCert = e.nextElement(); certificate = (X509Certificate) trustStore.getCertificate(aliasCert); try {
+ * cert.verify(certificate.getPublicKey()); trusted = true; break; } catch (Exception ex) { //Do nothing - cert not trusted yet } }
+ *
+ * if (!trusted) throw new SAMLEngineException("Certificate is not trusted.");
+ */
// Validate trust certificates
- final ExplicitKeyTrustEvaluator keyTrustEvaluator =
- new ExplicitKeyTrustEvaluator();
- if (!keyTrustEvaluator.validate(entityX509Cred, trustCred))
- {
+ final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();
+ if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
throw new SAMLEngineException("Certificate it is not trusted.");
}
// Validate signature
- final SignatureValidator sigValidator = new SignatureValidator(
- entityX509Cred);
+ final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
sigValidator.validate(tokenSaml.getSignature());
} catch (ValidationException e) {
@@ -503,11 +442,11 @@ public final class SignP12 implements SAMLEngineSignI {
return tokenSaml;
}
-
/**
* Load cryptographic service provider.
*
- * @throws SAMLEngineException the SAML engine exception
+ * @throws SAMLEngineException
+ * the SAML engine exception
*/
@Override
public void loadCryptServiceProvider() throws SAMLEngineException {
@@ -517,48 +456,38 @@ public final class SignP12 implements SAMLEngineSignI {
FileInputStream fisTrustStore = null;
try {
-// // Dynamically register Bouncy Castle provider.
-// boolean found = false;
-// // Check if BouncyCastle is already registered as a provider
-// final Provider[] providers = Security.getProviders();
-// for (int i = 0; i < providers.length; i++) {
-// if (providers[i].getName().equals(
-// BouncyCastleProvider.PROVIDER_NAME)) {
-// found = true;
-// }
-// }
-//
-// // Register only if the provider has not been previously registered
-// if (!found) {
-// LOG.debug("SAMLCore: Register Bouncy Castle provider.");
-// Security.insertProviderAt(new BouncyCastleProvider(), Security
-// .getProviders().length);
-// }
-
- p12Store = KeyStore.getInstance(properties
- .getProperty("keystoreType"));
-
- fis = new FileInputStream(properties
- .getProperty("keystorePath"));
-
- p12Store.load(fis, properties.getProperty(
- "keyStorePassword").toCharArray());
-
-
- trustStore = KeyStore.getInstance(properties
- .getProperty("trustStoreType"));
-
- fisTrustStore = new FileInputStream(properties
- .getProperty("trustStorePath"));
- trustStore.load(fisTrustStore, properties.getProperty(
- "trustStorePassword").toCharArray());
+ // Dynamically register Bouncy Castle provider.
+ boolean found = false;
+ // Check if BouncyCastle is already registered as a provider
+ final Provider[] providers = Security.getProviders();
+ for (int i = 0; i < providers.length; i++) {
+ if (providers[i].getName().equals(BouncyCastleProvider.PROVIDER_NAME)) {
+ found = true;
+ }
+ }
+
+ // Register only if the provider has not been previously registered
+ if (!found) {
+ LOG.debug("SAMLCore: Register Bouncy Castle provider.");
+ Security.insertProviderAt(new BouncyCastleProvider(), Security.getProviders().length);
+ }
+
+ p12Store = KeyStore.getInstance(properties.getProperty("keystoreType"));
+
+ fis = new FileInputStream(properties.getProperty("keystorePath"));
+
+ p12Store.load(fis, properties.getProperty("keyStorePassword").toCharArray());
+
+ trustStore = KeyStore.getInstance(properties.getProperty("trustStoreType"));
+
+ fisTrustStore = new FileInputStream(properties.getProperty("trustStorePath"));
+ trustStore.load(fisTrustStore, properties.getProperty("trustStorePassword").toCharArray());
} catch (Exception e) {
- throw new SAMLEngineException(
- "Error loading CryptographicServiceProvider", e);
- } finally {
+ throw new SAMLEngineException("Error loading CryptographicServiceProvider", e);
+ } finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(fisTrustStore);
- }
+ }
}
}