Java Code Examples for org.apache.nifi.security.util.KeyStoreUtils

The following examples show how to use org.apache.nifi.security.util.KeyStoreUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: localization_nifi   Source File: PostHTTP.java    License: Apache License 2.0 7 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    builder = builder.useProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 2
private Certificate validateServerKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException,
        InvalidKeyException, NoSuchProviderException, SignatureException {
    serverConfig = objectMapper.readValue(new ByteArrayInputStream(serverConfigFileOutputStream.toByteArray()), TlsConfig.class);

    KeyStore serverKeyStore = KeyStoreUtils.getKeyStore(serverConfig.getKeyStoreType());
    serverKeyStore.load(new ByteArrayInputStream(serverKeyStoreOutputStream.toByteArray()), serverConfig.getKeyStorePassword().toCharArray());
    String keyPassword = serverConfig.getKeyPassword();
    KeyStore.Entry serverKeyEntry = serverKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? serverConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(serverKeyEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) serverKeyEntry;
    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
    assertEquals(1, certificateChain.length);
    Certificate caCertificate = certificateChain[0];
    caCertificate.verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), caCertificate.getPublicKey());
    return caCertificate;
}
 
Example 3
private void validateClient(Certificate caCertificate) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException,
        UnrecoverableEntryException, InvalidKeyException, NoSuchProviderException, SignatureException {
    clientConfig = objectMapper.readValue(new ByteArrayInputStream(clientConfigFileOutputStream.toByteArray()), TlsClientConfig.class);

    KeyStore clientKeyStore = KeyStoreUtils.getKeyStore(clientConfig.getKeyStoreType());
    clientKeyStore.load(new ByteArrayInputStream(clientKeyStoreOutputStream.toByteArray()), clientConfig.getKeyStorePassword().toCharArray());
    String keyPassword = clientConfig.getKeyPassword();
    KeyStore.Entry clientKeyStoreEntry = clientKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? clientConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(clientKeyStoreEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry clientPrivateKeyEntry = (KeyStore.PrivateKeyEntry) clientKeyStoreEntry;
    Certificate[] certificateChain = clientPrivateKeyEntry.getCertificateChain();
    assertEquals(2, certificateChain.length);
    assertEquals(caCertificate, certificateChain[1]);
    certificateChain[0].verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(clientPrivateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());

    KeyStore clientTrustStore = KeyStoreUtils.getTrustStore(KeystoreType.JKS.toString());
    clientTrustStore.load(new ByteArrayInputStream(clientTrustStoreOutputStream.toByteArray()), clientConfig.getTrustStorePassword().toCharArray());
    assertEquals(caCertificate, clientTrustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT));
}
 
Example 4
private void checkClientCert(String clientDn, X509Certificate rootCert) throws Exception {
    String clientDnFile = TlsToolkitStandalone.getClientDnFile(CertificateUtils.reorderDn(clientDn));
    String password;
    try (FileReader fileReader = new FileReader(new File(tempDir, clientDnFile + ".password"))) {
        List<String> lines = IOUtils.readLines(fileReader);
        assertEquals(1, lines.size());
        password = lines.get(0);
    }

    KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
    try (FileInputStream fileInputStream = new FileInputStream(new File(tempDir, clientDnFile + ".p12"))) {
        keyStore.load(fileInputStream, password.toCharArray());
    }
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(TlsToolkitStandalone.NIFI_KEY, new char[0]);
    Certificate[] certificateChain = keyStore.getCertificateChain(TlsToolkitStandalone.NIFI_KEY);
    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    PublicKey publicKey = certificateChain[0].getPublicKey();
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKey, publicKey);

}
 
Example 5
Source Project: localization_nifi   Source File: GetHTTP.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example 6
Source Project: nifi   Source File: TlsCertificateAuthorityTest.java    License: Apache License 2.0 6 votes vote down vote up
private Certificate validateServerKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException,
        InvalidKeyException, NoSuchProviderException, SignatureException {
    serverConfig = objectMapper.readValue(new ByteArrayInputStream(serverConfigFileOutputStream.toByteArray()), TlsConfig.class);

    KeyStore serverKeyStore = KeyStoreUtils.getKeyStore(serverConfig.getKeyStoreType());
    serverKeyStore.load(new ByteArrayInputStream(serverKeyStoreOutputStream.toByteArray()), serverConfig.getKeyStorePassword().toCharArray());
    String keyPassword = serverConfig.getKeyPassword();
    KeyStore.Entry serverKeyEntry = serverKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? serverConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(serverKeyEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) serverKeyEntry;
    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();
    assertEquals(1, certificateChain.length);
    Certificate caCertificate = certificateChain[0];
    caCertificate.verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), caCertificate.getPublicKey());
    return caCertificate;
}
 
Example 7
Source Project: nifi   Source File: TlsCertificateAuthorityTest.java    License: Apache License 2.0 6 votes vote down vote up
private void validateClient(Certificate caCertificate) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException,
        UnrecoverableEntryException, InvalidKeyException, NoSuchProviderException, SignatureException {
    clientConfig = objectMapper.readValue(new ByteArrayInputStream(clientConfigFileOutputStream.toByteArray()), TlsClientConfig.class);

    KeyStore clientKeyStore = KeyStoreUtils.getKeyStore(clientConfig.getKeyStoreType());
    clientKeyStore.load(new ByteArrayInputStream(clientKeyStoreOutputStream.toByteArray()), clientConfig.getKeyStorePassword().toCharArray());
    String keyPassword = clientConfig.getKeyPassword();
    KeyStore.Entry clientKeyStoreEntry = clientKeyStore.getEntry(TlsToolkitStandalone.NIFI_KEY,
            new KeyStore.PasswordProtection(keyPassword == null ? clientConfig.getKeyStorePassword().toCharArray() : keyPassword.toCharArray()));

    assertTrue(clientKeyStoreEntry instanceof KeyStore.PrivateKeyEntry);
    KeyStore.PrivateKeyEntry clientPrivateKeyEntry = (KeyStore.PrivateKeyEntry) clientKeyStoreEntry;
    Certificate[] certificateChain = clientPrivateKeyEntry.getCertificateChain();
    assertEquals(2, certificateChain.length);
    assertEquals(caCertificate, certificateChain[1]);
    certificateChain[0].verify(caCertificate.getPublicKey());
    assertPrivateAndPublicKeyMatch(clientPrivateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());

    KeyStore clientTrustStore = KeyStoreUtils.getTrustStore(KeystoreType.JKS.toString());
    clientTrustStore.load(new ByteArrayInputStream(clientTrustStoreOutputStream.toByteArray()), clientConfig.getTrustStorePassword().toCharArray());
    assertEquals(caCertificate, clientTrustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT));
}
 
Example 8
Source Project: nifi   Source File: TlsToolkitStandaloneTest.java    License: Apache License 2.0 6 votes vote down vote up
private void checkClientCert(String clientDn, X509Certificate rootCert) throws Exception {
    String clientDnFile = TlsHelper.escapeFilename(CertificateUtils.reorderDn(clientDn));
    String password;
    try (FileReader fileReader = new FileReader(new File(tempDir, clientDnFile + ".password"))) {
        List<String> lines = IOUtils.readLines(fileReader);
        assertEquals(1, lines.size());
        password = lines.get(0);
    }

    KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
    try (FileInputStream fileInputStream = new FileInputStream(new File(tempDir, clientDnFile + ".p12"))) {
        keyStore.load(fileInputStream, password.toCharArray());
    }
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(TlsToolkitStandalone.NIFI_KEY, new char[0]);
    Certificate[] certificateChain = keyStore.getCertificateChain(TlsToolkitStandalone.NIFI_KEY);
    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    PublicKey publicKey = certificateChain[0].getPublicKey();
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKey, publicKey);

}
 
Example 9
Source Project: nifi   Source File: GetHTTP.java    License: Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example 10
Source Project: localization_nifi   Source File: BaseTlsManager.java    License: Apache License 2.0 5 votes vote down vote up
protected KeyStore loadKeystore(String keyStore, String keyStoreType, String keyStorePassword) throws GeneralSecurityException, IOException {
    KeyStore result = KeyStoreUtils.getKeyStore(keyStoreType);
    File file = new File(keyStore);
    if (file.exists()) {
        try (InputStream stream = inputStreamFactory.create(file)) {
            result.load(stream, keyStorePassword.toCharArray());
        }
        return result;
    }
    result.load(null, null);
    return result;
}
 
Example 11
Source Project: localization_nifi   Source File: SSLContextFactory.java    License: Apache License 2.0 5 votes vote down vote up
public SSLContextFactory(final NiFiProperties properties) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, UnrecoverableKeyException {
    keystore = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE);
    keystorePass = getPass(properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD));
    keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);

    truststore = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    truststorePass = getPass(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);

    // prepare the keystore
    final KeyStore keyStore = KeyStoreUtils.getKeyStore(keystoreType);
    final FileInputStream keyStoreStream = new FileInputStream(keystore);
    try {
        keyStore.load(keyStoreStream, keystorePass);
    } finally {
        FileUtils.closeQuietly(keyStoreStream);
    }
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass);

    // prepare the truststore
    final KeyStore trustStore = KeyStoreUtils.getTrustStore(truststoreType);
    final FileInputStream trustStoreStream = new FileInputStream(truststore);
    try {
        trustStore.load(trustStoreStream, truststorePass);
    } finally {
        FileUtils.closeQuietly(trustStoreStream);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    keyManagers = keyManagerFactory.getKeyManagers();
    trustManagers = trustManagerFactory.getTrustManagers();
}
 
Example 12
Source Project: nifi   Source File: BaseTlsManager.java    License: Apache License 2.0 5 votes vote down vote up
protected KeyStore loadKeystore(String keyStore, String keyStoreType, String keyStorePassword) throws GeneralSecurityException, IOException {
    KeyStore result = KeyStoreUtils.getKeyStore(keyStoreType);
    File file = new File(keyStore);
    if (file.exists()) {
        try (InputStream stream = inputStreamFactory.create(file)) {
            result.load(stream, keyStorePassword.toCharArray());
        }
        return result;
    }
    result.load(null, null);
    return result;
}
 
Example 13
Source Project: nifi   Source File: TlsToolkitStandaloneTest.java    License: Apache License 2.0 5 votes vote down vote up
private Certificate[] loadCertificateChain(String hostname, X509Certificate rootCert) throws Exception {
    File hostDir = new File(tempDir, hostname);
    Properties nifiProperties = checkHostDirAndReturnNifiProperties(hostname, rootCert);
    String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    String keyStoreFilename = BaseTlsToolkitCommandLine.KEYSTORE + keyStoreType;
    File keyStoreFile = new File(hostDir, keyStoreFilename);
    KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType);

    try (FileInputStream fileInputStream = new FileInputStream(keyStoreFile)) {
        keyStore.load(fileInputStream, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
    }

    return keyStore.getCertificateChain(TlsToolkitStandalone.NIFI_KEY);
}
 
Example 14
Source Project: nifi   Source File: StandardSSLContextService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of {@link ValidationResult}s when validating an actual JKS or PKCS12 file on disk. Verifies the
 * file permissions and existence, and attempts to open the file given the provided password.
 *
 * @param filename     the path of the file on disk
 * @param password     the file password
 * @param type         the type (JKS or PKCS12)
 * @return the list of validation results (empty is valid)
 */
private static List<ValidationResult> validateTruststoreFile(String filename, String password, String type) {
    List<ValidationResult> results = new ArrayList<>();

    final File file = new File(filename);
    if (!file.exists() || !file.canRead()) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject("Truststore Properties")
                .explanation("Cannot access file " + file.getAbsolutePath())
                .build());
    } else {
        char[] passwordChars = new char[0];
        if (!StringUtils.isBlank(password)) {
            passwordChars = password.toCharArray();
        }
        try {
            final boolean storeValid = KeyStoreUtils.isStoreValid(file.toURI().toURL(), KeystoreType.valueOf(type), passwordChars);
            if (!storeValid) {
                results.add(new ValidationResult.Builder()
                        .subject("Truststore Properties")
                        .valid(false)
                        .explanation("Invalid truststore password or type specified for file " + filename)
                        .build());
            }

        } catch (MalformedURLException e) {
            results.add(new ValidationResult.Builder()
                    .subject("Truststore Properties")
                    .valid(false)
                    .explanation("Malformed URL from file: " + e)
                    .build());
        }
    }

    return results;
}
 
Example 15
Source Project: nifi   Source File: PostHTTP.java    License: Apache License 2.0 5 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
        final String alias = keystore.aliases().nextElement();
        final Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            principal = ((X509Certificate) cert).getSubjectDN();
        }
    }

    builder = builder.setProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 16
private Properties checkHostDirAndReturnNifiProperties(String hostname, String dnPrefix, String dnSuffix, X509Certificate rootCert) throws Exception {
    File hostDir = new File(tempDir, hostname);
    Properties nifiProperties = new Properties();
    try (InputStream inputStream = new FileInputStream(new File(hostDir, TlsToolkitStandalone.NIFI_PROPERTIES))) {
        nifiProperties.load(inputStream);
    }

    String trustStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    assertEquals(KeystoreType.JKS.toString().toLowerCase(), trustStoreType.toLowerCase());
    KeyStore trustStore = KeyStoreUtils.getTrustStore(trustStoreType);
    try (InputStream inputStream = new FileInputStream(new File(hostDir, "truststore." + trustStoreType))) {
        trustStore.load(inputStream, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
    }

    String trustStoreFilename = BaseCommandLine.TRUSTSTORE + trustStoreType;
    assertEquals("./conf/" + trustStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));

    Certificate certificate = trustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT);
    assertEquals(rootCert, certificate);

    String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    String keyStoreFilename = BaseCommandLine.KEYSTORE + keyStoreType;
    File keyStoreFile = new File(hostDir, keyStoreFilename);
    assertEquals("./conf/" + keyStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE));

    KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType);
    char[] keyStorePassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray();
    try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
        keyStore.load(inputStream, keyStorePassword);
    }

    char[] keyPassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray();
    if (keyPassword == null || keyPassword.length == 0) {
        keyPassword = keyStorePassword;
    }

    KeyStore.Entry entry = keyStore.getEntry(TlsToolkitStandalone.NIFI_KEY, new KeyStore.PasswordProtection(keyPassword));
    assertEquals(KeyStore.PrivateKeyEntry.class, entry.getClass());

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();

    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    TlsConfig tlsConfig = new TlsConfig();
    tlsConfig.setDnPrefix(dnPrefix);
    tlsConfig.setDnSuffix(dnSuffix);
    assertEquals(tlsConfig.calcDefaultDn(hostname), CertificateUtils.convertAbstractX509Certificate(certificateChain[0]).getSubjectX500Principal().getName());
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());
    return nifiProperties;
}
 
Example 17
Source Project: localization_nifi   Source File: SslContextFactory.java    License: Apache License 2.0 4 votes vote down vote up
public static SSLContext createSslContext(final NiFiProperties props, final boolean strict)
        throws SslContextCreationException {

    final boolean hasKeystoreProperties = hasKeystoreProperties(props);
    if (hasKeystoreProperties == false) {
        if (strict) {
            throw new SslContextCreationException("SSL context cannot be created because keystore properties have not been configured.");
        } else {
            return null;
        }
    } else if (props.getNeedClientAuth() && hasTruststoreProperties(props) == false) {
        throw new SslContextCreationException("Need client auth is set to 'true', but no truststore properties are configured.");
    }

    try {
        // prepare the trust store
        final KeyStore trustStore;
        if (hasTruststoreProperties(props)) {
            trustStore = KeyStoreUtils.getTrustStore(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE));
            try (final InputStream trustStoreStream = new FileInputStream(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
                trustStore.load(trustStoreStream, props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
            }
        } else {
            trustStore = null;
        }
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // prepare the key store
        final KeyStore keyStore = KeyStoreUtils.getKeyStore(props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE));
        try (final InputStream keyStoreStream = new FileInputStream(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
            keyStore.load(keyStoreStream, props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // if the key password is provided, try to use that - otherwise default to the keystore password
        if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD))) {
            keyManagerFactory.init(keyStore, props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }

        // initialize the ssl context
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(),
                trustManagerFactory.getTrustManagers(), null);
        sslContext.getDefaultSSLParameters().setNeedClientAuth(props.getNeedClientAuth());

        return sslContext;

    } catch (final KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException e) {
        throw new SslContextCreationException(e);
    }
}
 
Example 18
/**
 * Loads the trusted certificate authorities according to the specified properties.
 *
 * @param properties properties
 * @return map of certificate authorities
 */
private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) {
    final Map<String, X509Certificate> certificateAuthorities = new HashMap<>();

    // get the path to the truststore
    final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    if (truststorePath == null) {
        throw new IllegalArgumentException("The truststore path is required.");
    }

    // get the truststore password
    final char[] truststorePassword;
    final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
    if (rawTruststorePassword == null) {
        truststorePassword = new char[0];
    } else {
        truststorePassword = rawTruststorePassword.toCharArray();
    }

    // load the configured truststore
    try (final FileInputStream fis = new FileInputStream(truststorePath)) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType());
        truststore.load(fis, truststorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        // consider any certificates in the truststore as a trusted ca
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
                    certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca);
                }
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException("Unable to load the configured truststore: " + e);
    }

    return certificateAuthorities;
}
 
Example 19
Source Project: localization_nifi   Source File: JettyServer.java    License: Apache License 2.0 4 votes vote down vote up
protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}
 
Example 20
Source Project: nifi   Source File: TlsToolkitStandaloneTest.java    License: Apache License 2.0 4 votes vote down vote up
private Properties checkHostDirAndReturnNifiProperties(String hostname, String dnPrefix, String dnSuffix, X509Certificate rootCert) throws Exception {
    File hostDir = new File(tempDir, hostname);
    Properties nifiProperties = new Properties();
    try (InputStream inputStream = new FileInputStream(new File(hostDir, TlsToolkitStandalone.NIFI_PROPERTIES))) {
        nifiProperties.load(inputStream);
    }

    String trustStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    assertEquals(KeystoreType.JKS.toString().toLowerCase(), trustStoreType.toLowerCase());
    KeyStore trustStore = KeyStoreUtils.getTrustStore(trustStoreType);
    try (InputStream inputStream = new FileInputStream(new File(hostDir, "truststore." + trustStoreType))) {
        trustStore.load(inputStream, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
    }

    String trustStoreFilename = BaseTlsToolkitCommandLine.TRUSTSTORE + trustStoreType;
    assertEquals("./conf/" + trustStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));

    Certificate certificate = trustStore.getCertificate(TlsToolkitStandalone.NIFI_CERT);
    assertEquals(rootCert, certificate);

    String keyStoreType = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    String keyStoreFilename = BaseTlsToolkitCommandLine.KEYSTORE + keyStoreType;
    File keyStoreFile = new File(hostDir, keyStoreFilename);
    assertEquals("./conf/" + keyStoreFilename, nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE));

    KeyStore keyStore = KeyStoreUtils.getKeyStore(keyStoreType);
    char[] keyStorePassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray();
    try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
        keyStore.load(inputStream, keyStorePassword);
    }

    char[] keyPassword = nifiProperties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray();
    if (keyPassword == null || keyPassword.length == 0) {
        keyPassword = keyStorePassword;
    }

    KeyStore.Entry entry = keyStore.getEntry(TlsToolkitStandalone.NIFI_KEY, new KeyStore.PasswordProtection(keyPassword));
    assertEquals(KeyStore.PrivateKeyEntry.class, entry.getClass());

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    Certificate[] certificateChain = privateKeyEntry.getCertificateChain();

    assertEquals(2, certificateChain.length);
    assertEquals(rootCert, certificateChain[1]);
    certificateChain[1].verify(rootCert.getPublicKey());
    certificateChain[0].verify(rootCert.getPublicKey());
    TlsConfig tlsConfig = new TlsConfig();
    tlsConfig.setDnPrefix(dnPrefix);
    tlsConfig.setDnSuffix(dnSuffix);
    assertEquals(tlsConfig.calcDefaultDn(hostname), CertificateUtils.convertAbstractX509Certificate(certificateChain[0]).getSubjectX500Principal().getName());
    TlsCertificateAuthorityTest.assertPrivateAndPublicKeyMatch(privateKeyEntry.getPrivateKey(), certificateChain[0].getPublicKey());
    return nifiProperties;
}
 
Example 21
Source Project: nifi   Source File: StandardSSLContextService.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of {@link ValidationResult}s when validating an actual JKS or PKCS12 file on disk. Verifies the
 * file permissions and existence, and attempts to open the file given the provided (keystore or key) password.
 *
 * @param filename     the path of the file on disk
 * @param password     the file password
 * @param keyPassword  the (optional) key-specific password
 * @param type         the type (JKS or PKCS12)
 * @return the list of validation results (empty is valid)
 */
private static List<ValidationResult> validateKeystoreFile(String filename, String password, String keyPassword, String type) {
    List<ValidationResult> results = new ArrayList<>();

    final File file = new File(filename);
    if (!file.exists() || !file.canRead()) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject("Keystore Properties")
                .explanation("Cannot access file " + file.getAbsolutePath())
                .build());
    } else {
        char[] passwordChars = new char[0];
        if (!StringUtils.isBlank(password)) {
            passwordChars = password.toCharArray();
        }
        try {
            final boolean storeValid = KeyStoreUtils.isStoreValid(file.toURI().toURL(), KeystoreType.valueOf(type), passwordChars);
            if (!storeValid) {
                results.add(new ValidationResult.Builder()
                        .subject("Keystore Properties")
                        .valid(false)
                        .explanation("Invalid keystore password or type specified for file " + filename)
                        .build());
            }

            // The key password can be explicitly set (and can be the same as the
            // keystore password or different), or it can be left blank. In the event
            // it's blank, the keystore password will be used
            char[] keyPasswordChars = new char[0];
            if (StringUtils.isBlank(keyPassword) || keyPassword.equals(password)) {
                keyPasswordChars = passwordChars;
            }
            if (!StringUtils.isBlank(keyPassword)) {
                keyPasswordChars = keyPassword.toCharArray();
            }

            boolean keyPasswordValid = KeyStoreUtils.isKeyPasswordCorrect(file.toURI().toURL(), KeystoreType.valueOf(type), passwordChars, keyPasswordChars);
            if (!keyPasswordValid) {
                results.add(new ValidationResult.Builder()
                        .subject("Keystore Properties")
                        .valid(false)
                        .explanation("Invalid key password specified for file " + filename)
                        .build());
            }

        } catch (MalformedURLException e) {
            results.add(new ValidationResult.Builder()
                    .subject("Keystore Properties")
                    .valid(false)
                    .explanation("Malformed URL from file: " + e)
                    .build());
        }
    }

    return results;
}
 
Example 22
Source Project: nifi   Source File: OcspCertificateValidator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Loads the trusted certificate authorities according to the specified properties.
 *
 * @param properties properties
 * @return map of certificate authorities
 */
private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) {
    final Map<String, X509Certificate> certificateAuthorities = new HashMap<>();

    // get the path to the truststore
    final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    if (truststorePath == null) {
        throw new IllegalArgumentException("The truststore path is required.");
    }

    // get the truststore password
    final char[] truststorePassword;
    final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
    if (rawTruststorePassword == null) {
        truststorePassword = new char[0];
    } else {
        truststorePassword = rawTruststorePassword.toCharArray();
    }

    // load the configured truststore
    try (final FileInputStream fis = new FileInputStream(truststorePath)) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType());
        truststore.load(fis, truststorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        // consider any certificates in the truststore as a trusted ca
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
                    certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca);
                }
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException("Unable to load the configured truststore: " + e);
    }

    return certificateAuthorities;
}
 
Example 23
Source Project: nifi   Source File: JettyServer.java    License: Apache License 2.0 4 votes vote down vote up
protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    contextFactory.setEndpointIdentificationAlgorithm(null);

    // Explicitly exclude legacy TLS protocol versions
    // contextFactory.setProtocol(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    contextFactory.setIncludeProtocols(CertificateUtils.getCurrentSupportedTlsProtocolVersions());
    contextFactory.setExcludeProtocols("TLS", "TLSv1", "TLSv1.1", "SSL", "SSLv2", "SSLv2Hello", "SSLv3");

    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}