[ 
https://issues.apache.org/jira/browse/KAFKA-4701?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16566017#comment-16566017
 ] 

ASF GitHub Bot commented on KAFKA-4701:
---------------------------------------

allenxiang closed pull request #2446: KAFKA-4701: Add dynamic truststore 
manager.
URL: https://github.com/apache/kafka/pull/2446
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git 
a/clients/src/main/java/org/apache/kafka/common/security/ssl/ReloadableX509TrustManager.java
 
b/clients/src/main/java/org/apache/kafka/common/security/ssl/ReloadableX509TrustManager.java
new file mode 100644
index 00000000000..bb33b0fbe63
--- /dev/null
+++ 
b/clients/src/main/java/org/apache/kafka/common/security/ssl/ReloadableX509TrustManager.java
@@ -0,0 +1,166 @@
+/*
+ * 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.kafka.common.security.ssl;
+
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedTrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.net.Socket;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Enumeration;
+
+class ReloadableX509TrustManager extends X509ExtendedTrustManager implements 
X509TrustManager {
+    private static final Logger log = 
LoggerFactory.getLogger(ReloadableX509TrustManager.class);
+
+    private final SecurityStore trustStore;
+    private final TrustManagerFactory tmf;
+    private X509TrustManager trustManager;
+    private long lastReload = 0L;
+
+    private KeyStore trustKeyStore;
+
+    public ReloadableX509TrustManager(SecurityStore trustStore, 
TrustManagerFactory tmf) {
+        this.trustStore = trustStore;
+        this.tmf = tmf;
+    }
+
+    public KeyStore getTrustKeyStore() {
+        return trustKeyStore;
+    }
+
+    @Override
+    public void checkClientTrusted(X509Certificate[] chain, String authType) 
throws CertificateException {
+        reloadTrustManager();
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        trustManager.checkClientTrusted(chain, authType);
+    }
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] chain, String authType) 
throws CertificateException {
+        if (trustManager == null) {
+            reloadTrustManager();
+        }
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        trustManager.checkServerTrusted(chain, authType);
+    }
+
+    @Override
+    public X509Certificate[] getAcceptedIssuers() {
+        reloadTrustManager();
+
+        if (trustManager == null) {
+            return new X509Certificate[0];
+        }
+        return trustManager.getAcceptedIssuers();
+    }
+
+    @Override
+    public void checkClientTrusted(X509Certificate[] x509Certificates, String 
s, Socket socket) throws CertificateException {
+        reloadTrustManager();
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        ((X509ExtendedTrustManager) 
trustManager).checkClientTrusted(x509Certificates, s, socket);
+    }
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] x509Certificates, String 
s, Socket socket) throws CertificateException {
+        if (trustManager == null) {
+            reloadTrustManager();
+        }
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        ((X509ExtendedTrustManager) 
trustManager).checkServerTrusted(x509Certificates, s, socket);
+    }
+
+    @Override
+    public void checkClientTrusted(X509Certificate[] x509Certificates, String 
s, SSLEngine sslEngine) throws CertificateException {
+        reloadTrustManager();
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        ((X509ExtendedTrustManager) 
trustManager).checkClientTrusted(x509Certificates, s, sslEngine);
+    }
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] x509Certificates, String 
s, SSLEngine sslEngine) throws CertificateException {
+        if (trustManager == null) {
+            reloadTrustManager();
+        }
+        if (trustManager == null) {
+            throw new CertificateException("Trust manager not initialized.");
+        }
+        ((X509ExtendedTrustManager) 
trustManager).checkServerTrusted(x509Certificates, s, sslEngine);
+    }
+
+    private void reloadTrustManager() {
+        try {
+            if (trustManager == null || trustStore.getLastModified() >= 
lastReload) {
+                trustKeyStore = trustStore.load();
+
+                Enumeration<String> alias = trustKeyStore.aliases();
+                log.info("Trust manager reloaded.");
+                StringBuilder logMessage = new StringBuilder("List of trusted 
certs: ");
+                if (alias.hasMoreElements()) {
+                    logMessage.append(alias.nextElement());
+                }
+                while (alias.hasMoreElements()) {
+                    logMessage.append(", ").append(alias.nextElement());
+                }
+                log.debug(logMessage.toString());
+
+                tmf.init(trustKeyStore);
+
+                trustManager = null;
+                TrustManager[] tms = tmf.getTrustManagers();
+                for (int i = 0; i < tms.length; i++) {
+                    if (tms[i] instanceof X509TrustManager) {
+                        trustManager = (X509TrustManager) tms[i];
+                    }
+                }
+
+                if (trustManager == null) {
+                    throw new NoSuchAlgorithmException("No X509TrustManager in 
TrustManagerFactory");
+                }
+
+                lastReload = System.currentTimeMillis();
+                // getLastModified() returns timestamp rounded to 1000 ms. Do 
the same here for lastReload.
+                lastReload -= lastReload % 1000;
+            }
+        } catch (GeneralSecurityException gsEx) {
+            log.error("Failed to reload trust manager due to security 
exception. {}", gsEx.getMessage());
+        } catch (IOException ioEx) {
+            log.error("Failed to reload trust manager due to IO exception. 
{}", ioEx.getMessage());
+        }
+    }
+}
diff --git 
a/clients/src/main/java/org/apache/kafka/common/security/ssl/SecurityStore.java 
b/clients/src/main/java/org/apache/kafka/common/security/ssl/SecurityStore.java
new file mode 100644
index 00000000000..a103007c42f
--- /dev/null
+++ 
b/clients/src/main/java/org/apache/kafka/common/security/ssl/SecurityStore.java
@@ -0,0 +1,61 @@
+/*
+ * 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.kafka.common.security.ssl;
+
+import org.apache.kafka.common.config.types.Password;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+
+class SecurityStore {
+    private final String type;
+    private final String path;
+
+    private final Password password;
+
+    SecurityStore(String type, String path, Password password) {
+        this.type = type == null ? KeyStore.getDefaultType() : type;
+        this.path = path;
+        this.password = password;
+    }
+
+    Password getPassword() {
+        return password;
+    }
+
+    KeyStore load() throws GeneralSecurityException, IOException {
+        FileInputStream in = null;
+        try {
+            KeyStore ks = KeyStore.getInstance(type);
+            in = new FileInputStream(path);
+            // If a password is not set access to the truststore is still 
available, but integrity checking is disabled.
+            char[] passwordChars = password != null ? 
password.value().toCharArray() : null;
+            ks.load(in, passwordChars);
+            return ks;
+        } finally {
+            if (in != null) in.close();
+        }
+    }
+
+    long getLastModified() {
+        File storeFile = new File(path);
+        return storeFile.lastModified();
+    }
+}
diff --git 
a/clients/src/main/java/org/apache/kafka/common/security/ssl/SslFactory.java 
b/clients/src/main/java/org/apache/kafka/common/security/ssl/SslFactory.java
index 65724883172..cdbd70bcad7 100644
--- a/clients/src/main/java/org/apache/kafka/common/security/ssl/SslFactory.java
+++ b/clients/src/main/java/org/apache/kafka/common/security/ssl/SslFactory.java
@@ -19,26 +19,25 @@
 import org.apache.kafka.common.Configurable;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.config.SslConfigs;
-import org.apache.kafka.common.network.Mode;
 import org.apache.kafka.common.config.types.Password;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.util.List;
-import java.util.Map;
+import org.apache.kafka.common.network.Mode;
 
 import javax.net.ssl.KeyManager;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLEngine;
 import javax.net.ssl.SSLParameters;
+import javax.net.ssl.TrustManager;
 import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.util.List;
+import java.util.Map;
 
 public class SslFactory implements Configurable {
-
     private final Mode mode;
     private final String clientAuthConfigOverride;
 
@@ -135,7 +134,7 @@ private SSLContext createSSLContext() throws 
GeneralSecurityException, IOExcepti
             String kmfAlgorithm = this.kmfAlgorithm != null ? 
this.kmfAlgorithm : KeyManagerFactory.getDefaultAlgorithm();
             KeyManagerFactory kmf = 
KeyManagerFactory.getInstance(kmfAlgorithm);
             KeyStore ks = keystore.load();
-            Password keyPassword = this.keyPassword != null ? this.keyPassword 
: keystore.password;
+            Password keyPassword = this.keyPassword != null ? this.keyPassword 
: keystore.getPassword();
             kmf.init(ks, keyPassword.value().toCharArray());
             keyManagers = kmf.getKeyManagers();
         }
@@ -145,7 +144,20 @@ private SSLContext createSSLContext() throws 
GeneralSecurityException, IOExcepti
         KeyStore ts = truststore == null ? null : truststore.load();
         tmf.init(ts);
 
-        sslContext.init(keyManagers, tmf.getTrustManagers(), 
this.secureRandomImplementation);
+        if ((wantClientAuth || needClientAuth) && truststore != null && mode 
== Mode.SERVER) {
+            TrustManager[] trustManagers = tmf.getTrustManagers();
+            TrustManager reloadableTrustManager = new 
ReloadableX509TrustManager(truststore, tmf);
+
+            for (int i = 0; i < trustManagers.length; i++) {
+                if (trustManagers[i] instanceof X509TrustManager) {
+                    trustManagers[i] = reloadableTrustManager;
+                }
+            }
+
+            sslContext.init(keyManagers, trustManagers, 
this.secureRandomImplementation);
+        } else {
+            sslContext.init(keyManagers, tmf.getTrustManagers(), 
this.secureRandomImplementation);
+        }
         return sslContext;
     }
 
@@ -154,8 +166,6 @@ public SSLEngine createSslEngine(String peerHost, int 
peerPort) {
         if (cipherSuites != null) 
sslEngine.setEnabledCipherSuites(cipherSuites);
         if (enabledProtocols != null) 
sslEngine.setEnabledProtocols(enabledProtocols);
 
-        // SSLParameters#setEndpointIdentificationAlgorithm enables endpoint 
validation
-        // only in client mode. Hence, validation is enabled only for clients.
         if (mode == Mode.SERVER) {
             sslEngine.setUseClientMode(false);
             if (needClientAuth)
@@ -197,31 +207,4 @@ private void createTruststore(String type, String path, 
Password password) {
             this.truststore = new SecurityStore(type, path, password);
         }
     }
-
-    private static class SecurityStore {
-        private final String type;
-        private final String path;
-        private final Password password;
-
-        private SecurityStore(String type, String path, Password password) {
-            this.type = type == null ? KeyStore.getDefaultType() : type;
-            this.path = path;
-            this.password = password;
-        }
-
-        private KeyStore load() throws GeneralSecurityException, IOException {
-            FileInputStream in = null;
-            try {
-                KeyStore ks = KeyStore.getInstance(type);
-                in = new FileInputStream(path);
-                // If a password is not set access to the truststore is still 
available, but integrity checking is disabled.
-                char[] passwordChars = password != null ? 
password.value().toCharArray() : null;
-                ks.load(in, passwordChars);
-                return ks;
-            } finally {
-                if (in != null) in.close();
-            }
-        }
-    }
-
 }
diff --git 
a/clients/src/test/java/org/apache/kafka/common/security/ssl/SslFactoryTest.java
 
b/clients/src/test/java/org/apache/kafka/common/security/ssl/SslFactoryTest.java
index 5546a55123f..6967ce182db 100644
--- 
a/clients/src/test/java/org/apache/kafka/common/security/ssl/SslFactoryTest.java
+++ 
b/clients/src/test/java/org/apache/kafka/common/security/ssl/SslFactoryTest.java
@@ -16,19 +16,24 @@
  */
 package org.apache.kafka.common.security.ssl;
 
-import java.io.File;
-import java.util.Map;
-
-import javax.net.ssl.SSLEngine;
-
 import org.apache.kafka.common.config.SslConfigs;
-import org.apache.kafka.test.TestSslUtils;
+import org.apache.kafka.common.config.types.Password;
 import org.apache.kafka.common.network.Mode;
+import org.apache.kafka.test.TestSslUtils;
 import org.junit.Test;
 
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManagerFactory;
+import java.io.File;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Map;
+
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -76,4 +81,64 @@ public void testClientMode() throws Exception {
         assertTrue(engine.getUseClientMode());
     }
 
+    @Test
+    public void testReloadableX509TrustManager() throws Exception {
+        Map<String, X509Certificate> certs = new HashMap<>();
+        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
+        TrustManagerFactory tmf = 
TrustManagerFactory.getInstance(tmfAlgorithm);
+        File trustStoreFile = File.createTempFile("truststore", ".jks");
+        Password trustStorePassword = new Password("TrustStorePassword");
+        KeyStore ts = createTruststore(1, trustStoreFile, trustStorePassword);
+
+        tmf.init(ts);
+        SecurityStore securityStore = new SecurityStore("jks", 
trustStoreFile.getPath(), trustStorePassword);
+
+        ReloadableX509TrustManager reloadableX509TrustManager = new 
ReloadableX509TrustManager(securityStore, tmf);
+        reloadableX509TrustManager.getAcceptedIssuers();
+
+        // One alias in truststore
+        assertEquals(1, reloadableX509TrustManager.getTrustKeyStore().size());
+
+        createTruststore(2, trustStoreFile, trustStorePassword);
+        reloadableX509TrustManager.getAcceptedIssuers();
+        // Two aliases in truststore, should have reloaded.
+        assertEquals(2, reloadableX509TrustManager.getTrustKeyStore().size());
+    }
+
+    @Test
+    public void testTrustManagerWithIOException() throws Exception {
+        Map<String, X509Certificate> certs = new HashMap<>();
+        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
+        TrustManagerFactory tmf = 
TrustManagerFactory.getInstance(tmfAlgorithm);
+        File trustStoreFile = File.createTempFile("truststore", ".jks");
+        Password trustStorePassword = new Password("TrustStorePassword");
+        KeyStore ts = createTruststore(1, trustStoreFile, trustStorePassword);
+
+        tmf.init(ts);
+        SecurityStore securityStore = new SecurityStore("jks", 
trustStoreFile.getPath(), trustStorePassword);
+
+        ReloadableX509TrustManager reloadableX509TrustManager = new 
ReloadableX509TrustManager(securityStore, tmf);
+
+        trustStoreFile.delete();
+        // ReloadableX509TrustManager should handle IO exception.
+        reloadableX509TrustManager.getAcceptedIssuers();
+
+        trustStoreFile.createNewFile();
+        createTruststore(1, trustStoreFile, trustStorePassword);
+        reloadableX509TrustManager.getAcceptedIssuers();
+        // Two aliases in truststore, should have reloaded.
+        assertEquals(1, reloadableX509TrustManager.getTrustKeyStore().size());
+    }
+
+    private KeyStore createTruststore(int numberOfKeypairs, File 
trustStoreFile, Password trustStorePassword) throws Exception {
+        Map<String, X509Certificate> certs = new HashMap<>();
+        for (int i = 0; i < numberOfKeypairs; i++) {
+            KeyPair cKP = TestSslUtils.generateKeyPair("RSA");
+            X509Certificate cCert = 
TestSslUtils.generateCertificate("CN=localhost, O=client " + i, cKP, 30, 
"SHA1withRSA");
+            certs.put("client" + i, cCert);
+        }
+        KeyStore ts = TestSslUtils.createTrustStore(trustStoreFile.getPath(), 
trustStorePassword, certs);
+        trustStoreFile.deleteOnExit();
+        return ts;
+    }
 }
diff --git a/clients/src/test/java/org/apache/kafka/test/TestSslUtils.java 
b/clients/src/test/java/org/apache/kafka/test/TestSslUtils.java
index 6c057d0ef31..4c16dfe896f 100644
--- a/clients/src/test/java/org/apache/kafka/test/TestSslUtils.java
+++ b/clients/src/test/java/org/apache/kafka/test/TestSslUtils.java
@@ -17,31 +17,8 @@
 package org.apache.kafka.test;
 
 import org.apache.kafka.common.config.SslConfigs;
-import org.apache.kafka.common.network.Mode;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.EOFException;
-import java.math.BigInteger;
-import java.net.InetAddress;
-
-import javax.net.ssl.TrustManagerFactory;
-
-import java.security.GeneralSecurityException;
-import java.security.Key;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.Security;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
 import org.apache.kafka.common.config.types.Password;
+import org.apache.kafka.common.network.Mode;
 import org.bouncycastle.asn1.DEROctetString;
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
@@ -60,11 +37,30 @@
 import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
 import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
 
+import javax.net.ssl.TrustManagerFactory;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
-import java.util.Map;
 import java.util.List;
-import java.util.ArrayList;
+import java.util.Map;
 
 public class TestSslUtils {
 
@@ -134,10 +130,11 @@ public static void createKeyStore(String filename,
         saveKeyStore(ks, filename, password);
     }
 
-    public static <T extends Certificate> void createTrustStore(
+    public static <T extends Certificate> KeyStore createTrustStore(
             String filename, Password password, Map<String, T> certs) throws 
GeneralSecurityException, IOException {
         KeyStore ks = KeyStore.getInstance("JKS");
-        try (FileInputStream in = new FileInputStream(filename)) {
+        try {
+            FileInputStream in = new FileInputStream(filename);
             ks.load(in, password.value().toCharArray());
         } catch (EOFException e) {
             ks = createEmptyKeyStore();
@@ -146,6 +143,7 @@ public static void createKeyStore(String filename,
             ks.setCertificateEntry(cert.getKey(), cert.getValue());
         }
         saveKeyStore(ks, filename, password);
+        return ks;
     }
 
     private static Map<String, Object> createSslConfig(Mode mode, File 
keyStoreFile, Password password, Password keyPassword,


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on 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


> Allow kafka brokers to dynamically reload truststore without restarting.
> ------------------------------------------------------------------------
>
>                 Key: KAFKA-4701
>                 URL: https://issues.apache.org/jira/browse/KAFKA-4701
>             Project: Kafka
>          Issue Type: Improvement
>          Components: security
>            Reporter: Allen Xiang
>            Priority: Major
>              Labels: security
>             Fix For: 2.1.0
>
>
> Right now in order to add SSL clients(update broker truststores), a rolling 
> restart of all brokers is required. This is very time consuming and 
> unnecessary. A dynamic truststore manager is needed to reload truststore from 
> file system without restarting brokers.



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Reply via email to