diff options
55 files changed, 2307 insertions, 470 deletions
diff --git a/eaaf_core/src/main/resources/eaaf_core.beans.xml b/eaaf_core/src/main/resources/eaaf_core.beans.xml index 2f87275d..9806664c 100644 --- a/eaaf_core/src/main/resources/eaaf_core.beans.xml +++ b/eaaf_core/src/main/resources/eaaf_core.beans.xml @@ -11,6 +11,8 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + <import resource="classpath:/spring/eaaf_utils.beans.xml"/> + <bean id="httpClientFactory" class="at.gv.egiz.eaaf.core.impl.utils.HttpClientFactory" /> diff --git a/eaaf_core/src/test/resources/SpringTest-context_authManager.xml b/eaaf_core/src/test/resources/SpringTest-context_authManager.xml index 0d269361..d7b148d0 100644 --- a/eaaf_core/src/test/resources/SpringTest-context_authManager.xml +++ b/eaaf_core/src/test/resources/SpringTest-context_authManager.xml @@ -9,6 +9,8 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + <import resource="classpath:/spring/eaaf_utils.beans.xml"/> + <bean id="TestAuthenticationDataBuilder" class="at.gv.egiz.eaaf.core.impl.idp.auth.TestAuthenticationDataBuilder" /> diff --git a/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml b/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml index 77d70740..295bf151 100644 --- a/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml +++ b/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml @@ -9,6 +9,8 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + <import resource="classpath:/spring/eaaf_utils.beans.xml"/> + <bean id="TestAuthenticationDataBuilder" class="at.gv.egiz.eaaf.core.impl.idp.auth.TestAuthenticationDataBuilder" /> diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafFactoryException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafFactoryException.java new file mode 100644 index 00000000..4e2a0242 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafFactoryException.java @@ -0,0 +1,28 @@ +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafFactoryException extends EaafException { + + private static final long serialVersionUID = 4710605711787308220L; + + /** + * In case that a factory can not build an object. + * + * @param errorId ErrorCode + * @param params Message parameters + * @param e Exception + */ + public EaafFactoryException(String errorId, Object[] params, Throwable e) { + super(errorId, params, e); + } + + /** + * In case that a factory can not build an object. + * + * @param errorId ErrorCode + * @param params Message parameters + */ + public EaafFactoryException(String errorId, Object[] params) { + super(errorId, params); + } + +} diff --git a/eaaf_core_utils/pom.xml b/eaaf_core_utils/pom.xml index 84ab46f5..6392fb76 100644 --- a/eaaf_core_utils/pom.xml +++ b/eaaf_core_utils/pom.xml @@ -42,6 +42,11 @@ </dependency> <dependency> + <groupId>at.asitplus.hsmfacade</groupId> + <artifactId>provider</artifactId> + </dependency> + + <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/exception/EaafKeyAccessException.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/exception/EaafKeyAccessException.java new file mode 100644 index 00000000..f9abd6d9 --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/exception/EaafKeyAccessException.java @@ -0,0 +1,22 @@ +package at.gv.egiz.eaaf.core.exception; + +import at.gv.egiz.eaaf.core.exceptions.EaafException; + +public class EaafKeyAccessException extends EaafException { + + private static final long serialVersionUID = -2641273589744430903L; + + public static final String ERROR_CODE_08 = "internal.keystore.08"; + public static final String ERROR_CODE_09 = "internal.keystore.09"; + + public EaafKeyAccessException(String errorCode, String... params) { + super(errorCode, new Object[] {params}); + + } + + public EaafKeyAccessException(String errorCode, Throwable e, String... params) { + super(errorCode, new Object[] {params}, e); + + } + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreFactory.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreFactory.java new file mode 100644 index 00000000..5e6ca34b --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreFactory.java @@ -0,0 +1,257 @@ +package at.gv.egiz.eaaf.core.impl.credential; + +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; + +import at.asitplus.hsmfacade.provider.HsmFacadeProvider; +import at.asitplus.hsmfacade.provider.RemoteKeyStoreLoadParameter; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafFactoryException; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EaafKeyStoreFactory { + + public static final String CONFIG_PROP_HSM_FACADE_HOST = "security.hsmfacade.host"; + public static final String CONFIG_PROP_HSM_FACADE_PORT = "security.hsmfacade.port"; + public static final String CONFIG_PROP_HSM_FACADE_SSLTRUST = "security.hsmfacade.trustedsslcert"; + public static final String CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME = "security.hsmfacade.username"; + public static final String CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD = "security.hsmfacade.password"; + public static final String CONFIG_PROP_HSM_FACADE_HSM_NAME = "security.hsmfacade.hsmname"; + + public static final String ERRORCODE_00 = "internal.keystore.00"; + public static final String ERRORCODE_01 = "internal.keystore.01"; + public static final String ERRORCODE_02 = "internal.keystore.02"; + public static final String ERRORCODE_03 = "internal.keystore.03"; + public static final String ERRORCODE_04 = "internal.keystore.04"; + public static final String ERRORCODE_05 = "internal.keystore.05"; + public static final String ERRORCODE_06 = "internal.keystore.06"; + public static final String ERRORCODE_07 = "internal.keystore.07"; + + private static final String HSM_FACADE_PROVIDER = "HsmFacade"; + private static final String HSM_FACADE_KEYSTORE_TYPE = "RemoteKeyStore"; + + @Autowired + private IConfiguration basicConfig; + @Autowired + private ResourceLoader resourceLoader; + + private boolean isHsmFacadeInitialized = false; + + /** + * Get a new KeyStore based on a KeyStore configuration-object. + * + * @param config KeyStore configuration + * @return new KeyStore instance + * @throws EaafException In case of a KeyStore initialization error + */ + public KeyStore buildNewKeyStore(KeyStoreConfiguration config) throws EaafException { + log.trace("Starting KeyStore generation based on configuration object ... "); + if (KeyStoreType.PKCS12.equals(config.getKeyStoreType()) + || KeyStoreType.JKS.equals(config.getKeyStoreType())) { + return getKeyStoreFromFileSystem(config); + + } else if (KeyStoreType.HSMFACADE.equals(config.getKeyStoreType())) { + if (isHsmFacadeInitialized) { + return getKeyStoreFromHsmFacade(config); + + } else { + log.error("HSMFacade can NOT be used for KeyStore: {} because {} is not initialized", + config.getFriendlyName()); + throw new EaafConfigurationException(ERRORCODE_00, + new Object[] { config.getFriendlyName() }); + + } + + } else if (KeyStoreType.PKCS11.equals(config.getKeyStoreType())) { + log.warn("KeyStoreType: {} is NOT supported", config.getKeyStoreType()); + throw new EaafConfigurationException(ERRORCODE_02, + new Object[] { config.getFriendlyName(), config.getKeyStoreType() }); + + } else { + log.warn("KeyStoreType: {} is unrecognized", config.getKeyStoreType()); + throw new EaafConfigurationException(ERRORCODE_01, + new Object[] { config.getFriendlyName() }); + + } + } + + /** + * Get the initialization state of the HSM Facade module. + * + * @return true if HSM Facade is available, otherwise false + */ + public boolean isHsmFacadeInitialized() { + return isHsmFacadeInitialized; + + } + + @PostConstruct + private void initialize() throws EaafException { + + final String hsmFacadeHost = basicConfig.getBasicConfiguration(CONFIG_PROP_HSM_FACADE_HOST); + if (StringUtils.isNotEmpty(hsmFacadeHost)) { + log.debug("Find host for HSMFacade. Starting crypto provider initialization ... "); + try { + final int port = Integer.parseUnsignedInt( + getConfigurationParameter(CONFIG_PROP_HSM_FACADE_PORT)); + final String clientUsername = + getConfigurationParameter(CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME); + final String clientPassword = + getConfigurationParameter(CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD); + final String hsmName = + getConfigurationParameter(CONFIG_PROP_HSM_FACADE_HSM_NAME); + + final HsmFacadeProvider provider = HsmFacadeProvider.Companion.getInstance(); + provider.init(getHsmFacadeTrustSslCertificate(), clientUsername, clientPassword, hsmFacadeHost, port, + hsmName); + Security.addProvider(provider); + isHsmFacadeInitialized = true; + log.info("HSM Facade is initialized. {} can provide KeyStores based on remote HSM", + EaafKeyStoreFactory.class.getSimpleName()); + + } catch (final EaafException e) { + throw e; + + } catch (final Exception e) { + log.error("HSM Facade initialization FAILED with an generic error.", e); + throw new EaafConfigurationException(ERRORCODE_03, new Object[] { e.getMessage() }, e); + } + + } else { + log.info("HSM Facade is not configurated. {} can only provide software keystores", + EaafKeyStoreFactory.class.getSimpleName()); + + } + + } + + private KeyStore getKeyStoreFromFileSystem(KeyStoreConfiguration config) throws EaafConfigurationException, + EaafFactoryException { + try { + final String keyStorePath = checkConfigurationParameter(config.getSoftKeyStoreFilePath(), + ERRORCODE_06, config.getFriendlyName(), "Software-KeyStore missing filepath to KeyStore"); + + final String keyStorePassword = checkConfigurationParameter(config.getSoftKeyStorePassword(), + ERRORCODE_06, config.getFriendlyName(), "Software-KeyStore missing Password for KeyStore"); + + final String absKeyStorePath = FileUtils.makeAbsoluteUrl(keyStorePath, basicConfig + .getConfigurationRootDirectory()); + final Resource ressource = resourceLoader.getResource(absKeyStorePath); + if (!ressource.exists()) { + throw new EaafConfigurationException(ERRORCODE_05, + new Object[] { CONFIG_PROP_HSM_FACADE_SSLTRUST, + "File not found at: " + absKeyStorePath }); + + } + + final InputStream is = ressource.getInputStream(); + final KeyStore keyStore = KeyStoreUtils.loadKeyStore(is, keyStorePassword); + is.close(); + if (keyStore == null) { + throw new EaafFactoryException(ERRORCODE_06, + new Object[] { config.getFriendlyName(), "KeyStore not valid or password wrong" }); + + } + + return keyStore; + + } catch (KeyStoreException | IOException e) { + log.error("Software KeyStore initialization FAILED with an generic error.", e); + throw new EaafConfigurationException(ERRORCODE_03, new Object[] { e.getMessage() }, e); + + } + } + + private KeyStore getKeyStoreFromHsmFacade(KeyStoreConfiguration config) + throws EaafFactoryException, EaafConfigurationException { + final String keyStoreName = checkConfigurationParameter(config.getKeyStoreName(), + ERRORCODE_06, config.getFriendlyName(), "KeyStoreName missing for HSM Facade"); + + try { + final KeyStore keyStore = KeyStore.getInstance(HSM_FACADE_KEYSTORE_TYPE, HSM_FACADE_PROVIDER); + keyStore.load(new RemoteKeyStoreLoadParameter(keyStoreName)); + return keyStore; + + } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException + | NoSuchProviderException e) { + log.error("Can not initialize KeyStore: {} with reason: {}", + config.getFriendlyName(), e.getMessage()); + throw new EaafFactoryException(ERRORCODE_06, + new Object[] { config.getFriendlyName(), e.getMessage() }, e); + + } + } + + private X509Certificate getHsmFacadeTrustSslCertificate() throws EaafConfigurationException { + try { + final String certFilePath = getConfigurationParameter(CONFIG_PROP_HSM_FACADE_SSLTRUST); + + final String absolutCertFilePath = FileUtils.makeAbsoluteUrl( + certFilePath, basicConfig.getConfigurationRootDirectory()); + final Resource certFile = resourceLoader.getResource(absolutCertFilePath); + + if (!certFile.exists()) { + throw new EaafConfigurationException(ERRORCODE_05, + new Object[] { CONFIG_PROP_HSM_FACADE_SSLTRUST, + "File not found at: " + absolutCertFilePath }); + + } + + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certFile + .getInputStream()); + + } catch (final EaafConfigurationException e) { + throw e; + + } catch (CertificateException | IOException e) { + log.error("Can not load trusted server-certificate for HSM-Facade. Reason: {}", e.getMessage()); + throw new EaafConfigurationException(ERRORCODE_05, + new Object[] { CONFIG_PROP_HSM_FACADE_SSLTRUST, e.getMessage() }, e); + + } + } + + @Nonnull + private String getConfigurationParameter(@Nonnull String configParamKey) + throws EaafConfigurationException { + return checkConfigurationParameter( + basicConfig.getBasicConfiguration(configParamKey), ERRORCODE_04, configParamKey); + + } + + @Nonnull + private String checkConfigurationParameter(@Nullable String configParam, @Nonnull String errorCode, + @Nonnull String... errorParams) + throws EaafConfigurationException { + if (StringUtils.isEmpty(configParam)) { + throw new EaafConfigurationException(errorCode, new Object[] { errorParams }); + + } + return configParam; + + } + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreUtils.java new file mode 100644 index 00000000..b4b44724 --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/EaafKeyStoreUtils.java @@ -0,0 +1,147 @@ +package at.gv.egiz.eaaf.core.impl.credential; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import at.gv.egiz.eaaf.core.exception.EaafKeyAccessException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EaafKeyStoreUtils { + private static final String ERROR_MSG_REASON = "Maybe 'Alias' is not valid"; + private static final String ERROR_MSG_1 = "Can NOT access key: {} in KeyStore: {}. Reason: {}"; + private static final String ERROR_MSG_2 = "Key: {} will be NOT available"; + + /** + * Read all certificates from a {@link KeyStore}. + * + * @param keyStore KeyStore with certificates + * @return {@link List} of {@link X509Certificate}, but never null + * @throws KeyStoreException In case of an error during KeyStore operations + */ + @Nonnull + public static List<X509Certificate> readCertsFromKeyStore(@Nonnull final KeyStore keyStore) throws KeyStoreException { + final List<X509Certificate> result = new ArrayList<>(); + + final Enumeration<String> aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + final String el = aliases.nextElement(); + log.trace("Process TrustStoreEntry: " + el); + if (keyStore.isCertificateEntry(el)) { + final Certificate cert = keyStore.getCertificate(el); + if (cert != null && cert instanceof X509Certificate) { + result.add((X509Certificate) cert); + } else { + log.info("Can not process entry: {}. Reason: {}", el, cert != null ? cert.getType() : "cert is null"); + } + + } + } + + return Collections.unmodifiableList(result); + } + + /** + * Get a specific private Key and the corresponding certificate from a {@link KeyStore}. + * + * @param keyStore KeyStore with certificates + * @param keyAlias Alias of the entry + * @param keyPassword Password to access the Key + * @param isRequired if true, the method throw an {@link EaafKeyAccessException} + * if the key is not available or invalid + * @param friendlyName Name of the KeyStore for logging purposes + * @return A {@link Pair} of {@link Key} and {@link X509Certificate} for this alias, + * or maybe null if isRequired was <code>false</code> + * @throws EaafKeyAccessException In case of an error during KeyStore operations + */ + @Nullable + public static Pair<Key, X509Certificate[]> getPrivateKeyAndCertificates(@Nonnull KeyStore keyStore, + @Nonnull String keyAlias, @Nullable char[] keyPassword, boolean isRequired, @Nonnull String friendlyName) + throws EaafKeyAccessException { + try { + Key privKey = keyStore.getKey(keyAlias, keyPassword); + if (privKey != null) { + final Certificate[] certChainSigning = keyStore.getCertificateChain(keyAlias); + X509Certificate[] certChain = new X509Certificate[certChainSigning.length]; + + for (int i = 0; i < certChainSigning.length; i++) { + if (certChainSigning[i] instanceof X509Certificate) { + certChain[i] = (X509Certificate) certChainSigning[i]; + } else { + log.warn("NO X509 certificate for signing: " + certChainSigning[i].getType()); + } + + } + + Pair<Key, X509Certificate[]> keyResult = Pair.newInstance(privKey, certChain); + validateKeyResult(keyResult, friendlyName, keyAlias); + return keyResult; + + } else { + if (isRequired) { + log.warn(ERROR_MSG_1, + keyAlias, friendlyName, ERROR_MSG_REASON); + throw new EaafKeyAccessException(EaafKeyAccessException.ERROR_CODE_09, + friendlyName, keyAlias, ERROR_MSG_REASON); + + } else { + log.info(ERROR_MSG_1, + keyAlias, friendlyName, ERROR_MSG_REASON); + log.info(ERROR_MSG_2, keyAlias); + + } + } + + } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) { + if (isRequired) { + log.warn(ERROR_MSG_1, + keyAlias, friendlyName, e.getMessage()); + throw new EaafKeyAccessException( + EaafKeyAccessException.ERROR_CODE_09, e, friendlyName, keyAlias, e.getMessage()); + + } else { + log.info(ERROR_MSG_1, + keyAlias, friendlyName, e.getMessage()); + log.info(ERROR_MSG_2, keyAlias); + + } + } + + return null; + + } + + private static void validateKeyResult(Pair<Key, X509Certificate[]> keyResult, + String friendlyName, String keyAlias) throws EaafKeyAccessException { + // some short validation + if (!(keyResult.getFirst() instanceof PrivateKey)) { + log.info("PrivateKey: {} in KeyStore: {} is of wrong type", keyAlias, friendlyName); + throw new EaafKeyAccessException( + EaafKeyAccessException.ERROR_CODE_09, + friendlyName, keyAlias, "Wrong PrivateKey type "); + + } + + if (keyResult.getSecond() == null || keyResult.getSecond().length == 0) { + log.info("NO certificate for Key: {} in KeyStore: {}", keyAlias, friendlyName); + throw new EaafKeyAccessException( + EaafKeyAccessException.ERROR_CODE_09, + friendlyName, keyAlias, "NO certificate for PrivateKey"); + + } + } +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/KeyStoreConfiguration.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/KeyStoreConfiguration.java new file mode 100644 index 00000000..6dbbba3e --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/credential/KeyStoreConfiguration.java @@ -0,0 +1,224 @@ +package at.gv.egiz.eaaf.core.impl.credential; + +import java.util.Map; + +import javax.annotation.Nonnull; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Getter +@Setter +public class KeyStoreConfiguration { + + public static final String PROP_CONFIG_KEYSTORE_TYPE = + "keystore.type"; + + public static final String PROP_CONFIG_HSMFACADE_NAME = + "keystore.name"; + + public static final String PROP_CONFIG_SOFTWARE_KEYSTORE_PATH = + "keystore.path"; + public static final String PROP_CONFIG_SOFTWARE_KEYSTORE_PASSORD = + "keystore.password"; + + /** + * FriendlyName for this KeyStore. Mainly used for logging. + */ + private String friendlyName; + + /** + * General type of the KeyStore that should be generated. + */ + private KeyStoreType keyStoreType; + + /** + * Name of the KeyStore in HSM Facade. + */ + private String keyStoreName; + + /** + * Path to software KeyStore in case of a PKCS12 or JKS KeyStore. + */ + private String softKeyStoreFilePath; + + /** + * Password of a software KeyStore in case of a PKCS12 or JKS KeyStore. + */ + private String softKeyStorePassword; + + /** + * Build a {@link KeyStoreConfiguration} from a configuration map. <br> + * <p> + * The configuration parameters defined in this class are used to load the + * configuration. + * </p> + * + * @param config Configuration + * @param friendlyName FriendlyName for this KeyStore + * @return Configuration object for {@link EaafKeyStoreFactory} + * @throws EaafConfigurationException In case of a configuration error. + */ + public static KeyStoreConfiguration buildFromConfigurationMap(Map<String, String> config, + String friendlyName) throws EaafConfigurationException { + + final KeyStoreConfiguration internalConfig = new KeyStoreConfiguration(); + internalConfig.setFriendlyName(friendlyName); + + final KeyStoreType internalKeyStoreType = KeyStoreType.fromString( + getConfigurationParameter(config, PROP_CONFIG_KEYSTORE_TYPE)); + if (internalKeyStoreType != null) { + internalConfig.setKeyStoreType(internalKeyStoreType); + + } else { + log.error("KeyStore: {} sets an unknown KeyStore type: {}", + friendlyName, getConfigurationParameter(config, PROP_CONFIG_KEYSTORE_TYPE)); + throw new EaafConfigurationException(EaafKeyStoreFactory.ERRORCODE_01, + new Object[] { friendlyName }); + + } + + if (internalKeyStoreType.equals(KeyStoreType.HSMFACADE)) { + log.trace("Set-up HSM-Facade KeyStore ... "); + internalConfig.setKeyStoreName( + getConfigurationParameter(config, PROP_CONFIG_HSMFACADE_NAME)); + + } else if (internalKeyStoreType.equals(KeyStoreType.PKCS12) + || internalKeyStoreType.equals(KeyStoreType.JKS)) { + log.trace("Set-up software KeyStore ... "); + internalConfig.setSoftKeyStoreFilePath( + getConfigurationParameter(config, PROP_CONFIG_SOFTWARE_KEYSTORE_PATH)); + internalConfig.setSoftKeyStorePassword( + getConfigurationParameter(config, PROP_CONFIG_SOFTWARE_KEYSTORE_PASSORD)); + + } else { + log.info("Configuration of type: {} not supported yet", internalKeyStoreType); + throw new EaafConfigurationException(EaafKeyStoreFactory.ERRORCODE_02, + new Object[] { friendlyName, config.get(PROP_CONFIG_KEYSTORE_TYPE) }); + + } + + return internalConfig; + } + + /** + * Set the Type of the KeyStore based on String identifier. + * + * @param keyStoreType String based KeyStore type + * @throws EaafConfigurationException In case of an unknown KeyStore type + */ + public void setKeyStoreType(@Nonnull String keyStoreType) throws EaafConfigurationException { + final KeyStoreType internalKeyStoreType = KeyStoreType.fromString(keyStoreType); + if (internalKeyStoreType != null) { + setKeyStoreType(internalKeyStoreType); + + } else { + log.error("KeyStore: {} sets an unknown KeyStore type: {}", + friendlyName, keyStoreType); + throw new EaafConfigurationException(EaafKeyStoreFactory.ERRORCODE_01, + new Object[] { friendlyName }); + + } + + } + + /** + * Set the Type of the KeyStore based on String identifier. + * + * @param type String based KeyStore type + */ + public void setKeyStoreType(@Nonnull KeyStoreType type) { + this.keyStoreType = type; + + } + + /** + * Validate the internal state of this configuration object. + * + * @throws EaafConfigurationException In case of a configuration error + */ + public void validate() throws EaafConfigurationException { + if (KeyStoreType.HSMFACADE.equals(keyStoreType)) { + log.trace("Validate HSM-Facade KeyStore ... "); + checkConfigurationValue(keyStoreName, EaafKeyStoreFactory.ERRORCODE_07, + friendlyName, "Missing 'KeyName' for HSM-Facade"); + + } else if (KeyStoreType.PKCS12.equals(keyStoreType) + || KeyStoreType.JKS.equals(keyStoreType)) { + log.trace("Validate software KeyStore ... "); + checkConfigurationValue(softKeyStoreFilePath, EaafKeyStoreFactory.ERRORCODE_07, + friendlyName, "Missing 'KeyPath' for software keystore"); + checkConfigurationValue(softKeyStorePassword, EaafKeyStoreFactory.ERRORCODE_07, + friendlyName, "Missing 'KeyPassword' for software keystore"); + + } else { + log.info("Validation of type: {} not supported yet", keyStoreType); + + } + } + + public enum KeyStoreType { + PKCS12("pkcs12"), JKS("jks"), HSMFACADE("hsmfacade"), PKCS11("pkcs11"); + + private final String keyStoreType; + + KeyStoreType(final String keyStoreType) { + this.keyStoreType = keyStoreType; + } + + /** + * Get Type of this KeyStore. + * + * @return + */ + public String getKeyStoreType() { + return this.keyStoreType; + } + + /** + * Get KeyStore type from String representation. + * + * @param s Config parameter + * @return + */ + public static KeyStoreType fromString(final String s) { + try { + return KeyStoreType.valueOf(s.toUpperCase()); + + } catch (IllegalArgumentException | NullPointerException e) { + return null; + } + } + + @Override + public String toString() { + return getKeyStoreType(); + + } + } + + @Nonnull + private static String getConfigurationParameter(@Nonnull Map<String, String> config, + @Nonnull String configParamKey) + throws EaafConfigurationException { + final String configValue = config.get(configParamKey); + checkConfigurationValue(configValue, EaafKeyStoreFactory.ERRORCODE_04, configParamKey); + return configValue; + + } + + private static void checkConfigurationValue(String configValue, String errorCode, String... params) + throws EaafConfigurationException { + if (StringUtils.isEmpty(configValue)) { + throw new EaafConfigurationException(errorCode, + new Object[] { params}); + + } + + } +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java index 8584d63f..67d87b0d 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java @@ -23,8 +23,9 @@ import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** - * Holder for a secure random instance following the initialization on demand holder design pattern. - * The secure random instance is a singleton that is initialized on first usage. + * Holder for a secure random instance following the initialization on demand + * holder design pattern. The secure random instance is a singleton that is + * initialized on first usage. * * @author tknall * diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSource.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSource.java new file mode 100644 index 00000000..5aa5b3b5 --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSource.java @@ -0,0 +1,16 @@ +package at.gv.egiz.eaaf.core.impl.logging; + +import java.util.Arrays; +import java.util.List; + +import at.gv.egiz.eaaf.core.api.logging.IMessageSourceLocation; + +public class EaafUtilsMessageSource implements IMessageSourceLocation { + + @Override + public List<String> getMessageSourceLocation() { + return Arrays.asList("classpath:messages/eaaf_utils_message"); + + } + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java index 5715a7b6..0d394d19 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java @@ -1,11 +1,12 @@ package at.gv.egiz.eaaf.core.impl.logging; import java.text.MessageFormat; + import at.gv.egiz.eaaf.core.api.IStatusMessenger; /** - * Simple {@link IStatusMessenger} implementation that formats messages by using. - * {@link MessageFormat} + * Simple {@link IStatusMessenger} implementation that formats messages by + * using. {@link MessageFormat} * * @author tlenz * diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java index 8090585f..ef1f3fdc 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java @@ -23,7 +23,8 @@ import org.apache.commons.lang3.StringUtils; import at.gv.egiz.eaaf.core.api.data.EaafConstants; /** - * Builds a DataURL parameter meant for the security layer implementation to respond to. + * Builds a DataURL parameter meant for the security layer implementation to + * respond to. * * @author Paul Ivancsics * @version $Id$ @@ -39,12 +40,13 @@ public class DataUrlBuilder { /** * Constructs a data URL for <code>VerifyIdentityLink</code> or - * <code>VerifyAuthenticationBlock</code>, including the <code>MOASessionID</code> as a parameter. + * <code>VerifyAuthenticationBlock</code>, including the + * <code>MOASessionID</code> as a parameter. * - * @param authBaseUrl base URL (context path) of the MOA ID Authentication component, including a - * trailing <code>'/'</code> + * @param authBaseUrl base URL (context path) of the MOA ID Authentication + * component, including a trailing <code>'/'</code> * @param authServletName request part of the data URL - * @param pendingReqId sessionID to be included in the dataURL + * @param pendingReqId sessionID to be included in the dataURL * @return String */ public String buildDataUrl(String authBaseUrl, String authServletName, @@ -70,10 +72,10 @@ public class DataUrlBuilder { /** * Method addParameter. - * + * * @param urlString represents the url * @param paramname is the parameter to be added - * @param value is the value of that parameter + * @param value is the value of that parameter * @return String */ private String addParameter(final String urlString, final String paramname, final String value) { diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java index 943d3dad..7cb551e2 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java @@ -17,8 +17,6 @@ * works that you distribute must include a readable copy of the "NOTICE" text file. */ - - package at.gv.egiz.eaaf.core.impl.utils; import java.io.BufferedInputStream; @@ -31,6 +29,7 @@ import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,7 +37,6 @@ import org.slf4j.LoggerFactory; public class FileUtils { private static final Logger log = LoggerFactory.getLogger(FileUtils.class); - /** * Reads a file, given by URL, into a byte array. * @@ -72,7 +70,7 @@ public class FileUtils { /** * Reads a file from a resource. * - * @param name filename + * @param name filename * @param encoding character encoding * @return file content * @throws IOException on any exception thrown @@ -82,11 +80,11 @@ public class FileUtils { return new String(content, encoding); } - /** - * Returns the absolute URL of a given url which is relative to the parameter root. + * Returns the absolute URL of a given url which is relative to the parameter + * root. * - * @param url Filepath + * @param url Filepath * @param root configuration root context * @return absolut filepath * @throws MalformedURLException In case of a filepath error @@ -102,9 +100,10 @@ public class FileUtils { } /** - * Returns the absolute URL of a given url which is relative to the parameter root. + * Returns the absolute URL of a given url which is relative to the parameter + * root. * - * @param url Filepath + * @param url Filepath * @param root configuration root context * @return absolut filepath */ @@ -145,7 +144,6 @@ public class FileUtils { } } - private static void copy(final InputStream fis, final OutputStream fos) { try { final byte[] buffer = new byte[0xFFFF]; @@ -161,7 +159,7 @@ public class FileUtils { /** * Copy file from source to destination. * - * @param src File source + * @param src File source * @param dest file destination */ public static void copyFile(final File src, final File dest) { diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java index c60fcd7f..ade0c28d 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java @@ -1,18 +1,15 @@ package at.gv.egiz.eaaf.core.impl.utils; -import java.io.IOException; -import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; + import javax.annotation.PostConstruct; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; + import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; @@ -38,18 +35,27 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContexts; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; +import lombok.extern.slf4j.Slf4j; + +@Slf4j public class HttpClientFactory implements IHttpClientFactory { - private static final Logger log = LoggerFactory.getLogger(HttpClientFactory.class); + @Autowired(required = true) private IConfiguration basicConfig; + @Autowired(required = true) ResourceLoader resourceLoader; + + @Autowired private EaafKeyStoreFactory keyStoreFactory; public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_USE = "client.http.connection.pool.use"; @@ -73,6 +79,8 @@ public class HttpClientFactory implements IHttpClientFactory { "client.auth.ssl.keystore.path"; public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD = "client.auth.ssl.keystore.password"; + private static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_NAME = + "client.auth.ssl.keystore.name"; public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE = "client.auth.ssl.keystore.type"; public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD = @@ -127,47 +135,6 @@ public class HttpClientFactory implements IHttpClientFactory { } - public enum KeyStoreType { - PKCS12("pkcs12"), JKS("jks"); - - private final String type; - - KeyStoreType(final String type) { - this.type = type; - } - - /** - * Get the KeyStore type. - * - * @return - */ - public String getType() { - return this.type; - } - - /** - * Get Keystore type from configuration. - * - * @param s String representation for keyStore type - * @return - */ - public static KeyStoreType fromString(final String s) { - try { - return KeyStoreType.valueOf(s.toUpperCase()); - - } catch (IllegalArgumentException | NullPointerException e) { - return null; - } - } - - @Override - public String toString() { - return getType(); - - } - - } - private HttpClientBuilder httpClientBuilder = null; /* @@ -246,7 +213,6 @@ public class HttpClientFactory implements IHttpClientFactory { // set pool connection if required injectConnectionPoolIfRequired(sslConnectionFactory); - } private void injectBasicAuthenticationIfRequired(final ClientAuthMode clientAuthMode) { @@ -286,54 +252,39 @@ public class HttpClientFactory implements IHttpClientFactory { final String keyPasswordString = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD); log.trace("Open SSL Client-Auth keystore with password: {}", keyPasswordString); - final char[] keyPassword = (keyPasswordString == null) ? StringUtils.EMPTY.toCharArray() + final char[] keyPassword = keyPasswordString == null ? StringUtils.EMPTY.toCharArray() : keyPasswordString.toCharArray(); return SSLContexts.custom().loadKeyMaterial(keystore, keyPassword).build(); } private KeyStore getSslAuthKeyStore() throws EaafConfigurationException { - final KeyStoreType keyStoreType = KeyStoreType.fromString(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE, KeyStoreType.PKCS12.getType())); + final String keyStoreType = basicConfig.getBasicConfiguration( + PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE, KeyStoreType.PKCS12.getKeyStoreType()); final String localKeyStorePath = basicConfig .getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PATH, StringUtils.EMPTY); final String keyStorePassword = basicConfig .getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD, StringUtils.EMPTY); + final String keyStoreName = basicConfig + .getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_NAME, StringUtils.EMPTY); try { + KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(keyStoreType); + keyStoreConfig.setFriendlyName("HttpClient Keystore"); + keyStoreConfig.setSoftKeyStoreFilePath(localKeyStorePath); + keyStoreConfig.setSoftKeyStorePassword(keyStorePassword); + keyStoreConfig.setKeyStoreName(keyStoreName); + log.debug("Open keyStore with type: {}", keyStoreType); - KeyStore clientStore; - if (keyStoreType.equals(KeyStoreType.PKCS12)) { - clientStore = KeyStore.getInstance("pkcs12"); - } else { - clientStore = KeyStore.getInstance("JKS"); - } - - - log.debug("Read keyStore path: {} from configuration", localKeyStorePath); - if (StringUtils.isNotEmpty(localKeyStorePath)) { - final String absFilePath = FileUtils.makeAbsoluteUrl(localKeyStorePath, - basicConfig.getConfigurationRootDirectory()); - final Resource ressource = resourceLoader.getResource(absFilePath); - final InputStream is = ressource.getInputStream(); - log.trace("Load keyStore: {} with password: {}", absFilePath, keyStorePassword); - clientStore.load(is, keyStorePassword.toCharArray()); - is.close(); - - return clientStore; - - } else { - log.warn("Path to keyStore for SSL Client-Authentication is empty or null"); - throw new EaafConfigurationException( - "Path to keyStore for SSL Client-Authentication is empty or null", new Object[] {}); - - } - - } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException - | IOException e) { + KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + + return keyStore; + + } catch (final EaafException e) { log.warn("Can NOT read keyStore: {} from filesystem", localKeyStorePath, null, e); throw new EaafConfigurationException("Can NOT read keyStore: {} from filesystem", - new Object[] {localKeyStorePath}, e); + new Object[] { localKeyStorePath }, e); } @@ -413,9 +364,6 @@ public class HttpClientFactory implements IHttpClientFactory { } - } - - } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java index 1f7601d8..66356ba0 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java @@ -19,18 +19,17 @@ package at.gv.egiz.eaaf.core.impl.utils; import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; - +import org.apache.commons.lang3.StringUtils; public class HttpUtils { - /** * Helper method to retrieve server URL including context path. * * @param request HttpServletRequest - * @return Server URL including context path (e.g. http://localhost:8443/moa-id-auth + * @return Server URL including context path (e.g. + * http://localhost:8443/moa-id-auth */ public static String getBaseUrl(final HttpServletRequest request) { final StringBuffer buffer = new StringBuffer(getServerUrl(request)); @@ -101,8 +100,8 @@ public class HttpUtils { /** * Add a http GET parameter to URL. * - * @param url URL - * @param paramname Name of the parameter. + * @param url URL + * @param paramname Name of the parameter. * @param paramvalue Value of the parameter. * @return */ diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java index 0dc00573..f922e1ac 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java @@ -5,7 +5,8 @@ import org.apache.http.impl.client.CloseableHttpClient; public interface IHttpClientFactory { /** - * Return an instance of a Apache HTTP client that follows http redirects automatically. + * Return an instance of a Apache HTTP client that follows http redirects + * automatically. * * @return */ @@ -14,7 +15,8 @@ public interface IHttpClientFactory { /** * Return an instance of a Apache HTTP client. * - * @param followRedirects if <code>false</code>, the client does not flow 30x http redirects + * @param followRedirects if <code>false</code>, the client does not flow 30x + * http redirects * @return */ CloseableHttpClient getHttpClient(boolean followRedirects); diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java index 18ddf422..99b87819 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java @@ -17,8 +17,6 @@ * works that you distribute must include a readable copy of the "NOTICE" text file. */ - - package at.gv.egiz.eaaf.core.impl.utils; import java.io.BufferedInputStream; @@ -50,16 +48,14 @@ public class KeyStoreUtils { */ private static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; - - /** * Loads a key store from file. * * @param keystoreType key store type - * @param urlString URL of key store - * @param password password protecting the key store + * @param urlString URL of key store + * @param password password protecting the key store * @return key store loaded - * @throws IOException thrown while reading the key store from file + * @throws IOException thrown while reading the key store from file * @throws GeneralSecurityException thrown while creating the key store */ public static KeyStore loadKeyStore(final String keystoreType, final String urlString, @@ -74,10 +70,10 @@ public class KeyStoreUtils { * Load a KeyStore from Filesystem. * * @param keyStorePath Path to KeyStore - * @param password KeyStore password + * @param password KeyStore password * @return KeyStore * @throws KeyStoreException In case of a keystore error - * @throws IOException In case of a general read error + * @throws IOException In case of a general read error */ public static KeyStore loadKeyStore(final String keyStorePath, final String password) throws KeyStoreException, IOException { @@ -89,13 +85,15 @@ public class KeyStoreUtils { } /** - * Loads a key store from an <code>InputStream</code>, and closes the <code>InputStream</code>. + * Loads a key store from an <code>InputStream</code>, and closes the + * <code>InputStream</code>. * * @param keystoreType key store type - * @param in input stream - * @param password password protecting the key store + * @param in input stream + * @param password password protecting the key store * @return key store loaded - * @throws IOException thrown while reading the key store from the stream + * @throws IOException thrown while reading the key store from the + * stream * @throws GeneralSecurityException thrown while creating the key store */ public static KeyStore loadKeyStore(final String keystoreType, final InputStream in, @@ -114,11 +112,11 @@ public class KeyStoreUtils { /** * Loads a keyStore without knowing the keyStore type. * - * @param is input stream + * @param is input stream * @param password Password protecting the keyStore * @return keyStore loaded * @throws KeyStoreException thrown if keyStore cannot be loaded - * @throws IOException In case of a general error + * @throws IOException In case of a general error */ public static KeyStore loadKeyStore(final InputStream is, final String password) throws KeyStoreException, IOException { @@ -140,10 +138,10 @@ public class KeyStoreUtils { } /** - * Creates a key store from X509 certificate files, aliasing them with the index in the - * <code>String[]</code>, starting with <code>"0"</code>. + * Creates a key store from X509 certificate files, aliasing them with the index + * in the <code>String[]</code>, starting with <code>"0"</code>. * - * @param keyStoreType key store type + * @param keyStoreType key store type * @param certFilenames certificate filenames * @return key store created * @throws Exception In case of an error @@ -192,6 +190,4 @@ public class KeyStoreUtils { } } - - } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java index 929d2994..0c5eeb40 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java @@ -28,8 +28,10 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; + import javax.annotation.Nonnull; import javax.annotation.Nullable; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,8 +51,7 @@ public class KeyValueUtils { public static final String DEFAULT_VALUE = "default"; /** - * Convert Java properties into a Map String/String. - * <br> + * Convert Java properties into a Map String/String. <br> * <b>Important:</b> The key/values from properties must be of type String! * * @param properties Java {@link Properties} that should be converted @@ -72,7 +73,7 @@ public class KeyValueUtils { /** * Extract the first child of an input key after a the prefix. * - * @param key Full input key + * @param key Full input key * @param prefix Prefix * @return Child key {String} if it exists or null */ @@ -82,11 +83,11 @@ public class KeyValueUtils { final int index = idAfterPrefix.indexOf(KEY_DELIMITER); if (index > 0) { final String adding = idAfterPrefix.substring(0, index); - if (!(adding.isEmpty())) { + if (!adding.isEmpty()) { return adding; } - } else if (!(idAfterPrefix.isEmpty())) { + } else if (!idAfterPrefix.isEmpty()) { return idAfterPrefix; } @@ -98,9 +99,10 @@ public class KeyValueUtils { /** * Extract the prefix from an input key. * - * @param key Full input key + * @param key Full input key * @param suffix Suffix of this key - * @return Prefix {String} of the key or null if input key does not ends with postfix string + * @return Prefix {String} of the key or null if input key does not ends with + * postfix string */ public static String getPrefixFromKey(final String key, final String suffix) { if (key != null && suffix != null && key.endsWith(suffix)) { @@ -118,9 +120,10 @@ public class KeyValueUtils { /** * Remove a prefix string from a key. * - * @param key Full input key + * @param key Full input key * @param prefix Prefix, which should be removed - * @return The suffix of the input key or null if the input does not starts with the prefix + * @return The suffix of the input key or null if the input does not starts with + * the prefix */ public static String removePrefixFromKey(final String key, String prefix) { if (prefix == null) { @@ -145,9 +148,10 @@ public class KeyValueUtils { /** * Remove a prefix string from all keys in Map String/String of key/value pairs. * - * @param keys Input data of key/value pairs + * @param keys Input data of key/value pairs * @param prefix Prefix which should be removed - * @return Map String/String of key/value pairs without prefix in key, but never null + * @return Map String/String of key/value pairs without prefix in key, but never + * null */ public static Map<String, String> removePrefixFromKeys(final Map<String, String> keys, final String prefix) { @@ -165,26 +169,29 @@ public class KeyValueUtils { } /** - * Get a subset of key/value pairs which starts with a prefix string The Prefix is removed from - * the key. + * Get a subset of key/value pairs which starts with a prefix string The Prefix + * is removed from the key. * - * @param keys Input data of key/value pairs + * @param keys Input data of key/value pairs * @param prefix Prefix string - * @return Map String/String of key/value pairs without prefix in key, but never null + * @return Map String/String of key/value pairs without prefix in key, but never + * null */ public static Map<String, String> getSubSetWithPrefix(final Map<String, String> keys, final String prefix) { return removePrefixFromKeys(keys, prefix); } - /** - * Add a prefix to key/value pairs to make the key absolute according to key namespace convention. + * Add a prefix to key/value pairs to make the key absolute according to key + * namespace convention. * - * @param input Input key/value pairs which should be updated - * @param prefix Key prefix, which should be added if the key is not absolute + * @param input Input key/value pairs which should be updated + * @param prefix Key prefix, which should be added if the key is not + * absolute * @param absolutIdentifier Key identifier, which indicates an absolute key - * @return Map String/String of key/value pairs in which all keys are absolute but never null + * @return Map String/String of key/value pairs in which all keys are absolute + * but never null */ public static Map<String, String> makeKeysAbsolut(final Map<String, String> input, final String prefix, final String absolutIdentifier) { @@ -225,7 +232,7 @@ public class KeyValueUtils { /** * Find the highest free list counter. * - * @param input Array of list keys + * @param input Array of list keys * @param listPrefix {String} prefix of the list * @return {int} highest free list counter */ @@ -247,7 +254,7 @@ public class KeyValueUtils { /** * Find the highest free list counter. * - * @param keySet Set of list keys + * @param keySet Set of list keys * @param listPrefix {String} prefix of the list * @return {int} highest free list counter */ @@ -261,13 +268,12 @@ public class KeyValueUtils { return findNextFreeListCounter(array, listPrefix); } - /** * Normalize a CSV encoded list of value of an key/value pair. * * <p> - * This method removes all whitespace at the begin or the end of CSV values and remove newLine - * signs at the end of value. The ',' is used as list delimiter + * This method removes all whitespace at the begin or the end of CSV values and + * remove newLine signs at the end of value. The ',' is used as list delimiter * </p> * * @param value CSV encoded input data @@ -289,7 +295,6 @@ public class KeyValueUtils { return normalizedCodes; } - /** * Check a String if it is a comma separated list of values. * @@ -298,7 +303,8 @@ public class KeyValueUtils { * </p> * * @param value CSV encoded input data - * @return true if the input data contains a ',' and has more then 1 list element, otherwise false + * @return true if the input data contains a ',' and has more then 1 list + * element, otherwise false */ public static boolean isCsvValueString(final String value) { if (StringUtils.isNotEmpty(value)) { @@ -316,8 +322,8 @@ public class KeyValueUtils { /** * Convert a CSV list to a List of CSV values. <br> * <br> - * This method removes all whitespace at the begin or the end of CSV values and remove newLine - * signs at the end of value. The ',' is used as list delimiter + * This method removes all whitespace at the begin or the end of CSV values and + * remove newLine signs at the end of value. The ',' is used as list delimiter * * @param csv CSV encoded input data * @return List of CSV normalized values, but never null @@ -338,8 +344,8 @@ public class KeyValueUtils { /** * Convert a List of String elements to a Map of Key/Value pairs. <br> - * Every List element used as a key/value pair and the '=' sign represents the delimiter between - * key and value + * Every List element used as a key/value pair and the '=' sign represents the + * delimiter between key and value * * @param elements List of key/value elements * @return Map of Key / Value pairs, but never null diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java index 755c4431..5d2a11d0 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java @@ -17,18 +17,18 @@ * works that you distribute must include a readable copy of the "NOTICE" text file. */ - - package at.gv.egiz.eaaf.core.impl.utils; import java.util.ListIterator; + import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.NodeIterator; /** - * A <code>NodeIterator</code> implementation based on a <code>ListIterator</code>. + * A <code>NodeIterator</code> implementation based on a + * <code>ListIterator</code>. * * @see java.util.ListIterator * @see org.w3c.dom.traversal.NodeIterator @@ -48,31 +48,26 @@ public class NodeIteratorAdapter implements NodeIterator { this.nodeIterator = nodeIterator; } - @Override public Node getRoot() { return null; } - @Override public int getWhatToShow() { return NodeFilter.SHOW_ALL; } - @Override public NodeFilter getFilter() { return null; } - @Override public boolean getExpandEntityReferences() { return false; } - @Override public Node nextNode() throws DOMException { if (nodeIterator.hasNext()) { @@ -81,7 +76,6 @@ public class NodeIteratorAdapter implements NodeIterator { return null; } - @Override public Node previousNode() throws DOMException { if (nodeIterator.hasPrevious()) { @@ -90,7 +84,6 @@ public class NodeIteratorAdapter implements NodeIterator { return null; } - @Override public void detach() { diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java index a942f75e..83a6725c 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java @@ -17,11 +17,10 @@ * works that you distribute must include a readable copy of the "NOTICE" text file. */ - - package at.gv.egiz.eaaf.core.impl.utils; import java.util.List; + import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -45,13 +44,11 @@ public class NodeListAdapter implements NodeList { this.nodeList = nodeList; } - @Override public Node item(final int index) { return (Node) nodeList.get(index); } - @Override public int getLength() { return nodeList.size(); diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java index 14d54b0b..aedbbb7f 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java @@ -19,7 +19,6 @@ package at.gv.egiz.eaaf.core.impl.utils; - import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; @@ -27,12 +26,13 @@ import java.security.SecureRandom; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; + import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; /** * Random number generator used to generate ID's. @@ -44,9 +44,9 @@ public class Random { private static final Logger log = LoggerFactory.getLogger(Random.class); private static final char[] allowedPreFix = - {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', - 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /** random number generator used. */ private static SecureRandom random; @@ -63,14 +63,14 @@ public class Random { } - // random = iaik.security.random.SHA256FIPS186Random.getDefault(); } /** - * Generate a unique process reference-value [160bit], which always starts with a letter <br> - * This unique ID consists of single letter, a 64bit date String[yyyyddMM], and a 88bit random - * value. + * Generate a unique process reference-value [160bit], which always starts with + * a letter <br> + * This unique ID consists of single letter, a 64bit date String[yyyyddMM], and + * a 88bit random value. * * @return 160bit ID, which is hex encoded */ @@ -98,12 +98,8 @@ public class Random { } - - } - - /** * Creates a new random number [256bit], and encode it as hex value. * diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java index ee88c4bb..bc770a8c 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java @@ -8,17 +8,13 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.Base64; + import javax.annotation.PostConstruct; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; -import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EaafException; -import at.gv.egiz.eaaf.core.exceptions.EaafIllegalStateException; -import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; + import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DurationFieldType; @@ -30,9 +26,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafIllegalStateException; +import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; + /** - * PendingRequestId generation strategy based on signed tokens that facilitates extended token - * validation. + * PendingRequestId generation strategy based on signed tokens that facilitates + * extended token validation. * * @author tlenz * @@ -78,7 +81,7 @@ public class SecurePendingRequestIdGenerationStrategy .encodeToString(externalPendingRequestId.toString().getBytes("UTF-8")); } catch (final UnsupportedEncodingException e) { - throw new EaafException("internal.99", new Object[] {e.getMessage()}, e); + throw new EaafException("internal.99", new Object[] { e.getMessage() }, e); } @@ -131,7 +134,6 @@ public class SecurePendingRequestIdGenerationStrategy return internalPendingReqId; - } catch (final IllegalArgumentException | EaafIllegalStateException e) { log.warn("Token is NOT a valid String. Msg: {}", e.getMessage()); log.debug("TokenValue: {}", externalPendingReqId); @@ -177,7 +179,6 @@ public class SecurePendingRequestIdGenerationStrategy } - @PostConstruct private void initialize() throws EaafConfigurationException { log.debug("Initializing " + this.getClass().getName() + " ... "); @@ -186,7 +187,7 @@ public class SecurePendingRequestIdGenerationStrategy baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET); if (StringUtils.isEmpty(pendingReqIdDigistSecret)) { throw new EaafConfigurationException("config.08", - new Object[] {CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET}); + new Object[] { CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET }); } digistAlgorithm = baseConfig.getBasicConfiguration( @@ -201,11 +202,10 @@ public class SecurePendingRequestIdGenerationStrategy final KeySpec spec = new PBEKeySpec(pendingReqIdDigistSecret.toCharArray(), salt, 10000, 128); key = keyFactory.generateSecret(spec); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { log.error("Can NOT initialize TokenService with configuration object", e); throw new EaafConfigurationException("config.09", - new Object[] {CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET, "Can NOT generate HMAC key"}, + new Object[] { CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET, "Can NOT generate HMAC key" }, e); } @@ -229,7 +229,7 @@ public class SecurePendingRequestIdGenerationStrategy } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) { log.error("Can NOT generate secure pendingRequestId", e); throw new EaafIllegalStateException( - new Object[] {"Can NOT caluclate digist for secure pendingRequestId"}, e); + new Object[] { "Can NOT caluclate digist for secure pendingRequestId" }, e); } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java index 049f7175..78f0cdec 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java @@ -1,11 +1,13 @@ package at.gv.egiz.eaaf.core.impl.utils; +import org.apache.commons.lang3.StringUtils; + import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; -import org.apache.commons.lang3.StringUtils; /** - * Simple pendingRequestId generation strategy that facilitates no extended validation. + * Simple pendingRequestId generation strategy that facilitates no extended + * validation. * * @author tlenz * @@ -34,8 +36,6 @@ public class SimplePendingRequestIdGenerationStrategy "PendingRequestId is empty or null"); } - - return externalPendingReqId; } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java index 795b71f7..22a6de2b 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java @@ -17,8 +17,6 @@ * works that you distribute must include a readable copy of the "NOTICE" text file. */ - - package at.gv.egiz.eaaf.core.impl.utils; import java.io.ByteArrayOutputStream; @@ -39,8 +37,8 @@ public class StreamUtils { * * @param is1 The 1st <code>InputStream</code> to compare. * @param is2 The 2nd <code>InputStream</code> to compare. - * @return boolean <code>true</code>, if both streams contain the exactly the same content, - * <code>false</code> otherwise. + * @return boolean <code>true</code>, if both streams contain the exactly the + * same content, <code>false</code> otherwise. * @throws IOException An error occurred reading one of the streams. */ public static boolean compareStreams(final InputStream is1, final InputStream is2) @@ -83,10 +81,11 @@ public class StreamUtils { /** * Compare two byte arrays, up to a given maximum length. * - * @param b1 1st byte array to compare. - * @param b2 2nd byte array to compare. + * @param b1 1st byte array to compare. + * @param b2 2nd byte array to compare. * @param length The maximum number of bytes to compare. - * @return <code>true</code>, if the byte arrays are equal, <code>false</code> otherwise. + * @return <code>true</code>, if the byte arrays are equal, <code>false</code> + * otherwise. */ private static boolean compareBytes(final byte[] b1, final byte[] b2, final int length) { if (b1.length != b2.length) { @@ -115,8 +114,8 @@ public class StreamUtils { copyStream(in, out, null); /* - * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) >= 0) - * out.write(b); + * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = + * in.read()) >= 0) out.write(b); * */ in.close(); @@ -126,10 +125,11 @@ public class StreamUtils { /** * Reads a <code>String</code> from a stream, using given encoding. * - * @param in The <code>InputStream</code> to read. + * @param in The <code>InputStream</code> to read. * @param encoding The character encoding to use for converting the bytes of the - * <code>InputStream</code> into a <code>String</code>. - * @return The content of the given <code>InputStream</code> converted into a <code>String</code>. + * <code>InputStream</code> into a <code>String</code>. + * @return The content of the given <code>InputStream</code> converted into a + * <code>String</code>. * @throws IOException on any exception thrown */ public static String readStream(final InputStream in, final String encoding) throws IOException { @@ -137,23 +137,26 @@ public class StreamUtils { copyStream(in, out, null); /* - * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) >= 0) - * out.write(b); + * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = + * in.read()) >= 0) out.write(b); */ in.close(); return out.toString(encoding); } /** - * Reads all data (until EOF is reached) from the given source to the destination stream. If the - * destination stream is null, all data is dropped. It uses the given buffer to read data and - * forward it. If the buffer is null, this method allocates a buffer. + * Reads all data (until EOF is reached) from the given source to the + * destination stream. If the destination stream is null, all data is dropped. + * It uses the given buffer to read data and forward it. If the buffer is null, + * this method allocates a buffer. * - * @param source The stream providing the data. - * @param destination The stream that takes the data. If this is null, all data from source will - * be read and discarded. - * @param buffer The buffer to use for forwarding. If it is null, the method allocates a buffer. - * @exception IOException If reading from the source or writing to the destination fails. + * @param source The stream providing the data. + * @param destination The stream that takes the data. If this is null, all data + * from source will be read and discarded. + * @param buffer The buffer to use for forwarding. If it is null, the + * method allocates a buffer. + * @exception IOException If reading from the source or writing to the + * destination fails. */ private static void copyStream(final InputStream source, final OutputStream destination, byte[] buffer) throws IOException { @@ -169,14 +172,15 @@ public class StreamUtils { while ((bytesRead = source.read(buffer)) >= 0) { destination.write(buffer, 0, bytesRead); } - } + } } // /** // * Gets the stack trace of the <code>Throwable</code> passed in as a string. // * // * @param t The <code>Throwable</code>. - // * @return a String representing the stack trace of the <code>Throwable</code>. + // * @return a String representing the stack trace of the + // <code>Throwable</code>. // */ // public static String getStackTraceAsString(final Throwable t) { // final ByteArrayOutputStream stackTraceBis = new ByteArrayOutputStream(); diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java index 3875e587..d8976548 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java @@ -19,7 +19,6 @@ package at.gv.egiz.eaaf.core.impl.utils; - import at.gv.egiz.eaaf.core.api.IRequest; /** @@ -37,7 +36,8 @@ public class TransactionIdUtils { /** * Set all MDC variables from pending request to this threat context.<br> - * These includes SessionID, TransactionID, and unique service-provider identifier + * These includes SessionID, TransactionID, and unique service-provider + * identifier * * @param pendingRequest Http request object */ @@ -59,7 +59,6 @@ public class TransactionIdUtils { } - public static void setServiceProviderId(final String oaUniqueId) { org.slf4j.MDC.put(MDC_SERVICEPROVIDER_ID, oaUniqueId); @@ -90,5 +89,4 @@ public class TransactionIdUtils { } - } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java index 00a31a13..72c183bf 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java @@ -8,9 +8,9 @@ import javax.security.auth.x500.X500Principal; public class X509Utils { /** - * Sorts the Certificate Chain by IssuerDN and SubjectDN. The [0]-Element should be the Hostname, - * the last Element should be the Root Certificate. - * + * Sorts the Certificate Chain by IssuerDN and SubjectDN. The [0]-Element should + * be the Hostname, the last Element should be the Root Certificate. + * * @param certs The first element must be the correct one. * @return sorted Certificate Chain */ diff --git a/eaaf_core_utils/src/main/resources/messages/eaaf_utils_message.properties b/eaaf_core_utils/src/main/resources/messages/eaaf_utils_message.properties new file mode 100644 index 00000000..2d9a863a --- /dev/null +++ b/eaaf_core_utils/src/main/resources/messages/eaaf_utils_message.properties @@ -0,0 +1,12 @@ +internal.keystore.00=HSM-Facade NOT INITIALIZED. KeyStore:{0} initialization failed +internal.keystore.01=KeyStore:{0} configuration has an unsupported type in configuration. +internal.keystore.02=Type:{1} of KeyStore:{0} is NOT SUPPORTED yet. +internal.keystore.03=HSM-Facade initialization failed with a generic error: {0} +internal.keystore.04=HSM-Facade has a wrong configuration. Missing property: {0} +internal.keystore.05=HSM-Facade has a wrong configuration. Property: {0} Reason:{1} +internal.keystore.06=KeyStore: {0} initialization failed. Reason: {1} +internal.keystore.07=Validation of KeyStore: {0} failed. Reason: {1} +internal.keystore.08=Can not access Key: {1} in KeyStore: {0} +internal.keystore.09=Can not access Key: {1} in KeyStore: {0} Reason: {2} + + diff --git a/eaaf_core_utils/src/main/resources/spring/eaaf_utils.beans.xml b/eaaf_core_utils/src/main/resources/spring/eaaf_utils.beans.xml new file mode 100644 index 00000000..7568f423 --- /dev/null +++ b/eaaf_core_utils/src/main/resources/spring/eaaf_utils.beans.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" > + + <bean id="eaafKeyStoreFactory" + class="at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory" /> + + <bean id="eaafUtilsMessageSource" + class="at.gv.egiz.eaaf.core.impl.logging.EaafUtilsMessageSource" /> + + +</beans>
\ No newline at end of file diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSourceTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSourceTest.java new file mode 100644 index 00000000..f6df60ae --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/EaafUtilsMessageSourceTest.java @@ -0,0 +1,36 @@ +package at.gv.egiz.eaaf.core.impl.logging; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.gv.egiz.eaaf.core.api.logging.IMessageSourceLocation; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/spring/test_eaaf_pvp_not_lazy.beans.xml") +public class EaafUtilsMessageSourceTest { + + @Autowired + private ResourceLoader loader; + @Autowired(required = false) + private IMessageSourceLocation messageSource; + + @Test + public void simpleTests() { + Assert.assertNotNull("No messageSource", messageSource); + + Assert.assertNotNull("No sourcePath", messageSource.getMessageSourceLocation()); + + for (final String el : messageSource.getMessageSourceLocation()) { + final Resource messages = loader.getResource(el + ".properties"); + Assert.assertTrue("Source not exist", messages.exists()); + + } + + } +} diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java index be5d95b1..9c1d0c82 100644 --- a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java @@ -3,6 +3,7 @@ package at.gv.egiz.eaaf.core.impl.logging; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; + import at.gv.egiz.eaaf.core.api.IStatusMessenger; public class JUnitTestStatusMessenger implements IStatusMessenger { @@ -48,7 +49,7 @@ public class JUnitTestStatusMessenger implements IStatusMessenger { * Add a message into Message-Store. * * @param msgCode message-code - * @param msg message + * @param msg message */ public void addMsg(final String msgCode, final String msg) { if (!msgStore.containsKey(msgCode)) { diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java index 258c3210..58788392 100644 --- a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java @@ -6,14 +6,17 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; + import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; + import com.google.common.collect.Sets; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; + @RunWith(BlockJUnit4ClassRunner.class) public class KeyValueUtilsTest { @@ -442,5 +445,4 @@ public class KeyValueUtilsTest { } - } diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/EaafKeyStoreFactoryTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/EaafKeyStoreFactoryTest.java new file mode 100644 index 00000000..c47805e8 --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/EaafKeyStoreFactoryTest.java @@ -0,0 +1,636 @@ +package at.gv.egiz.eaaf.core.test.credentials; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.X509Certificate; +import java.util.List; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.MethodMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.common.base.Optional; +import com.google.common.base.Predicates; +import com.google.common.base.Throwables; +import com.google.common.collect.FluentIterable; + +import at.gv.egiz.eaaf.core.exception.EaafKeyAccessException; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafFactoryException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.test.dummy.DummyAuthConfigMap; +import io.grpc.StatusRuntimeException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/spring/test_eaaf_pvp_lazy.beans.xml") +@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) +public class EaafKeyStoreFactoryTest { + + private static final String PATH_TO_SOFTWARE_KEYSTORE_JKS_WITH_TRUSTED_CERTS = + "src/test/resources/data/junit.jks"; + private static final String PATH_TO_SOFTWARE_KEYSTORE_JKS = + "src/test/resources/data/junit_without_trustcerts.jks"; + private static final String PATH_TO_SOFTWARE_KEYSTORE_PKCS12 = + "src/test/resources/data/junit_without_trustcerts.p12"; + private static final String PATH_TO_HSM_FACADE_TRUST_CERT = "src/test/resources/data/test.crt"; + private static final String SOFTWARE_KEYSTORE_PASSWORD = "password"; + + @Autowired + private DummyAuthConfigMap mapConfig; + @Autowired + private ApplicationContext context; + + /** + * jUnit test set-up. + */ + @Before + public void testSetup() { + mapConfig.clearAllConfig(); + + } + + @Test + @DirtiesContext + public void startWithoutConfigHsmFacadeConfig() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + } + + @Test + @DirtiesContext + public void buildyStoreWithOutConfig() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.01", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void buildyStoreWithPkcs11() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.PKCS11); + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.02", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithoutConfig() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithoutConfigSecond() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.PKCS12); + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithoutPassword() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_JKS); + + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithoutPath() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithoutType() throws EaafException { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_JKS); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + final KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.assertNotNull("KeyStore is null", keyStore); + + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithWrongPath() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath("src/test/resources/notexist.jks"); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.05", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreWithWrongPassword() { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_JKS); + keyStoreConfig.setSoftKeyStorePassword("wrong password"); + + + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafFactoryException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + + } + } + + @Test + @DirtiesContext + public void softwareKeyStoreSuccessJks() throws EaafException { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_JKS); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + keyStoreConfig.validate(); + + final KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.assertNotNull("KeyStore is null", keyStore); + + } + + @Test + @DirtiesContext + public void softwareKeyStoreAccessOperations() throws EaafException, KeyStoreException { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_JKS_WITH_TRUSTED_CERTS); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + keyStoreConfig.validate(); + + final KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.assertNotNull("KeyStore is null", keyStore); + + //read trusted certs + List<X509Certificate> trustedCerts = EaafKeyStoreUtils.readCertsFromKeyStore(keyStore); + Assert.assertNotNull("Trusted certs", trustedCerts); + Assert.assertEquals("Trusted certs size", 2, trustedCerts.size()); + + //read priv. key + Pair<Key, X509Certificate[]> privCred1 = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "meta", "password".toCharArray(), true, "jUnit test"); + Assert.assertNotNull("Credential 1", privCred1); + Assert.assertNotNull("Credential 1 priv. key", privCred1.getFirst()); + Assert.assertNotNull("Credential 1 certificate", privCred1.getSecond()); + + //read priv. key + Pair<Key, X509Certificate[]> privCred2 = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "sig", "password".toCharArray(), true, "jUnit test"); + Assert.assertNotNull("Credential 2", privCred2); + Assert.assertNotNull("Credential 2 priv. key", privCred2.getFirst()); + Assert.assertNotNull("Credential 2 certificate", privCred2.getSecond()); + + + //read priv. key + Pair<Key, X509Certificate[]> privCred3 = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "notexist", "password".toCharArray(), false, "jUnit test"); + Assert.assertNull("Credential 3", privCred3); + + //read priv. key + Pair<Key, X509Certificate[]> privCred4 = EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "meta", "wrong".toCharArray(), false, "jUnit test"); + Assert.assertNull("Credential 3", privCred4); + + try { + EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "meta", "wrong".toCharArray(), true, "jUnit test"); + Assert.fail("Wrong password not detected"); + + } catch (EaafKeyAccessException e) { + Assert.assertEquals("wrong errorcode", "internal.keystore.09", e.getErrorId()); + } + + try { + EaafKeyStoreUtils.getPrivateKeyAndCertificates( + keyStore, "wrong", "password".toCharArray(), true, "jUnit test"); + Assert.fail("Wrong alias not detected"); + + } catch (EaafKeyAccessException e) { + Assert.assertEquals("wrong errorcode", "internal.keystore.09", e.getErrorId()); + } + + + } + + @Test + @DirtiesContext + public void softwareKeyStoreSuccessPkcs12() throws EaafException { + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertFalse("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.PKCS12); + keyStoreConfig.setSoftKeyStoreFilePath(PATH_TO_SOFTWARE_KEYSTORE_PKCS12); + keyStoreConfig.setSoftKeyStorePassword(SOFTWARE_KEYSTORE_PASSWORD); + + keyStoreConfig.validate(); + + final KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.assertNotNull("KeyStore is null", keyStore); + + } + + @Test + public void hsmFacadeOnlyHostConfig() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingPort() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingUsername() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingPassword() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingKeyStoreName() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingTrustedCertificate() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e); + + } + } + + @Test + public void hsmFacadeMissingTrustedCertificateFile() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, + "src/test/resources/data/notexist.crt"); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e, "internal.keystore.05"); + + } + } + + @Test + public void hsmFacadeMissingWrongTrustedCertificate() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, + "src/test/resources/spring/test_eaaf_pvp_lazy.beans.xml"); + + try { + context.getBean(EaafKeyStoreFactory.class); + Assert.fail("Missing HSM Facade not detected"); + + } catch (final BeansException e) { + checkMissingConfigException(e, "internal.keystore.05"); + + } + } + + @Test + @DirtiesContext + public void hsmFacadeInitialized() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, + PATH_TO_HSM_FACADE_TRUST_CERT); + + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertTrue("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + } + + @Test + @DirtiesContext + public void hsmFacadeKeyStoreNoKeyStoreName() { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, + PATH_TO_HSM_FACADE_TRUST_CERT); + + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertTrue("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.HSMFACADE); + + try { + keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.fail("Wrong config not detected"); + + } catch (final EaafException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e, "Wong ExceptionType"); + Assert.assertEquals("wrong errorCode", "internal.keystore.06", e.getErrorId()); + } + + } + + @Test + @DirtiesContext + public void hsmFacadeKeyStoreSuccess() throws EaafException { + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HOST, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_PORT, + RandomStringUtils.randomNumeric(4)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_USERNAME, + RandomStringUtils.randomNumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_CLIENT_PASSWORD, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_HSM_NAME, + RandomStringUtils.randomAlphanumeric(10)); + mapConfig.putConfigValue(EaafKeyStoreFactory.CONFIG_PROP_HSM_FACADE_SSLTRUST, + PATH_TO_HSM_FACADE_TRUST_CERT); + + final EaafKeyStoreFactory keyStoreFactory = context.getBean(EaafKeyStoreFactory.class); + Assert.assertTrue("HSM Facade state wrong", keyStoreFactory.isHsmFacadeInitialized()); + + final KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.HSMFACADE); + keyStoreConfig.setKeyStoreName("testkeyStore"); + + keyStoreConfig.validate(); + + try { + final KeyStore keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + Assert.assertNotNull("KeyStore is null", keyStore); + + } catch (final StatusRuntimeException e) { + // because there is no mockup of HSM facade available + // Assert.assertTrue("Wrong exception", e.getMessage().contains("io + // exception")); + + } + + } + + private void checkMissingConfigException(Exception e) { + checkMissingConfigException(e, "internal.keystore.04"); + + } + + private void checkMissingConfigException(Exception e, String errorCode) { + final Optional<Throwable> eaafException = FluentIterable.from( + Throwables.getCausalChain(e)).filter( + Predicates.instanceOf(EaafConfigurationException.class)).first(); + Assert.assertTrue("Wrong exception", eaafException.isPresent()); + Assert.assertEquals("Wrong errorCode", + errorCode, ((EaafException) eaafException.get()).getErrorId()); + + } + +} diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/KeyStoreConfigurationTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/KeyStoreConfigurationTest.java new file mode 100644 index 00000000..8cb81107 --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/credentials/KeyStoreConfigurationTest.java @@ -0,0 +1,190 @@ +package at.gv.egiz.eaaf.core.test.credentials; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; + +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; + +@RunWith(BlockJUnit4ClassRunner.class) +public class KeyStoreConfigurationTest { + + private Map<String, String> config; + + @Before + public void testSetup() { + config = new HashMap<>(); + + } + + @Test + public void emptyConfigMap() { + try { + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.04", e.getErrorId()); + } + } + + @Test + public void emptyKeyStoreType() { + try { + config.put("keystore.type", ""); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.04", e.getErrorId()); + } + } + + @Test + public void unknownKeyStoreType() { + try { + config.put("keystore.type", "test"); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.01", e.getErrorId()); + } + } + + @Test + public void pkcs11KeyStoreType() throws EaafConfigurationException { + config.put("keystore.type", "pkcs11"); + try { + final KeyStoreConfiguration keyStoreConfig = KeyStoreConfiguration.buildFromConfigurationMap(config, + "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.02", e.getErrorId()); + } + } + + @Test + public void hsmFacadeKeyStoreTypeMissingName() { + try { + config.put("keystore.type", "hsmfacade"); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.04", e.getErrorId()); + } + } + + @Test + public void hsmFacadeKeyStoreTypeSucces() throws EaafConfigurationException { + final String keyStoreName = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.type", "hsmfacade"); + config.put("keystore.name", keyStoreName); + + final KeyStoreConfiguration keyStoreConfig = KeyStoreConfiguration.buildFromConfigurationMap(config, + "jUnitTest"); + + Assert.assertNotNull("KeyStore config object", keyStoreConfig); + Assert.assertEquals("Wrong Type", KeyStoreType.HSMFACADE, keyStoreConfig.getKeyStoreType()); + Assert.assertEquals("Wrong KeyStoreName", keyStoreName, keyStoreConfig.getKeyStoreName()); + + } + + @Test + public void softwareKeyStoreTypeMissingPath() { + try { + final String keyStorePass = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.type", "software"); + config.put("keystore.password", keyStorePass); + config.put("keystore.type", "jks"); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.04", e.getErrorId()); + } + } + + @Test + public void softwareKeyStoreTypeMissingPassword() { + try { + final String keyStorePath = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.type", "software"); + config.put("keystore.software.path", keyStorePath); + config.put("keystore.type", "jks"); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.04", e.getErrorId()); + } + } + + @Test + public void softwareKeyStoreTypeUnknownType() { + try { + final String keyStorePath = RandomStringUtils.randomAlphabetic(5); + final String keyStorePass = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.path", keyStorePath); + config.put("keystore.password", keyStorePass); + config.put("keystore.type", RandomStringUtils.randomAlphabetic(4)); + + KeyStoreConfiguration.buildFromConfigurationMap(config, "jUnitTest"); + Assert.fail("Wrong config not detected"); + + } catch (final EaafConfigurationException e) { + Assert.assertEquals("wrong errorCode", "internal.keystore.01", e.getErrorId()); + } + } + + @Test + public void softwareKeyStoreTypeSuccesJks() throws EaafConfigurationException { + final String keyStorePath = RandomStringUtils.randomAlphabetic(5); + final String keyStorePass = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.type", "jks"); + config.put("keystore.path", keyStorePath); + config.put("keystore.password", keyStorePass); + + final KeyStoreConfiguration keyStoreConfig = KeyStoreConfiguration.buildFromConfigurationMap(config, + "jUnitTest"); + + Assert.assertNotNull("KeyStore config object", keyStoreConfig); + Assert.assertEquals("Wrong Type", KeyStoreType.JKS, keyStoreConfig.getKeyStoreType()); + Assert.assertEquals("Wrong KeyStoreName", keyStorePath, keyStoreConfig.getSoftKeyStoreFilePath()); + Assert.assertEquals("Wrong KeyStoreName", keyStorePass, keyStoreConfig.getSoftKeyStorePassword()); + + } + + @Test + public void softwareKeyStoreTypeSuccesPkcs12() throws EaafConfigurationException { + final String keyStorePath = RandomStringUtils.randomAlphabetic(5); + final String keyStorePass = RandomStringUtils.randomAlphabetic(5); + config.put("keystore.type", "pkcs12"); + config.put("keystore.path", keyStorePath); + config.put("keystore.password", keyStorePass); + + final KeyStoreConfiguration keyStoreConfig = KeyStoreConfiguration.buildFromConfigurationMap(config, + "jUnitTest"); + + Assert.assertNotNull("KeyStore config object", keyStoreConfig); + Assert.assertEquals("Wrong Type", KeyStoreType.PKCS12, keyStoreConfig.getKeyStoreType()); + Assert.assertEquals("Wrong KeyStoreName", keyStorePath, keyStoreConfig.getSoftKeyStoreFilePath()); + Assert.assertEquals("Wrong KeyStoreName", keyStorePass, keyStoreConfig.getSoftKeyStorePassword()); + + } +} diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/dummy/DummyAuthConfigMap.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/dummy/DummyAuthConfigMap.java new file mode 100644 index 00000000..bf1dfd03 --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/dummy/DummyAuthConfigMap.java @@ -0,0 +1,142 @@ +package at.gv.egiz.eaaf.core.test.dummy; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; +import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; + +/** + * Dummy Application-configuration implementation for jUnit tests. + * + * @author tlenz + * + */ +public class DummyAuthConfigMap implements IConfigurationWithSP { + + private Map<String, String> config = new HashMap<>(); + + /** + * Creates an emptry configuration. + * + */ + public DummyAuthConfigMap() { + + } + + /** + * Dummy Application-configuration. + * + * @param configIs Property based configuration + * @throws IOException In case of an configuration read error + */ + public DummyAuthConfigMap(final InputStream configIs) throws IOException { + + final Properties props = new Properties(); + props.load(configIs); + + config = KeyValueUtils.convertPropertiesToMap(props); + + } + + /** + * Dummy Application-configuration. + * + * @param path Path to property based configuration + * @throws IOException In case of an configuration read error + */ + public DummyAuthConfigMap(final String path) throws IOException { + + final Properties props = new Properties(); + props.load(this.getClass().getResourceAsStream(path)); + + config = KeyValueUtils.convertPropertiesToMap(props); + + } + + @Override + public String getBasicConfiguration(final String key) { + return config.get(key); + + } + + @Override + public String getBasicConfiguration(final String key, final String defaultValue) { + final String value = getBasicConfiguration(key); + if (StringUtils.isEmpty(value)) { + return defaultValue; + } else { + return value; + } + + } + + @Override + public boolean getBasicConfigurationBoolean(final String key) { + final String value = getBasicConfiguration(key); + if (StringUtils.isEmpty(value)) { + return false; + } else { + return Boolean.valueOf(value); + } + } + + @Override + public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue) { + return Boolean.parseBoolean(getBasicConfiguration(key, String.valueOf(defaultValue))); + + } + + @Override + public Map<String, String> getBasicConfigurationWithPrefix(final String prefix) { + return KeyValueUtils.getSubSetWithPrefix(config, prefix); + + } + + @Override + public ISpConfiguration getServiceProviderConfiguration(final String uniqueID) + throws EaafConfigurationException { + return null; + } + + @Override + public <T> T getServiceProviderConfiguration(final String spIdentifier, final Class<T> decorator) + throws EaafConfigurationException { + return null; + } + + @Override + public URI getConfigurationRootDirectory() { + return new java.io.File(".").toURI(); + + } + + @Override + public String validateIdpUrl(final URL authReqUrl) throws EaafException { + return null; + } + + public void putConfigValue(final String key, final String value) { + config.put(key, value); + } + + public void removeConfigValue(final String key) { + config.remove(key); + + } + + public void clearAllConfig() { + config.clear(); + } + +} diff --git a/eaaf_core_utils/src/test/resources/data/junit.jks b/eaaf_core_utils/src/test/resources/data/junit.jks Binary files differnew file mode 100644 index 00000000..59e6ad13 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/junit.jks diff --git a/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.jks b/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.jks Binary files differnew file mode 100644 index 00000000..b5262cb8 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.jks diff --git a/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.p12 b/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.p12 Binary files differnew file mode 100644 index 00000000..c3fe2681 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/junit_without_trustcerts.p12 diff --git a/eaaf_core_utils/src/test/resources/data/test.crt b/eaaf_core_utils/src/test/resources/data/test.crt new file mode 100644 index 00000000..76c18361 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/test.crt @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +MIIEXDCCA0SgAwIBAgIEY4Qn3zANBgkqhkiG9w0BAQsFADCBpzELMAkGA1UEBhMCQVQxSDBGBgNVBAoMP0EtVHJ1c3QgR2VzLiBmLiBTaWNoZXJoZWl0c3N5c3RlbWUgaW0gZWxla3RyLiBEYXRlbnZlcmtlaHIgR21iSDEmMCQGA1UECwwdYS1zaWduLVRlc3QtUHJlbWl1bS1Nb2JpbGUtMDUxJjAkBgNVBAMMHWEtc2lnbi1UZXN0LVByZW1pdW0tTW9iaWxlLTA1MB4XDTE5MTIxMzEzNDg0N1oXDTI0MTIxMzEzNDg0N1owYDELMAkGA1UEBhMCQVQxFzAVBgNVBAMMDk1heCBNdXN0ZXJtYW5uMRMwEQYDVQQEDApNdXN0ZXJtYW5uMQwwCgYDVQQqDANNYXgxFTATBgNVBAUTDDgxNjkyMjY1ODM0ODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAUAVvbow4O/DMA5ZZoPHQXe0rtf86lvH8GLM/Crz1vvRYyQ5D4ESYRFy+s3zHdLqhE4l8I95i9jz2qTvof46mqjggGfMIIBmzCBggYIKwYBBQUHAQEEdjB0MEkGCCsGAQUFBzAChj1odHRwOi8vd3d3LmEtdHJ1c3QuYXQvY2VydHMvYS1zaWduLXRlc3QtcHJlbWl1bS1tb2JpbGUtMDUuY3J0MCcGCCsGAQUFBzABhhtodHRwOi8vb2NzcC5hLXRydXN0LmF0L29jc3AwEwYDVR0jBAwwCoAITuhoD/7N29AwEQYDVR0OBAoECEyqhgBwLul2MA4GA1UdDwEB/wQEAwIGwDAJBgNVHRMEAjAAMIGGBgNVHSAEfzB9MHsGBiooABEBBDBxMDgGCCsGAQUFBwICMCwaKkRpZXNlcyBaZXJ0aWZpa2F0IGRpZW50IG51ciB6dSBUZXN0endlY2tlbjA1BggrBgEFBQcCARYpaHR0cDovL3d3dy5hLXRydXN0LmF0L2RvY3MvY3AvYS1zaWduLVRFU1QwSAYDVR0fBEEwPzA9oDugOYY3aHR0cDovL2NybC5hLXRydXN0LmF0L2NybC9hLXNpZ24tdGVzdC1wcmVtaXVtLW1vYmlsZS0wNTANBgkqhkiG9w0BAQsFAAOCAQEATD4ZnrEV+xeT7PFI/idqHdElLZ1BVUO9G9qfQQn4oKNCWWHxMo/ZXSlvsOtTjFezCQFkcFO1eJtXNHCyqfr69jorzhZcicscNRMrDlJoB/sJr0l/Ekjlt/dgRaTuZ7NzWE/oTefI3M3xkkLd0ydAMrhrZx+9f82VE3k63I1fmT90kQ8PfDzAMMRmlwbZDA+2TB8iF7SQkOOL6H1j2L9qrhjlG2ekU4cyx6KMkRjLLbr1JVgS07qOzUkeQPR2KTJcWWR+/NQZWDKdOz97eVOulxeI+Y3y96arraGM7lIbV9ZrpkbUn/IxQ9TQTE5X02EipgnZdR7bZrwJ7hJ27vwnfQ== +-----END CERTIFICATE----- diff --git a/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_lazy.beans.xml b/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_lazy.beans.xml new file mode 100644 index 00000000..210b88be --- /dev/null +++ b/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_lazy.beans.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" + default-lazy-init="true"> + + <bean id="dummyAuthConfigMap" + class="at.gv.egiz.eaaf.core.test.dummy.DummyAuthConfigMap" /> + + <bean id="eaafKeyStoreFactory" + class="at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory" /> + + <bean id="eaafUtilsMessageSource" + class="at.gv.egiz.eaaf.core.impl.logging.EaafUtilsMessageSource" /> + +</beans>
\ No newline at end of file diff --git a/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_not_lazy.beans.xml b/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_not_lazy.beans.xml new file mode 100644 index 00000000..402e07f9 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/spring/test_eaaf_pvp_not_lazy.beans.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" + default-lazy-init="true"> + + <bean id="dummyAuthConfigMap" + class="at.gv.egiz.eaaf.core.test.dummy.DummyAuthConfigMap" /> + + <import resource="classpath:/spring/eaaf_utils.beans.xml"/> + +</beans>
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java index f607f8cb..11fd41fb 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java @@ -7,17 +7,37 @@ public class Constants { public static final String CONFIG_PROP_VDA_AUTHBLOCK_TRANSFORMATION_ID = CONFIG_PROP_PREFIX + ".vda.authblock.transformation.id"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_PATH = CONFIG_PROP_PREFIX + ".security.keystore.path"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD = CONFIG_PROP_PREFIX - + ".security.keystore.password"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS = CONFIG_PROP_PREFIX + ".security.sign.alias"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD = CONFIG_PROP_PREFIX - + ".security.sign.password"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS = CONFIG_PROP_PREFIX - + ".security.encryption.alias"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD = CONFIG_PROP_PREFIX - + ".security.encryption.password"; + + //KeyStore configuration + public static final String CONFIG_PROP_SECURITY_KEYSTORE_TYPE = + CONFIG_PROP_PREFIX + ".security.keystore.type"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_NAME = + CONFIG_PROP_PREFIX + ".security.keystore.name"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_PATH = + CONFIG_PROP_PREFIX + ".security.keystore.path"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD = + CONFIG_PROP_PREFIX + ".security.keystore.password"; + + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS = + CONFIG_PROP_PREFIX + ".security.sign.alias"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD = + CONFIG_PROP_PREFIX + ".security.sign.password"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS = + CONFIG_PROP_PREFIX + ".security.encryption.alias"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD = + CONFIG_PROP_PREFIX + ".security.encryption.password"; + //TrustStore configuration + public static final String CONFIG_PROP_SECURITY_TRUSTSTORE_TYPE = + CONFIG_PROP_PREFIX + ".security.truststore.type"; + public static final String CONFIG_PROP_SECURITY_TRUSTSTORE_NAME = + CONFIG_PROP_PREFIX + ".security.truststore.name"; + public static final String CONFIG_PROP_SECURITY_TRUSTSTORE_PATH = + CONFIG_PROP_PREFIX + ".security.truststore.path"; + public static final String CONFIG_PROP_SECURITY_TRUSTSTORE_PASSWORD = + CONFIG_PROP_PREFIX + ".security.truststore.password"; + + public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT = "default"; public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT = CONFIG_PROP_VDA_ENDPOINT_QUALeID + CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT; diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java index 0d2c1815..259c21bf 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java @@ -1,17 +1,12 @@ package at.gv.egiz.eaaf.modules.auth.sl20.utils; import java.io.IOException; -import java.net.MalformedURLException; import java.security.Key; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.PrivateKey; -import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.Collections; -import java.util.Enumeration; import java.util.List; import javax.annotation.Nonnull; @@ -38,9 +33,13 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exception.EaafKeyAccessException; import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; +import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.utils.X509Utils; import at.gv.egiz.eaaf.modules.auth.sl20.Constants; import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; @@ -53,88 +52,60 @@ import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoParserException; public class JsonSecurityUtils implements IJoseTools { private static final Logger log = LoggerFactory.getLogger(JsonSecurityUtils.class); - @Autowired(required = true) - IConfiguration authConfig; - private Key signPrivKey = null; - private X509Certificate[] signCertChain = null; - - private Key encPrivKey = null; - private X509Certificate[] encCertChain = null; - - private List<X509Certificate> trustedCerts = new ArrayList<>(); - + private static final String FRIENDLYNAME_KEYSTORE = "SL2.0 KeyStore"; + private static final String FRIENDLYNAME_TRUSTSTORE = "SL2.0 TrustStore"; + + @Autowired(required = true) IConfiguration authConfig; + @Autowired(required = true) EaafKeyStoreFactory keystoreFactory; + + private KeyStore keyStore; + private KeyStore trustStore; + private static JsonMapper mapper = new JsonMapper(); @PostConstruct - protected void initalize() { + protected void initalize() throws SL20Exception { log.info("Initialize SL2.0 authentication security constrains ... "); try { - if (getKeyStoreFilePath() != null) { - final KeyStore keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), getKeyStorePassword()); - - // load signing key - signPrivKey = keyStore.getKey(getSigningKeyAlias(), getSigningKeyPassword().toCharArray()); - final Certificate[] certChainSigning = keyStore.getCertificateChain(getSigningKeyAlias()); - signCertChain = new X509Certificate[certChainSigning.length]; - for (int i = 0; i < certChainSigning.length; i++) { - if (certChainSigning[i] instanceof X509Certificate) { - signCertChain[i] = (X509Certificate) certChainSigning[i]; - } else { - log.warn("NO X509 certificate for signing: " + certChainSigning[i].getType()); - } - - } - - // load encryption key - try { - encPrivKey = keyStore.getKey(getEncryptionKeyAlias(), getEncryptionKeyPassword().toCharArray()); - if (encPrivKey != null) { - final Certificate[] certChainEncryption = keyStore.getCertificateChain(getEncryptionKeyAlias()); - encCertChain = new X509Certificate[certChainEncryption.length]; - for (int i = 0; i < certChainEncryption.length; i++) { - if (certChainEncryption[i] instanceof X509Certificate) { - encCertChain[i] = (X509Certificate) certChainEncryption[i]; - } else { - log.warn("NO X509 certificate for encryption: " + certChainEncryption[i].getType()); - } - } - } else { - log.info("No encryption key for SL2.0 found. End-to-End encryption is not used."); - } - - } catch (final Exception e) { - log.warn("No encryption key for SL2.0 found. End-to-End encryption is not used. Reason: " + e.getMessage(), - e); - - } - - // load trusted certificates - trustedCerts = readCertsFromKeyStore(keyStore); - - // some short validation - if (signPrivKey == null || !(signPrivKey instanceof PrivateKey)) { - log.info("Can NOT open privateKey for SL2.0 signing. KeyStore=" + getKeyStoreFilePath()); - throw new SL20Exception("sl20.03", new Object[] { "Can NOT open private key for signing" }); - - } - - if (signCertChain == null || signCertChain.length == 0) { - log.info("NO certificate for SL2.0 signing. KeyStore=" + getKeyStoreFilePath()); - throw new SL20Exception("sl20.03", new Object[] { "NO certificate for SL2.0 signing" }); - - } - - log.info("SL2.0 authentication security constrains initialized."); - + //load KeyStore + KeyStoreConfiguration keyStoreConfig = buildKeyStoreConfiguration(); + keyStore = keystoreFactory.buildNewKeyStore(keyStoreConfig); + + //load TrustStore + KeyStoreConfiguration trustStoreConfig = buildTrustStoreConfiguration(); + trustStore = keystoreFactory.buildNewKeyStore(trustStoreConfig); + + //validate KeyStore entries + EaafKeyStoreUtils.getPrivateKeyAndCertificates(keyStore, getSigningKeyAlias(), + getSigningKeyPassword(), true, FRIENDLYNAME_KEYSTORE); + Pair<Key, X509Certificate[]> encCredentials = + EaafKeyStoreUtils.getPrivateKeyAndCertificates(keyStore, getEncryptionKeyAlias(), + getEncryptionKeyPassword(), false, FRIENDLYNAME_TRUSTSTORE); + if (encCredentials == null) { + log.info("No encryption key for SL2.0 found. End-to-End encryption is not used."); + + } + + //validate TrustStore + List<X509Certificate> trustedCerts = EaafKeyStoreUtils.readCertsFromKeyStore(trustStore); + if (trustedCerts.isEmpty()) { + log.info("No certificates in TrustStore: {}. Signature validation will FAIL!", + FRIENDLYNAME_TRUSTSTORE); + } else { - log.info("NO SL2.0 authentication security configuration. Initialization was skipped"); + log.info("Find #{} certificates in TrustStore: {}", + trustedCerts.size(), FRIENDLYNAME_TRUSTSTORE); + } + + log.info("SL2.0 authentication security constrains initialized."); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { - log.error("SL2.0 security constrains initialization FAILED.", e); + log.error("SL2.0 security constrains initialization FAILED."); + throw new SL20Exception("sl20.11", new Object[] {e.getMessage()}, e); } @@ -153,15 +124,18 @@ public class JsonSecurityUtils implements IJoseTools { // set signing information jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); - jws.setKey(signPrivKey); + Pair<Key, X509Certificate[]> signingCred = EaafKeyStoreUtils.getPrivateKeyAndCertificates(keyStore, + getSigningKeyAlias(), getSigningKeyPassword(), true, FRIENDLYNAME_KEYSTORE); + + jws.setKey(signingCred.getFirst()); // TODO: - jws.setCertificateChainHeaderValue(signCertChain); - jws.setX509CertSha256ThumbprintHeaderValue(signCertChain[0]); + jws.setCertificateChainHeaderValue(signingCred.getSecond()); + jws.setX509CertSha256ThumbprintHeaderValue(signingCred.getSecond()[0]); return jws.getCompactSerialization(); - } catch (final JoseException e) { + } catch (final JoseException | EaafKeyAccessException e) { log.warn("Can NOT sign SL2.0 command.", e); throw new SlCommandoBuildException("Can NOT sign SL2.0 command.", e); @@ -172,7 +146,7 @@ public class JsonSecurityUtils implements IJoseTools { @Override public VerificationResult validateSignature(final String serializedContent, final KeyStore trustStore, final AlgorithmConstraints algconstraints) throws JoseException, IOException, KeyStoreException { - final List<X509Certificate> trustedCertificates = readCertsFromKeyStore(trustStore); + final List<X509Certificate> trustedCertificates = EaafKeyStoreUtils.readCertsFromKeyStore(trustStore); return validateSignature(serializedContent, trustedCertificates, algconstraints); } @@ -244,7 +218,8 @@ public class JsonSecurityUtils implements IJoseTools { SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING .toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING.size()])); - final VerificationResult result = validateSignature(serializedContent, trustedCerts, algConstraints); + final VerificationResult result = + validateSignature(serializedContent, EaafKeyStoreUtils.readCertsFromKeyStore(trustStore), algConstraints); if (!result.isValidSigned()) { log.info("JWS signature invalide. Stopping authentication process ..."); @@ -256,7 +231,7 @@ public class JsonSecurityUtils implements IJoseTools { log.debug("SL2.0 commando signature validation sucessfull"); return result; - } catch (JoseException | JsonParseException e) { + } catch (JoseException | JsonParseException | KeyStoreException e) { log.warn("SL2.0 commando signature validation FAILED", e); throw new SL20SecurityException(new Object[] { e.getMessage() }, e); @@ -284,6 +259,9 @@ public class JsonSecurityUtils implements IJoseTools { // set payload receiverJwe.setCompactSerialization(compactSerialization); + Pair<Key, X509Certificate[]> encryptionCred = EaafKeyStoreUtils.getPrivateKeyAndCertificates(keyStore, + getEncryptionKeyAlias(), getEncryptionKeyPassword(), true, FRIENDLYNAME_KEYSTORE); + // validate key from header against key from config final List<X509Certificate> x5cCerts = receiverJwe.getCertificateChainHeaderValue(); final String x5t256 = receiverJwe.getX509CertSha256ThumbprintHeaderValue(); @@ -292,7 +270,7 @@ public class JsonSecurityUtils implements IJoseTools { log.trace("Sorting received X509 certificates ... "); final List<X509Certificate> sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); - if (!sortedX5cCerts.get(0).equals(encCertChain[0])) { + if (!sortedX5cCerts.get(0).equals(encryptionCred.getSecond()[0])) { log.info("Certificate from JOSE header does NOT match encryption certificate"); try { @@ -307,7 +285,7 @@ public class JsonSecurityUtils implements IJoseTools { } else if (StringUtils.isNotEmpty(x5t256)) { log.debug("Found x5t256 fingerprint in JOSE header .... "); - final String certFingerPrint = X509Util.x5tS256(encCertChain[0]); + final String certFingerPrint = X509Util.x5tS256(encryptionCred.getSecond()[0]); if (!certFingerPrint.equals(x5t256)) { log.info("X5t256 from JOSE header does NOT match encryption certificate"); log.debug("X5t256 from JOSE header: " + x5t256 + " Encrytption cert: " + certFingerPrint); @@ -324,12 +302,12 @@ public class JsonSecurityUtils implements IJoseTools { } // set key - receiverJwe.setKey(encPrivKey); + receiverJwe.setKey(encryptionCred.getFirst()); // decrypt payload return mapper.getMapper().readTree(receiverJwe.getPlaintextString()); - } catch (final JoseException e) { + } catch (final JoseException | EaafKeyAccessException e) { log.warn("SL2.0 result decryption FAILED", e); throw new SL20SecurityException(new Object[] { e.getMessage() }, e); @@ -340,37 +318,74 @@ public class JsonSecurityUtils implements IJoseTools { } catch (final IOException e) { log.warn("Decrypted SL2.0 result can not be parsed.", e); throw new SlCommandoParserException("Decrypted SL2.0 result can not be parsed", e); + } - } @Override public X509Certificate getEncryptionCertificate() { - // TODO: maybe update after SL2.0 update on encryption certificate parts - if (encCertChain != null && encCertChain.length > 0) { - return encCertChain[0]; - } else { - return null; + Pair<Key, X509Certificate[]> encryptionCred; + try { + encryptionCred = EaafKeyStoreUtils.getPrivateKeyAndCertificates(keyStore, + getEncryptionKeyAlias(), getEncryptionKeyPassword(), false, FRIENDLYNAME_KEYSTORE); + if (encryptionCred != null && encryptionCred.getSecond().length > 0) { + return encryptionCred.getSecond()[0]; + + } + + } catch (EaafKeyAccessException e) { + log.trace("Exception is skipped because Encryption is not mandatory on this level", e); + } + + return null; + } - private String getKeyStoreFilePath() throws EaafConfigurationException, MalformedURLException { - return FileUtils.makeAbsoluteUrl(authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PATH), - authConfig.getConfigurationRootDirectory()); + private KeyStoreConfiguration buildKeyStoreConfiguration() throws EaafConfigurationException { + KeyStoreConfiguration config = new KeyStoreConfiguration(); + config.setFriendlyName(FRIENDLYNAME_KEYSTORE); + + config.setKeyStoreType(authConfig.getBasicConfiguration( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_TYPE), + KeyStoreType.JKS.getKeyStoreType())); + config.setKeyStoreName( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_NAME)); + config.setSoftKeyStoreFilePath( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PATH)); + config.setSoftKeyStorePassword( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD)); + + //validate configuration state + config.validate(); + + return config; + } - - private String getKeyStorePassword() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD); - if (value != null) { - value = value.trim(); - } - - return value; - + + private KeyStoreConfiguration buildTrustStoreConfiguration() throws EaafConfigurationException { + KeyStoreConfiguration config = new KeyStoreConfiguration(); + config.setFriendlyName(FRIENDLYNAME_TRUSTSTORE); + + config.setKeyStoreType(authConfig.getBasicConfiguration( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_TRUSTSTORE_TYPE), + KeyStoreType.JKS.getKeyStoreType())); + config.setKeyStoreName( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_TRUSTSTORE_NAME)); + config.setSoftKeyStoreFilePath( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_TRUSTSTORE_PATH)); + config.setSoftKeyStorePassword( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_TRUSTSTORE_PASSWORD)); + + //validate configuration state + config.validate(); + + return config; } + private String getSigningKeyAlias() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS).trim(); + String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS); if (value != null) { value = value.trim(); } @@ -378,18 +393,17 @@ public class JsonSecurityUtils implements IJoseTools { return value; } - private String getSigningKeyPassword() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD).trim(); + private char[] getSigningKeyPassword() { + String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD); if (value != null) { - value = value.trim(); + return value.trim().toCharArray(); } - return value; + return null; } private String getEncryptionKeyAlias() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS) - .trim(); + String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS); if (value != null) { value = value.trim(); } @@ -397,36 +411,13 @@ public class JsonSecurityUtils implements IJoseTools { return value; } - private String getEncryptionKeyPassword() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD) - .trim(); + private char[] getEncryptionKeyPassword() { + String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD); if (value != null) { - value = value.trim(); - } - - return value; - } - - @Nonnull - private List<X509Certificate> readCertsFromKeyStore(@Nonnull final KeyStore keyStore) throws KeyStoreException { - final List<X509Certificate> result = new ArrayList<>(); - - final Enumeration<String> aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - final String el = aliases.nextElement(); - log.trace("Process TrustStoreEntry: " + el); - if (keyStore.isCertificateEntry(el)) { - final Certificate cert = keyStore.getCertificate(el); - if (cert != null && cert instanceof X509Certificate) { - result.add((X509Certificate) cert); - } else { - log.info("Can not process entry: {}. Reason: {}", el, cert != null ? cert.getType() : "cert is null"); - } - - } + return value.trim().toCharArray(); } - return Collections.unmodifiableList(result); + return null; } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/pom.xml b/eaaf_modules/eaaf_module_pvp2_core/pom.xml index c9aac506..a81ad889 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/pom.xml +++ b/eaaf_modules/eaaf_module_pvp2_core/pom.xml @@ -22,7 +22,6 @@ <artifactId>eaaf-core</artifactId> <version>${egiz.eaaf.version}</version> </dependency> - <dependency> <groupId>org.opensaml</groupId> <artifactId>opensaml-core</artifactId> @@ -82,6 +81,12 @@ <artifactId>mockwebserver</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>xml-apis</groupId> + <artifactId>xml-apis</artifactId> + <version>1.4.01</version> + <scope>test</scope> + </dependency> </dependencies> diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java index 8a33b205..902f84c7 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java @@ -406,6 +406,7 @@ public abstract class AbstractChainingMetadataProvider implements IGarbageCollec private void addAndRemoveMetadataProvider() throws EaafConfigurationException { log.info("EAAF chaining metadata resolver starting internal managment task .... "); + // get all actually loaded metadata providers final Map<String, MetadataResolver> loadedproviders = getAllActuallyLoadedResolvers(); @@ -428,6 +429,7 @@ public abstract class AbstractChainingMetadataProvider implements IGarbageCollec try { if (StringUtils.isNotEmpty(metadataurl) && loadedproviders.containsKey(metadataurl)) { + // SAML2 SP is actually loaded, to nothing loadedproviders.remove(metadataurl); } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java index 6959b6bd..cd77228c 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java @@ -19,8 +19,6 @@ package at.gv.egiz.eaaf.modules.pvp2.impl.utils; -import java.io.IOException; -import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; @@ -33,24 +31,24 @@ import java.util.List; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; +import org.apache.commons.lang3.StringUtils; +import org.apache.xml.security.algorithms.JCEMapper; +import org.opensaml.security.credential.UsageType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ResourceLoader; + import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; import at.gv.egiz.eaaf.core.exceptions.EaafException; -import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; import at.gv.egiz.eaaf.modules.pvp2.api.utils.IPvp2CredentialProvider; import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.EaafKeyStoreX509CredentialAdapter; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.security.credential.UsageType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; - import lombok.extern.slf4j.Slf4j; @Slf4j @@ -63,6 +61,9 @@ public abstract class AbstractCredentialProvider implements IPvp2CredentialProvi @Autowired protected IConfiguration basicConfig; + @Autowired + private EaafKeyStoreFactory keyStoreFactory; + private KeyStore keyStore = null; /** @@ -71,23 +72,25 @@ public abstract class AbstractCredentialProvider implements IPvp2CredentialProvi * * @return keyStore friendlyName */ - public abstract String getFriendlyName(); + public final String getFriendlyName() { + try { + return getBasicKeyStoreConfig().getFriendlyName(); + + } catch (EaafConfigurationException e) { + return "No KeyStoreName"; + + } - /** - * Get KeyStore. - * - * @return URL to the keyStore - * @throws EaafException In case of an invalid filepath - */ - @Nonnull - public abstract String getKeyStoreFilePath() throws EaafException; + } /** - * Get keyStore password. + * Get the basic KeyStore configuration object for this SAML2 credential. * - * @return Password of the keyStore + * @return KeyStore configuration object + * @throws EaafConfigurationException In case of a configuration error */ - public abstract String getKeyStorePassword(); + @Nonnull + public abstract KeyStoreConfiguration getBasicKeyStoreConfig() throws EaafConfigurationException; /** * Get alias of key for metadata signing. @@ -154,8 +157,6 @@ public abstract class AbstractCredentialProvider implements IPvp2CredentialProvi } } - - /** * Get Credentials to sign SAML2 messages, like AuthnRequest, Response, * Assertions as some examples. @@ -250,21 +251,36 @@ public abstract class AbstractCredentialProvider implements IPvp2CredentialProvi } - @Lazy @PostConstruct private void initialize() throws Exception { try { - final Resource ressource = resourceLoader.getResource(getKeyStoreFilePath()); - final InputStream is = ressource.getInputStream(); - keyStore = KeyStoreUtils.loadKeyStore(is, getKeyStorePassword()); + final KeyStoreConfiguration keyStoreConfig = getBasicKeyStoreConfig(); + keyStore = keyStoreFactory.buildNewKeyStore(keyStoreConfig); + + if (JCEMapper.getProviderId() != null + && !JCEMapper.getProviderId().equals(keyStore.getProvider().getName())) { + log.error("OpenSAML3.x can ONLY use a single type of CryptoProvider in an application. " + + "Can NOT set: {}, because {} was already set", keyStore.getProvider().getName(), + JCEMapper.getProviderId()); + throw new EaafConfigurationException(EaafKeyStoreFactory.ERRORCODE_06, + new Object[] { keyStoreConfig.getFriendlyName(), + "OpenSAML3.x can ONLY use a single type of CryptoProvider" }); + + } - if (keyStore == null) { - throw new EaafConfigurationException("module.00", - new Object[] { getFriendlyName(), "KeyStore initialization failed. Maybe wrong password" }); + // Set JCEMapper only in case of HSM based KeyStores because Software KeyStores + // can use + // the default SecurityProvider system in OpenSAML3.x signing engine + if (!KeyStoreType.JKS.equals(keyStoreConfig.getKeyStoreType()) + && !KeyStoreType.PKCS12.equals(keyStoreConfig.getKeyStoreType()) + && JCEMapper.getProviderId() == null) { + log.info("Register CryptoProvider: {} as defaut for OpenSAML3.x", + keyStore.getProvider().getName()); + JCEMapper.setProviderId(keyStore.getProvider().getName()); } - } catch (IOException | KeyStoreException | EaafException e) { + } catch (final EaafException e) { log.error("Can not initialize KeyStore for eIDAS authentication client.", e); throw e; diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java index b6171e97..22ee389f 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/CredentialProviderTest.java @@ -3,14 +3,8 @@ package at.gv.egiz.eaaf.modules.pvp2.test; import java.security.cert.X509Certificate; import java.util.List; -import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyAuthConfigMap; -import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider; - import org.apache.commons.lang3.RandomStringUtils; +import org.apache.xml.security.algorithms.JCEMapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -23,6 +17,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafFactoryException; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyAuthConfigMap; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.test.dummy.DummyCredentialProvider; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ @@ -34,9 +36,14 @@ public class CredentialProviderTest { private static final String PATH_JKS_WITH_TRUST_CERTS = "src/test/resources/data/junit.jks"; private static final String PATH_JKS_WITHOUT_TRUST_CERTS = "src/test/resources/data/junit_without_trustcerts.jks"; + //private static final String HSMF_ALIAS_METADATA = "shibboleth-sign"; + //private static final String HSMF_ALIAS_SIGN = "shibboleth-sign"; + //private static final String HSMF_ALIAS_ENC = "shibboleth-sign"; + private static final String ALIAS_METADATA = "meta"; private static final String ALIAS_SIGN = "sig"; private static final String ALIAS_ENC = "meta"; + private static final String PASSWORD = "password"; @@ -59,6 +66,8 @@ public class CredentialProviderTest { config.removeConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_ALIAS); config.removeConfigValue(DummyCredentialProvider.KEY_ENCRYPTION_PASSWORD); + + JCEMapper.setProviderId(null); } @@ -86,7 +95,7 @@ public class CredentialProviderTest { Assert.fail("No KeyStore not detected"); } catch (final BeansException e) { - org.springframework.util.Assert.isInstanceOf(java.io.FileNotFoundException.class, + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, e.getCause(), "Wrong exception"); } @@ -101,7 +110,7 @@ public class CredentialProviderTest { Assert.fail("No KeyStore not detected"); } catch (final BeansException e) { - org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + org.springframework.util.Assert.isInstanceOf(EaafFactoryException.class, e.getCause(), "Wrong exception"); } @@ -384,6 +393,33 @@ public class CredentialProviderTest { @Test @DirtiesContext + public void otherKeyStoreTypeAlreadyLoaded() throws CredentialsNotAvailableException { + config.putConfigValue(DummyCredentialProvider.KEYSTORE_PATH, PATH_JKS_WITHOUT_TRUST_CERTS); + + config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_RSA_ALG, + "RSA-SIG_" + RandomStringUtils.randomAlphabetic(10)); + config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_SIGNING_EC_ALG, + "EC-SIG_" + RandomStringUtils.randomAlphabetic(10)); + config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_RSA_ALG, + "RSA_ENC_" + RandomStringUtils.randomAlphabetic(10)); + config.putConfigValue(PvpConstants.CONFIG_PROP_SEC_ENCRYPTION_KEY_EC_ALG, + "EC-ENC_" + RandomStringUtils.randomAlphabetic(10)); + + try { + JCEMapper.setProviderId(RandomStringUtils.randomAlphabetic(5)); + + context.getBean(DummyCredentialProvider.class); + + } catch (final BeansException e) { + org.springframework.util.Assert.isInstanceOf(EaafConfigurationException.class, + e.getCause(), "Wrong exception"); + + } + + } + + @Test + @DirtiesContext public void notKeyConfiguration() { final DummyCredentialProvider credential = context.getBean(DummyCredentialProvider.class); diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java index b9f1326d..0f8eff72 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/java/at/gv/egiz/eaaf/modules/pvp2/test/dummy/DummyCredentialProvider.java @@ -1,15 +1,12 @@ package at.gv.egiz.eaaf.modules.pvp2.test.dummy; -import java.net.MalformedURLException; +import org.springframework.beans.factory.annotation.Autowired; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EaafException; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import org.springframework.beans.factory.annotation.Autowired; - public class DummyCredentialProvider extends AbstractCredentialProvider { @Autowired IConfiguration basicConfig; @@ -26,32 +23,26 @@ public class DummyCredentialProvider extends AbstractCredentialProvider { public static final String KEY_ENCRYPTION_ALIAS = "key.enc.alias"; public static final String KEY_ENCRYPTION_PASSWORD = "key.enc.pass"; + private static final String KEYSTORENAME = "jUnit test credential provider"; + @Override - public String getFriendlyName() { - return "jUnit test credential provider"; + public KeyStoreConfiguration getBasicKeyStoreConfig() { + KeyStoreConfiguration keyStoreConfig = new KeyStoreConfiguration(); + keyStoreConfig.setKeyStoreType(KeyStoreType.JKS); + keyStoreConfig.setFriendlyName(KEYSTORENAME); + + keyStoreConfig.setSoftKeyStoreFilePath(getKeyStoreFilePath()); + keyStoreConfig.setSoftKeyStorePassword(getKeyStorePassword()); + + return keyStoreConfig; } - @Override - public String getKeyStoreFilePath() throws EaafException { + public String getKeyStoreFilePath() { final String path = basicConfig.getBasicConfiguration(KEYSTORE_PATH); - - if (path != null) { - try { - return FileUtils.makeAbsoluteUrl( - path, - basicConfig.getConfigurationRootDirectory()); - - } catch (final MalformedURLException e) { - throw new EaafConfigurationException("internel test error", null, e); - - } - } - - throw new EaafConfigurationException("No keyStore path", null); - + return path; + } - @Override public String getKeyStorePassword() { return basicConfig.getBasicConfiguration(KEYSTORE_PASSWORD); } @@ -86,4 +77,5 @@ public class DummyCredentialProvider extends AbstractCredentialProvider { return basicConfig.getBasicConfiguration(KEY_ENCRYPTION_PASSWORD); } + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/config/config_2.props b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/config/config_2.props new file mode 100644 index 00000000..60cecebb --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/config/config_2.props @@ -0,0 +1,12 @@ +keystore.path=classpath:/data/junit.jks +keystore.pass=password +key.metadata.alias=shibboleth-sign +key.metadata.pass=password +key.sig.alias=shibboleth-sign +key.sig.pass=password +key.enc.alias= +key.enc.pass= + +client.http.connection.timeout.socket=2 +client.http.connection.timeout.connection=2 +client.http.connection.timeout.request=2
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core.beans.xml b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core.beans.xml index 3b2d0a28..5e3f0b9b 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core.beans.xml +++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core.beans.xml @@ -19,4 +19,7 @@ <bean id="httpClientFactory" class="at.gv.egiz.eaaf.core.impl.utils.HttpClientFactory" /> + <bean id="eaafKeyStoreFactory" + class="at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory" /> + </beans>
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core_spring_config.beans.xml b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core_spring_config.beans.xml index 5c1a6095..5319236b 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core_spring_config.beans.xml +++ b/eaaf_modules/eaaf_module_pvp2_core/src/test/resources/spring/test_eaaf_core_spring_config.beans.xml @@ -14,4 +14,7 @@ class="at.gv.egiz.eaaf.core.impl.idp.module.test.DummyAuthConfig" /> + <bean id="eaafKeyStoreFactory" + class="at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory" /> + </beans>
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_1.props b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_1.props index 6324f190..164b8807 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_1.props +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_1.props @@ -7,8 +7,6 @@ key.sig.pass=password key.enc.alias= key.enc.pass= -pvp2.assertion.encryption.active=true - client.http.connection.timeout.socket=2 client.http.connection.timeout.connection=2 client.http.connection.timeout.request=2
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_2.props b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_2.props new file mode 100644 index 00000000..60cecebb --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/config/config_2.props @@ -0,0 +1,12 @@ +keystore.path=classpath:/data/junit.jks +keystore.pass=password +key.metadata.alias=shibboleth-sign +key.metadata.pass=password +key.sig.alias=shibboleth-sign +key.sig.pass=password +key.enc.alias= +key.enc.pass= + +client.http.connection.timeout.socket=2 +client.http.connection.timeout.connection=2 +client.http.connection.timeout.request=2
\ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/spring/test_eaaf_core.beans.xml b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/spring/test_eaaf_core.beans.xml index f46b7747..99552053 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/spring/test_eaaf_core.beans.xml +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/test/resources/spring/test_eaaf_core.beans.xml @@ -25,4 +25,7 @@ <bean id="dummyRevisionLogger" class="at.gv.egiz.eaaf.core.impl.logging.DummyRevisionsLogger" /> + <bean id="eaafKeyStoreFactory" + class="at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory" /> + </beans>
\ No newline at end of file @@ -43,13 +43,14 @@ <iaik.prod.iaik_xades.version>2.13_moa</iaik.prod.iaik_xades.version> <iaik.prod.iaik_xsect.version>2.13_moa</iaik.prod.iaik_xsect.version> + <hsm-facade-provider.version>0.1.1-SNAPSHOT</hsm-facade-provider.version> <!-- Other third-party libs --> <org.springframework.version>5.1.5.RELEASE</org.springframework.version> <org.opensaml.version>3.4.3</org.opensaml.version> <org.apache.santuario.xmlsec.version>2.1.4</org.apache.santuario.xmlsec.version> <org.bouncycastle.bcprov-jdk15on.version>1.64</org.bouncycastle.bcprov-jdk15on.version> - + <org.slf4j.version>1.7.25</org.slf4j.version> <commons-codec.version>1.11</commons-codec.version> <org.apache.commons-lang3.version>3.8.1</org.apache.commons-lang3.version> @@ -103,6 +104,13 @@ </activation> <repositories> <repository> + <id>asit</id> + <url>https://dev.a-sit.at/repositories/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> <id>egiz-commons</id> <url>https://apps.egiz.gv.at/maven/</url> <releases> @@ -308,6 +316,12 @@ </dependency> <dependency> + <groupId>at.asitplus.hsmfacade</groupId> + <artifactId>provider</artifactId> + <version>${hsm-facade-provider.version}</version> + </dependency> + + <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>${javax.annotation-api}</version> @@ -483,7 +497,7 @@ <version>${egiz.eaaf.version}</version> <scope>test</scope> <type>test-jar</type> - </dependency> + </dependency> </dependencies> </dependencyManagement> <dependencies> |