gresockj commented on a change in pull request #4986:
URL: https://github.com/apache/nifi/pull/4986#discussion_r616786463



##########
File path: 
nifi-bootstrap/src/main/java/org/apache/nifi/bootstrap/util/SecureNiFiConfigUtil.java
##########
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.bootstrap.util;
+
+import org.apache.nifi.security.util.KeyStoreUtils;
+import org.apache.nifi.security.util.StandardTlsConfiguration;
+import org.apache.nifi.security.util.TlsConfiguration;
+import org.apache.nifi.util.NiFiProperties;
+import org.apache.nifi.util.StringUtils;
+import org.bouncycastle.util.IPAddress;
+import org.slf4j.Logger;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.security.GeneralSecurityException;
+import java.time.LocalDate;
+import java.time.temporal.ChronoUnit;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class SecureNiFiConfigUtil {
+
+    private static final int CERT_DURATION_DAYS = 60;
+    public static final String LOCALHOST_IP = "127.0.0.1";
+    private static final String LOCALHOST_NAME = "localhost";
+    public static final String PROPERTY_VALUE_PATTERN = "%s=%s";
+
+    private SecureNiFiConfigUtil() {
+
+    }
+
+    private static boolean fileExists(String filename) {
+        return StringUtils.isNotEmpty(filename) && 
Paths.get(filename).toFile().exists();
+    }
+
+    /**
+     * If HTTPS is enabled (nifi.web.https.port is set), but the keystore file 
specified in nifi.security.keystore
+     * does not exist, this will generate a key pair and self-signed 
certificate, generate the associated keystore
+     * and truststore and write them to disk under the configured filepaths, 
generate a secure random keystore password
+     * and truststore password, and write these to the nifi.properties file.
+     * @param nifiPropertiesFilename The filename of the nifi.properties file
+     * @param cmdLogger The bootstrap logger
+     * @throws IOException can be thrown when writing keystores to disk
+     * @throws RuntimeException indicates a security exception while 
generating keystores
+     */
+    public static void configureSecureNiFiProperties(String 
nifiPropertiesFilename, Logger cmdLogger) throws IOException, RuntimeException, 
GeneralSecurityException {
+        final File propertiesFile = new File(nifiPropertiesFilename);
+        final Properties nifiProperties = loadProperties(propertiesFile);
+
+        if 
(StringUtils.isEmpty(nifiProperties.getProperty(NiFiProperties.WEB_HTTPS_PORT, 
""))) {
+            cmdLogger.debug("No HTTPS configuration detected: skipping Apache 
Nifi certificate generation.");
+            return;
+        }
+
+        String keystorePath = 
nifiProperties.getProperty(NiFiProperties.SECURITY_KEYSTORE, "");
+        String truststorePath = 
nifiProperties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE, "");
+        if (StringUtils.isEmpty(keystorePath) || 
StringUtils.isEmpty(truststorePath)) {
+            cmdLogger.debug("HTTPS is configured, but keystore and truststore 
are not specified.");
+            return;
+        }
+
+        boolean keystoreExists = fileExists(keystorePath);
+        boolean truststoreExists = fileExists(truststorePath);
+
+        if (!keystoreExists && !truststoreExists) {
+            TlsConfiguration tlsConfiguration = null;
+            cmdLogger.info("Generating Self-Signed Certificate: Expires on 
{}", LocalDate.now().plus(CERT_DURATION_DAYS, ChronoUnit.DAYS));
+            try {
+                String[] subjectAlternativeNames = 
getSubjectAlternativeNames(nifiProperties, cmdLogger);
+                tlsConfiguration = 
KeyStoreUtils.createTlsConfigAndNewKeystoreTruststore(StandardTlsConfiguration
+                        .fromNiFiProperties(nifiProperties), 
CERT_DURATION_DAYS, subjectAlternativeNames);
+            } catch (IOException | GeneralSecurityException e) {
+                cmdLogger.error("Self-Signed Certificate Generation Failed", 
e);
+                throw e;
+            }
+
+            // Move over the new stores from temp dir
+            Files.move(Paths.get(tlsConfiguration.getKeystorePath()), 
Paths.get(keystorePath),
+                    StandardCopyOption.REPLACE_EXISTING);
+            Files.move(Paths.get(tlsConfiguration.getTruststorePath()), 
Paths.get(truststorePath),
+                    StandardCopyOption.REPLACE_EXISTING);
+
+            updateProperties(propertiesFile, tlsConfiguration);
+
+            cmdLogger.debug("Successfully generated {} and {}.", keystorePath, 
truststorePath);
+        } else if (!keystoreExists && truststoreExists) {
+            cmdLogger.warn("Truststore file {} already exists.  Apache NiFi 
will not generate keystore and truststore separately.",
+                    truststorePath);
+        } else if (keystoreExists && !truststoreExists) {
+            cmdLogger.warn("Keystore file {} already exists.  Apache NiFi will 
not generate keystore and truststore separately.",
+                    keystorePath);
+        }
+    }
+
+    /**
+     * Attempts to add some reasonable guesses at desired SAN values that can 
be added to the generated
+     * certificate.
+     * @param nifiProperties The nifi.properties
+     * @return A Pair with IP SANs on the left and DNS SANs on the right
+     */
+    private static String[] getSubjectAlternativeNames(Properties 
nifiProperties, Logger cmdLogger) {
+        Set<String> dnsSubjectAlternativeNames = new HashSet<>();
+
+        try {
+            
dnsSubjectAlternativeNames.add(InetAddress.getLocalHost().getHostName());
+        } catch (UnknownHostException e) {
+            cmdLogger.debug("Could not add localhost hostname as certificate 
SAN", e);
+        }
+        addSubjectAlternativeName(nifiProperties, 
NiFiProperties.REMOTE_INPUT_HOST, dnsSubjectAlternativeNames);
+        addSubjectAlternativeName(nifiProperties, 
NiFiProperties.WEB_HTTPS_HOST, dnsSubjectAlternativeNames);
+        addSubjectAlternativeName(nifiProperties, 
NiFiProperties.WEB_PROXY_HOST, dnsSubjectAlternativeNames);
+        addSubjectAlternativeName(nifiProperties, 
NiFiProperties.LOAD_BALANCE_ADDRESS, dnsSubjectAlternativeNames);
+
+        // Not necessary to add as a SAN
+        dnsSubjectAlternativeNames.remove(LOCALHOST_NAME);

Review comment:
       Because CertificateUtils.generateSelfSignedX509Certificate(...) already 
adds the CN as a SAN, so localhost will already be a SAN.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to