Search in sources :

Example 1 with KeyStoreProtectionManager

use of org.nhindirect.common.crypto.KeyStoreProtectionManager in project nhin-d by DirectProject.

the class CertificatesController method toCertDataFormat.

/*
	 * Converts an incoming P12 format to an appropriate format to be store in the config store.  If a keystore protection manager
	 * has been configured, then the private key is wrapped before sending to the config store.
	 */
private byte[] toCertDataFormat(byte[] certOrP12Bytes, byte[] privateKeyBytes, PrivateKeyType privKeyType) throws CryptoException {
    try {
        // if there is no private key, then just return the encoded certificate
        if (privKeyType == PrivateKeyType.NONE)
            return certOrP12Bytes;
        final CertContainer cont = CertUtils.toCertContainer(certOrP12Bytes);
        // if this is a PKCS12 format, then either return the bytes as is, or if there is keystore manager, wrap the private keys
        if (privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE | privKeyType == PrivateKeyType.PKCS_12_UNPROTECTED) {
            // as PKCS12 file
            if (this.keyManager == null) {
                this.log.info("Storing PKCS12 file in PKCS12 unprotected format");
                return certOrP12Bytes;
            } else {
                this.log.info("Storing PKCS12 file in wrapped format");
                // now wrap the private key
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), cont.getKey());
                // return the wrapped key format
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        } else // when there is private key file, then either turn into a PKCS12 file (if there is no key manager), or wrap the key.
        {
            // cert and wrapped key format
            if (privKeyType == PrivateKeyType.PKCS8_WRAPPED) {
                this.log.info("Storing already wrapped PKCS8 file");
                return CertUtils.certAndWrappedKeyToRawByteFormat(privateKeyBytes, cont.getCert());
            }
            // get a private key object, the private key is normalized at this point into an unencrypted format
            final KeyFactory kf = KeyFactory.getInstance("RSA", CertUtils.getJCEProviderName());
            final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(privateKeyBytes);
            final Key privKey = kf.generatePrivate(keysp);
            if (this.keyManager == null) {
                this.log.info("Storing PKCS8 private key in PKCS12 unprotected format");
                // if there is no keystore manager, we can't wrap the keys, so we'll just send them over the wire
                // as PKCS12 file.  need to turn this into a PKCS12 format
                final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CertUtils.getJCEProviderName());
                localKeyStore.load(null, null);
                localKeyStore.setKeyEntry("privCert", privKey, "".toCharArray(), new java.security.cert.Certificate[] { cont.getCert() });
                final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
                localKeyStore.store(outStr, "".toCharArray());
                try {
                    return outStr.toByteArray();
                } finally {
                    IOUtils.closeQuietly(outStr);
                }
            } else {
                this.log.info("Storing PKCS8 private key in wrapped format");
                // wrap the key and turn the stream in the wrapped key format
                final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), privKey);
                return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
            }
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to conver certificate and key to cert data format: " + e.getMessage(), e);
    }
}
Also used : PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) MutableKeyStoreProtectionManager(org.nhindirect.common.crypto.MutableKeyStoreProtectionManager) KeyStoreProtectionManager(org.nhindirect.common.crypto.KeyStoreProtectionManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException) KeyStore(java.security.KeyStore) CertContainer(org.nhindirect.config.model.utils.CertUtils.CertContainer) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 2 with KeyStoreProtectionManager

use of org.nhindirect.common.crypto.KeyStoreProtectionManager in project nhin-d by DirectProject.

the class NHINDSecurityAndTrustMailet method init.

/**
	 * {@inheritDoc}
	 */
@Override
public void init() throws MessagingException {
    LOGGER.info("Initializing NHINDSecurityAndTrustMailet");
    super.init();
    // set the outbound policy for notifications if possible
    try {
        final boolean useOutboundPolicy = Boolean.parseBoolean(GatewayConfiguration.getConfigurationParam(SecurityAndTrustMailetOptions.USE_OUTGOING_POLICY_FOR_INCOMING_NOTIFICATIONS, this, "false"));
        // we don't know if this parameter came from the mailet config or the options manager, so just go ahead and set it at
        // the options manager level because that it where the agent reads the value... no danger that we will overwrite the value that we want...
        // we would just be writing the same value if the information came from the options manager module
        // the mailet parameter gets precedence, so we want to overwrite the options manager if the value exists in the mailet configuration
        OptionsManager.getInstance().setOptionsParameter(new OptionsParameter(OptionsParameter.USE_OUTGOING_POLICY_FOR_INCOMING_NOTIFICATIONS, Boolean.toString(useOutboundPolicy)));
    } catch (Exception e) {
    // log a warning that the parameter could not be set
    }
    // set the rejection policy for tampered routing headers
    try {
        final boolean rejectOnTamperPolicy = Boolean.parseBoolean(GatewayConfiguration.getConfigurationParam(SecurityAndTrustMailetOptions.REJECT_ON_ROUTING_TAMPER, this, "false"));
        OptionsManager.getInstance().setOptionsParameter(new OptionsParameter(OptionsParameter.REJECT_ON_ROUTING_TAMPER, Boolean.toString(rejectOnTamperPolicy)));
    } catch (Exception e) {
    // log a warning that the parameter could not be set
    }
    // set the JCE providers if available
    final String JCEName = GatewayConfiguration.getConfigurationParam(SecurityAndTrustMailetOptions.JCE_PROVIDER_NAME, this, "");
    if (!StringUtils.isEmpty(JCEName))
        OptionsManager.getInstance().setOptionsParameter(new OptionsParameter(OptionsParameter.JCE_PROVIDER, JCEName));
    final String sensitiveJCEName = GatewayConfiguration.getConfigurationParam(SecurityAndTrustMailetOptions.JCE_SENTITIVE_PROVIDER, this, "");
    if (!StringUtils.isEmpty(sensitiveJCEName))
        OptionsManager.getInstance().setOptionsParameter(new OptionsParameter(OptionsParameter.JCE_SENTITIVE_PROVIDER, sensitiveJCEName));
    // Get the configuration URL
    final String configURLParam = getInitParameter(SecurityAndTrustMailetOptions.CONFIG_URL_PARAM);
    if (StringUtils.isEmpty(configURLParam)) {
        LOGGER.error("NHINDSecurityAndTrustMailet Configuration URL cannot be empty or null.");
        throw new MessagingException("NHINDSecurityAndTrustMailet Configuration URL cannot be empty or null.");
    }
    // parse into a URL and validate it is properly formed
    URL configURL = null;
    try {
        configURL = new URL(configURLParam);
    } catch (MalformedURLException ex) {
        LOGGER.error("Invalid configuration URL:" + ex.getMessage(), ex);
        throw new MessagingException("NHINDSecurityAndTrustMailet Configuration URL cannot be empty or null.", ex);
    }
    final Collection<Module> modules = getInitModules();
    Provider<SmtpAgentConfig> configProvider;
    try {
        configProvider = this.getConfigProvider();
        if (configProvider == null)
            configProvider = createCompatConfigProvider(configURL);
        if (configProvider instanceof URLAccessedConfigProvider)
            ((URLAccessedConfigProvider) configProvider).setConfigURL(configURL);
        final Provider<ServiceSecurityManager> srvSecMgr = getServiceSecurityManagerProvider();
        if (configProvider instanceof SecureURLAccessedConfigProvider)
            ((SecureURLAccessedConfigProvider) configProvider).setServiceSecurityManager(srvSecMgr);
        final Provider<KeyStoreProtectionManager> keyStoreManagerProvider = getKeyStoreManagerProvider();
        if (configProvider instanceof KeyStoreProtectionConfigProvider && keyStoreManagerProvider != null)
            ((KeyStoreProtectionConfigProvider) configProvider).setKeyStoreProtectionManger(keyStoreManagerProvider);
        agent = SmtpAgentFactory.createAgent(configURL, configProvider, null, modules);
    } catch (SmtpAgentException e) {
        LOGGER.error("Failed to create the SMTP agent: " + e.getMessage(), e);
        throw new MessagingException("Failed to create the SMTP agent: " + e.getMessage(), e);
    }
    ///CLOVER:OFF
    if (agent == null) {
        LOGGER.error("Failed to create the SMTP agent. Reason unknown.");
        throw new MessagingException("Failed to create the SMTP agent.  Reason unknown.");
    }
    ///CLOVER:ON
    // get the DSN creation options
    // default is RELIABLE_DSN_OPTION
    final String dnsCreateOptions = GatewayConfiguration.getConfigurationParam(SecurityAndTrustMailetOptions.AUTO_DSN_FAILURE_CREATION_PARAM, this, RELIABLE_DSN_OPTION);
    for (String dsnOption : dnsCreateOptions.split(",")) {
        if (dsnOption.equalsIgnoreCase(RELIABLE_DSN_OPTION))
            autoDSNForTimelyAndReliable = true;
        else if (dsnOption.equalsIgnoreCase(GENERAL_DSN_OPTION))
            autoDSNForGeneral = true;
    }
    // set the agent and config in the Gateway state
    final GatewayState gwState = GatewayState.getInstance();
    if (gwState.isAgentSettingManagerRunning())
        gwState.stopAgentSettingsManager();
    gwState.setSmtpAgent(agent);
    gwState.setSmptAgentConfig(SmptAgentConfigFactory.createSmtpAgentConfig(configURL, configProvider, null));
    gwState.startAgentSettingsManager();
    LOGGER.info("NHINDSecurityAndTrustMailet initialization complete.");
}
Also used : MalformedURLException(java.net.MalformedURLException) SmtpAgentException(org.nhindirect.gateway.smtp.SmtpAgentException) MessagingException(javax.mail.MessagingException) KeyStoreProtectionManager(org.nhindirect.common.crypto.KeyStoreProtectionManager) MessagingException(javax.mail.MessagingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SmtpAgentException(org.nhindirect.gateway.smtp.SmtpAgentException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) URL(java.net.URL) SmtpAgentConfig(org.nhindirect.gateway.smtp.config.SmtpAgentConfig) OptionsParameter(org.nhindirect.stagent.options.OptionsParameter) ServiceSecurityManager(org.nhindirect.common.rest.ServiceSecurityManager) GatewayState(org.nhindirect.gateway.smtp.GatewayState) SecureURLAccessedConfigProvider(org.nhindirect.gateway.smtp.provider.SecureURLAccessedConfigProvider) URLAccessedConfigProvider(org.nhindirect.gateway.smtp.provider.URLAccessedConfigProvider) SecureURLAccessedConfigProvider(org.nhindirect.gateway.smtp.provider.SecureURLAccessedConfigProvider) Module(com.google.inject.Module) AuditorModule(org.nhindirect.gateway.smtp.module.AuditorModule) KeyStoreProtectionConfigProvider(org.nhindirect.gateway.smtp.provider.KeyStoreProtectionConfigProvider)

Aggregations

KeyStoreProtectionManager (org.nhindirect.common.crypto.KeyStoreProtectionManager)2 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)2 Module (com.google.inject.Module)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Key (java.security.Key)1 KeyFactory (java.security.KeyFactory)1 KeyStore (java.security.KeyStore)1 PrivateKey (java.security.PrivateKey)1 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)1 SecretKey (javax.crypto.SecretKey)1 SecretKeyFactory (javax.crypto.SecretKeyFactory)1 MessagingException (javax.mail.MessagingException)1 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)1 CryptoException (org.nhindirect.common.crypto.exceptions.CryptoException)1 ServiceSecurityManager (org.nhindirect.common.rest.ServiceSecurityManager)1 CertContainer (org.nhindirect.config.model.utils.CertUtils.CertContainer)1