Elffuss BraidHub

kikocis/java-driver public

JAVA-841, JAVA-948: Refactor SSLOptions API.
Changeset99e6e7949d0ec8adad0117bb0ab0641f81de83661ad73a34a6fef3095a082d3c
Authorolim7t <omichallat+github@gmail.com> · 2015-10-29 17:28 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-13 12:09 +01:00
Parents485402c1885d

Browse the files at this changeset

14 files changed

modified changelog/README.md +2 −0
@@ -10,6 +10,8 @@
1010 - [bug] JAVA-972: TypeCodec.parse() implementations should be case insensitive when checking for keyword NULL.
1111 - [bug] JAVA-971: Make type codecs invariant.
1212 - [bug] JAVA-986: Update documentation links to reference 3.0.
13+- [improvement] JAVA-841: Refactor SSLOptions API.
14+- [improvement] JAVA-948: Don't limit cipher suites by default.
1315
1416 Merged from 2.1 branch:
1517
modified driver-core/pom.xml +15 −0
@@ -139,6 +139,14 @@
139139 <scope>test</scope>
140140 </dependency>
141141
142+ <dependency>
143+ <groupId>io.netty</groupId>
144+ <artifactId>netty-tcnative</artifactId>
145+ <version>1.1.33.Fork10</version>
146+ <classifier>${os.detected.classifier}</classifier>
147+ <scope>test</scope>
148+ </dependency>
149+
142150 </dependencies>
143151
144152 <build>
@@ -291,6 +299,13 @@
291299 </plugin>
292300 </plugins>
293301 </pluginManagement>
302+ <extensions>
303+ <extension>
304+ <groupId>kr.motd.maven</groupId>
305+ <artifactId>os-maven-plugin</artifactId>
306+ <version>1.4.1.Final</version>
307+ </extension>
308+ </extensions>
294309 </build>
295310
296311 <profiles>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +4 −3
@@ -1110,8 +1110,9 @@
11101110 /**
11111111 * Enables the use of SSL for the created {@code Cluster}.
11121112 * <p>
1113- * Calling this method will use default SSL options (see {@link SSLOptions#SSLOptions()}).
1114- * This is thus a shortcut for {@code withSSL(new SSLOptions())}.
1113+ * Calling this method will use the JDK-based implementation with the default options
1114+ * (see {@link JdkSSLOptions.Builder}).
1115+ * This is thus a shortcut for {@code withSSL(JdkSSLOptions.builder().build())}.
11151116 * <p>
11161117 * Note that if SSL is enabled, the driver will not connect to any
11171118 * Cassandra nodes that doesn't have SSL enabled and it is strongly
@@ -1121,7 +1122,7 @@
11211122 * @return this builder.
11221123 */
11231124 public Builder withSSL() {
1124- this.sslOptions = new SSLOptions();
1125+ this.sslOptions = JdkSSLOptions.builder().build();
11251126 return this;
11261127 }
11271128
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +1 −7
@@ -35,14 +35,12 @@
3535 import io.netty.channel.group.ChannelGroup;
3636 import io.netty.channel.group.DefaultChannelGroup;
3737 import io.netty.channel.socket.SocketChannel;
38-import io.netty.handler.ssl.SslHandler;
3938 import io.netty.handler.timeout.IdleStateEvent;
4039 import io.netty.handler.timeout.IdleStateHandler;
4140 import io.netty.util.Timeout;
4241 import io.netty.util.Timer;
4342 import io.netty.util.TimerTask;
4443 import io.netty.util.concurrent.GlobalEventExecutor;
45-import javax.net.ssl.SSLEngine;
4644 import org.slf4j.Logger;
4745 import org.slf4j.LoggerFactory;
4846
@@ -1299,11 +1297,7 @@
12991297 ChannelPipeline pipeline = channel.pipeline();
13001298
13011299 if (sslOptions != null) {
1302- SSLEngine engine = sslOptions.context.createSSLEngine();
1303- engine.setUseClientMode(true);
1304- engine.setEnabledCipherSuites(sslOptions.cipherSuites);
1305- SslHandler handler = new SslHandler(engine);
1306- pipeline.addLast("ssl", handler);
1300+ pipeline.addLast("ssl", sslOptions.newSSLHandler(channel));
13071301 }
13081302
13091303 // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
added driver-core/src/main/java/com/datastax/driver/core/JdkSSLOptions.java +131 −0
@@ -0,0 +1,131 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.security.NoSuchAlgorithmException;
19+
20+import io.netty.channel.socket.SocketChannel;
21+import io.netty.handler.ssl.SslHandler;
22+import javax.net.ssl.SSLContext;
23+import javax.net.ssl.SSLEngine;
24+
25+/**
26+ * {@link SSLOptions} implementation based on built-in JDK classes.
27+ */
28+public class JdkSSLOptions implements SSLOptions {
29+
30+ /**
31+ * Creates a builder to create a new instance.
32+ *
33+ * @return the builder.
34+ */
35+ public static Builder builder() {
36+ return new Builder();
37+ }
38+
39+ private final SSLContext context;
40+ private final String[] cipherSuites;
41+
42+ /**
43+ * Creates a new instance.
44+ *
45+ * @param context the SSL context.
46+ * @param cipherSuites the cipher suites to use.
47+ */
48+ protected JdkSSLOptions(SSLContext context, String[] cipherSuites) {
49+ this.context = (context == null) ? makeDefaultContext() : context;
50+ this.cipherSuites = cipherSuites;
51+ }
52+
53+ @Override
54+ public SslHandler newSSLHandler(SocketChannel channel) {
55+ SSLEngine engine = newSSLEngine(channel);
56+ return new SslHandler(engine);
57+ }
58+
59+ /**
60+ * Creates an SSL engine each time a connection is established.
61+ *
62+ * <p>
63+ * You might want to override this if you need to fine-tune the engine's configuration
64+ * (for example enabling hostname verification).
65+ *
66+ * @param channel the Netty channel for that connection.
67+ * @return the engine.
68+ */
69+ protected SSLEngine newSSLEngine(SocketChannel channel) {
70+ SSLEngine engine = context.createSSLEngine();
71+ engine.setUseClientMode(true);
72+ if (cipherSuites != null)
73+ engine.setEnabledCipherSuites(cipherSuites);
74+ return engine;
75+ }
76+
77+ private static SSLContext makeDefaultContext() throws IllegalStateException {
78+ try {
79+ return SSLContext.getDefault();
80+ } catch (NoSuchAlgorithmException e) {
81+ throw new IllegalStateException("Cannot initialize SSL Context", e);
82+ }
83+ }
84+
85+ /**
86+ * Helper class to build JDK-based SSL options.
87+ */
88+ public static class Builder {
89+ private SSLContext context;
90+ private String[] cipherSuites;
91+
92+ /**
93+ * Set the SSL context to use.
94+ * <p>
95+ * If this method isn't called, a context with the default options will be used,
96+ * and you can use the default
97+ * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization">JSSE System properties</a>
98+ * to customize its behavior. This may in particular involve
99+ * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore">creating a simple keyStore and trustStore</a>.
100+ *
101+ * @param context the SSL context.
102+ * @return this builder.
103+ */
104+ public Builder withSSLContext(SSLContext context) {
105+ this.context = context;
106+ return this;
107+ }
108+
109+ /**
110+ * Set the cipher suites to use.
111+ * <p>
112+ * If this method isn't called, the default is to present all the eligible client ciphers to the server.
113+ *
114+ * @param cipherSuites the cipher suites to use.
115+ * @return this builder.
116+ */
117+ public Builder withCipherSuites(String[] cipherSuites) {
118+ this.cipherSuites = cipherSuites;
119+ return this;
120+ }
121+
122+ /**
123+ * Builds a new instance based on the parameters provided to this builder.
124+ *
125+ * @return the new instance.
126+ */
127+ public JdkSSLOptions build() {
128+ return new JdkSSLOptions(context, cipherSuites);
129+ }
130+ }
131+}
added driver-core/src/main/java/com/datastax/driver/core/NettySSLOptions.java +43 −0
@@ -0,0 +1,43 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import io.netty.channel.socket.SocketChannel;
19+import io.netty.handler.ssl.SslContext;
20+import io.netty.handler.ssl.SslHandler;
21+
22+/**
23+ * {@link SSLOptions} implementation based on Netty's SSL context.
24+ * <p>
25+ * Netty has the ability to use OpenSSL if available, instead of the JDK's built-in engine. This yields better performance.
26+ */
27+public class NettySSLOptions implements SSLOptions {
28+ private final SslContext context;
29+
30+ /**
31+ * Create a new instance from a given context.
32+ *
33+ * @param context the Netty context. {@code SslContextBuilder.forClient()} provides a fluent API to build it.
34+ */
35+ public NettySSLOptions(SslContext context) {
36+ this.context = context;
37+ }
38+
39+ @Override
40+ public SslHandler newSSLHandler(SocketChannel channel) {
41+ return context.newHandler(channel.alloc());
42+ }
43+}
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +15 −42
@@ -15,55 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import javax.net.ssl.SSLContext;
19-import java.security.KeyManagementException;
20-import java.security.NoSuchAlgorithmException;
18+import io.netty.channel.socket.SocketChannel;
19+import io.netty.handler.ssl.SslHandler;
2120
2221 /**
23- * Options to provide to enable SSL connections.
22+ * Defines how the driver configures SSL connections.
23+ *
24+ * @see JdkSSLOptions
25+ * @see NettySSLOptions
2426 */
25-public class SSLOptions {
27+public interface SSLOptions {
2628
2729 /**
28- * The default SSL cipher suites.
29- */
30- public static final String[] DEFAULT_SSL_CIPHER_SUITES = { "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA" };
31-
32- final SSLContext context;
33- final String[] cipherSuites;
34-
35- /**
36- * Creates default SSL options.
30+ * Creates a new SSL handler for the given Netty channel.
3731 * <p>
38- * The resulting options will use the default JSSE options, and you can use the default
39- * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization">JSSE System properties</a>
40- * to customize it's behavior. This may in particular involve
41- * <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore">creating a simple keyStore and trustStore</a>.
32+ * This gets called each time the driver opens a new connection to a Cassandra host. The newly created handler will be added
33+ * to the channel's pipeline to provide SSL support for the connection.
4234 * <p>
43- * The cipher suites used by this default instance are the one defined by
44- * {@code DEFAULT_SSL_CIPHER_SUITES} and match the default cipher suites
45- * supported by Cassandra server side.
46- */
47- public SSLOptions() {
48- this(makeDefaultContext(), DEFAULT_SSL_CIPHER_SUITES);
49- }
50-
51- /**
52- * Creates SSL options that uses the provided SSL context and cipher suites.
35+ * You don't necessarily need to implement this method directly; see the provided implementations: {@link JdkSSLOptions} and
36+ * {@link NettySSLOptions}.
5337 *
54- * @param context the {@code SSLContext} to use.
55- * @param cipherSuites the cipher suites to use.
38+ * @param channel the channel.
39+ * @return the handler.
5640 */
57- public SSLOptions(SSLContext context, String[] cipherSuites) {
58- this.context = context;
59- this.cipherSuites = cipherSuites;
60- }
61-
62- private static SSLContext makeDefaultContext() throws IllegalStateException {
63- try {
64- return SSLContext.getDefault();
65- } catch (NoSuchAlgorithmException e) {
66- throw new IllegalStateException("Cannot initialize SSL Context", e);
67- }
68- }
41+ SslHandler newSSLHandler(SocketChannel channel);
6942 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +7 −21
@@ -60,12 +60,12 @@
6060 public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
6161 public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
6262
63- public static final File DEFAULT_CLIENT_TRUSTSTORE_FILE = createTempStore(DEFAULT_CLIENT_TRUSTSTORE_PATH);
64-
6563 public static final String DEFAULT_CLIENT_KEYSTORE_PASSWORD = "cassandra1sfun";
6664 public static final String DEFAULT_CLIENT_KEYSTORE_PATH = "/client.keystore";
6765
68- public static final File DEFAULT_CLIENT_KEYSTORE_FILE = createTempStore(DEFAULT_CLIENT_KEYSTORE_PATH);
66+ // Contain the same keypair as the client keystore, but in format usable by OpenSSL
67+ public static final File DEFAULT_CLIENT_PRIVATE_KEY_FILE = createTempStore("/client.key");
68+ public static final File DEFAULT_CLIENT_CERT_CHAIN_FILE = createTempStore("/client.crt");
6969
7070 public static final String DEFAULT_SERVER_TRUSTSTORE_PASSWORD = "cassandra1sfun";
7171 public static final String DEFAULT_SERVER_TRUSTSTORE_PATH = "/server.truststore";
@@ -492,9 +492,7 @@
492492
493493 builder = configure(builder);
494494
495- cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
496- .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
497- .build();
495+ cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
498496 session = cluster.connect();
499497 keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
500498 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
@@ -522,24 +520,12 @@
522520
523521 private void clearSimpleKeyspace() {
524522 if(keyspace != null) {
525- logger.debug("Removing keyspace {}.", keyspace);
526- // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and
527- // tables being slow, particularly in a CI environment.
523+ // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables.
524+ // This should be more than enough although some tests create many tables, so dropping a keyspace
525+ // could take as long as 12 seconds on restricted hardware.
528526 int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
529527 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
530528 try {
531- KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace);
532- if (ksm != null) {
533- // drop each table individually as this seems to be more dependable than dropping
534- // the entire keyspace at once if it has many tables.
535- if(ksm.getTables().size() > 10) {
536- for (TableMetadata table : ksm.getTables()) {
537- logger.debug("Dropping table {}.{}.", keyspace, table.getName());
538- session.execute("DROP TABLE " + keyspace + "." + table.getName());
539- }
540- }
541- }
542- logger.debug("Dropping keyspace {}.", keyspace);
543529 session.execute("DROP KEYSPACE " + keyspace);
544530 } finally {
545531 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +14 −30
@@ -15,15 +15,21 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.base.Optional;
18+import org.testng.annotations.DataProvider;
1919 import org.testng.annotations.Test;
2020
2121 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2222
23-import static com.datastax.driver.core.CCMBridge.*;
23+import static com.datastax.driver.core.SSLTestBase.SslImplementation.JDK;
24+import static com.datastax.driver.core.SSLTestBase.SslImplementation.NETTY_OPENSSL;
2425
2526 public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
2627
28+ @DataProvider(name="sslImplementation")
29+ public static Object[][] sslImplementation() {
30+ return new Object[][]{ { JDK }, { NETTY_OPENSSL } };
31+ }
32+
2733 public SSLAuthenticatedEncryptionTest() {
2834 super(true);
2935 }
@@ -38,9 +44,9 @@
3844 * @test_category connection:ssl, authentication
3945 * @expected_result Connection can be established to a cassandra node using SSL that requires client auth.
4046 */
41- @Test(groups="short")
42- public void should_connect_with_ssl_with_client_auth_and_node_requires_auth() throws Exception {
43- connectWithSSLOptions(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
47+ @Test(groups="short", dataProvider = "sslImplementation")
48+ public void should_connect_with_ssl_with_client_auth_and_node_requires_auth(SslImplementation sslImplementation) throws Exception {
49+ connectWithSSLOptions(getSSLOptions(sslImplementation, true, true));
4450 }
4551
4652
@@ -54,30 +60,8 @@
5460 * @test_category connection:ssl, authentication
5561 * @expected_result Connection is not established.
5662 */
57- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
58- public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception {
59- connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
60- }
61-
62- /**
63- * <p>
64- * Validates that SSL connectivity can be configured via the standard javax.net.ssl System properties.
65- * </p>
66- *
67- * @test_category connection:ssl, authentication
68- * @expected_result Connection can be established.
69- */
70- @Test(groups="short")
71- public void should_use_system_properties_with_default_ssl_options() throws Exception {
72- try {
73- System.setProperty("javax.net.ssl.keyStore", DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath());
74- System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD);
75- System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
76- System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
77-
78- connectWithSSL();
79- } finally {
80- clearSystemProperties();
81- }
63+ @Test(groups="short", dataProvider = "sslImplementation", expectedExceptions={NoHostAvailableException.class})
64+ public void should_not_connect_without_client_auth_but_node_requires_auth(SslImplementation sslImplementation) throws Exception {
65+ connectWithSSLOptions(getSSLOptions(sslImplementation, false, true));
8266 }
8367 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +17 −31
@@ -17,16 +17,22 @@
1717
1818 import java.util.concurrent.TimeUnit;
1919
20-import com.google.common.base.Optional;
20+import org.testng.annotations.DataProvider;
2121 import org.testng.annotations.Test;
2222
2323 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2424
2525 import static com.datastax.driver.core.Assertions.assertThat;
26-import static com.datastax.driver.core.CCMBridge.*;
26+import static com.datastax.driver.core.SSLTestBase.SslImplementation.JDK;
27+import static com.datastax.driver.core.SSLTestBase.SslImplementation.NETTY_OPENSSL;
2728
2829 public class SSLEncryptionTest extends SSLTestBase {
2930
31+ @DataProvider(name="sslImplementation")
32+ public static Object[][] sslImplementation() {
33+ return new Object[][]{ { JDK }, { NETTY_OPENSSL } };
34+ }
35+
3036 public SSLEncryptionTest() {
3137 super(false);
3238 }
@@ -40,9 +46,9 @@
4046 * @test_category connection:ssl
4147 * @expected_result Connection can be established to a cassandra node using SSL.
4248 */
43- @Test(groups="short")
44- public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth() throws Exception {
45- connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
49+ @Test(groups="short", dataProvider = "sslImplementation")
50+ public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth(SslImplementation sslImplementation) throws Exception {
51+ connectWithSSLOptions(getSSLOptions(sslImplementation, false, true));
4652 }
4753
4854 /**
@@ -54,9 +60,9 @@
5460 * @test_category connection:ssl
5561 * @expected_result Connection can not be established to a cassandra node using SSL with an untrusted cert.
5662 */
57- @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
58- public void should_not_connect_with_ssl_without_trusting_server_cert() throws Exception {
59- connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.<String>absent()));
63+ @Test(groups="short", dataProvider = "sslImplementation", expectedExceptions={NoHostAvailableException.class})
64+ public void should_not_connect_with_ssl_without_trusting_server_cert(SslImplementation sslImplementation) throws Exception {
65+ connectWithSSLOptions(getSSLOptions(sslImplementation, false, false));
6066 }
6167
6268 /**
@@ -97,13 +103,13 @@
97103 * @test_category connection:ssl
98104 * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
99105 */
100- @Test(groups="long")
101- public void should_reconnect_with_ssl_on_node_up() throws Exception {
106+ @Test(groups="long", dataProvider = "sslImplementation")
107+ public void should_reconnect_with_ssl_on_node_up(SslImplementation sslImplementation) throws Exception {
102108 Cluster cluster = null;
103109 try {
104110 cluster = Cluster.builder()
105111 .addContactPoint(CCMBridge.IP_PREFIX + '1')
106- .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
112+ .withSSL(getSSLOptions(sslImplementation, true, true))
107113 .build();
108114
109115 cluster.connect();
@@ -117,24 +123,4 @@
117123 cluster.close();
118124 }
119125 }
120-
121- /**
122- * <p>
123- * Validates that SSL connectivity can be configured via the standard javax.net.ssl System properties.
124- * </p>
125- *
126- * @test_category connection:ssl
127- * @expected_result Connection can be established.
128- */
129- @Test(groups="short")
130- public void should_use_system_properties_with_default_ssl_options() throws Exception {
131- try {
132- System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath());
133- System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD);
134-
135- connectWithSSL();
136- } finally {
137- clearSystemProperties();
138- }
139- }
140126 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +47 −55
@@ -18,17 +18,17 @@
1818 import java.security.KeyStore;
1919 import java.security.SecureRandom;
2020
21-import com.google.common.base.Optional;
21+import io.netty.handler.ssl.SslContextBuilder;
2222 import javax.net.ssl.KeyManagerFactory;
2323 import javax.net.ssl.SSLContext;
2424 import javax.net.ssl.TrustManagerFactory;
2525 import org.testng.annotations.AfterClass;
2626 import org.testng.annotations.BeforeClass;
2727
28-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE;
29-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
30-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE;
31-import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
28+import static io.netty.handler.ssl.SslProvider.OPENSSL;
29+import static org.assertj.core.api.Assertions.fail;
30+
31+
3232 public abstract class SSLTestBase {
3333
3434 private final boolean requireClientAuth;
@@ -76,69 +76,61 @@
7676 }
7777 }
7878
79- /**
80- * <p>
81- * Attempts to connect to a cassandra cluster with using {@link Cluster.Builder#withSSL} with no
82- * provided {@link SSLOptions} and then closes the created {@link Cluster} instance.
83- * </p>
84- *
85- * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
86- * raised here if connection cannot be established.
87- */
88- protected void connectWithSSL() throws Exception {
89- Cluster cluster = null;
90- try {
91- cluster = Cluster.builder()
92- .addContactPoint(CCMBridge.IP_PREFIX + '1')
93- .withSSL()
94- .build();
95-
96- cluster.connect();
97- } finally {
98- if (cluster != null)
99- cluster.close();
100- }
101- }
102-
103- /**
104- * Clears all System properties associated with SSL key and trust stores.
105- */
106- protected void clearSystemProperties() {
107- System.clearProperty("javax.net.ssl.keyStore");
108- System.clearProperty("javax.net.ssl.keyStorePassword");
109- System.clearProperty("javax.net.ssl.trustStore");
110- System.clearProperty("javax.net.ssl.trustStorePassword");
111- }
79+ enum SslImplementation { JDK, NETTY_OPENSSL}
11280
11381 /**
114- * @param keyStorePath Path to keystore, if absent is not used.
115- * @param trustStorePath Path to truststore, if absent is not used.
116- * @return {@link com.datastax.driver.core.SSLOptions} with the given keystore and truststore path's for
82+ * @param sslImplementation the SSL implementation to use
83+ * @param clientAuth whether the client should authenticate
84+ * @param trustingServer whether the client should trust the server's certificate
85+ * @return {@link com.datastax.driver.core.SSLOptions} with the given configuration for
11786 * server certificate validation and client certificate authentication.
11887 */
119- public SSLOptions getSSLOptions(Optional<String> keyStorePath, Optional<String> trustStorePath) throws Exception {
88+ public SSLOptions getSSLOptions(SslImplementation sslImplementation, boolean clientAuth, boolean trustingServer) throws Exception {
12089
12190 TrustManagerFactory tmf = null;
122- if(trustStorePath.isPresent()) {
91+ if (trustingServer) {
12392 KeyStore ks = KeyStore.getInstance("JKS");
124- ks.load(this.getClass().getResourceAsStream(trustStorePath.get()), DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
93+ ks.load(
94+ this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH),
95+ CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
12596
12697 tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
12798 tmf.init(ks);
12899 }
129100
130- KeyManagerFactory kmf = null;
131- if(keyStorePath.isPresent()) {
132- KeyStore ks = KeyStore.getInstance("JKS");
133- ks.load(this.getClass().getResourceAsStream(keyStorePath.get()), DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
134101
135- kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
136- kmf.init(ks, DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
102+ switch (sslImplementation) {
103+ case JDK:
104+ KeyManagerFactory kmf = null;
105+ if (clientAuth) {
106+ KeyStore ks = KeyStore.getInstance("JKS");
107+ ks.load(
108+ this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH),
109+ CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
110+
111+ kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
112+ kmf.init(ks, CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
113+ }
114+
115+ SSLContext sslContext = SSLContext.getInstance("TLS");
116+ sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
117+
118+ return JdkSSLOptions.builder().withSSLContext(sslContext).build();
119+
120+ case NETTY_OPENSSL:
121+ SslContextBuilder builder = SslContextBuilder
122+ .forClient()
123+ .sslProvider(OPENSSL)
124+ .trustManager(tmf);
125+
126+ if (clientAuth) {
127+ builder.keyManager(CCMBridge.DEFAULT_CLIENT_CERT_CHAIN_FILE, CCMBridge.DEFAULT_CLIENT_PRIVATE_KEY_FILE);
128+ }
129+
130+ return new NettySSLOptions(builder.build());
131+ default:
132+ fail("Unsupported SSL implementation: " + sslImplementation);
133+ return null;
137134 }
138-
139- SSLContext sslContext = SSLContext.getInstance("TLS");
140- sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
141-
142- return new SSLOptions(sslContext, SSLOptions.DEFAULT_SSL_CIPHER_SUITES);
143135 }
144136 }
added driver-core/src/test/resources/client.crt +19 −0
@@ -0,0 +1,19 @@
1+-----BEGIN CERTIFICATE-----
2+MIIDqTCCApGgAwIBAgIERLZiJzANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMCVVMxEzARBgNV
3+BAgTCkNhbGlmb3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1EYXRhU3RheCBJ
4+bmMuMRowGAYDVQQLExFEcml2ZXJzIGFuZCBUb29sczEWMBQGA1UEAxMNRHJpdmVyIENsaWVudDAe
5+Fw0xNTAzMTIwMTA4MjRaFw0xNTA2MTAwMTA4MjRaMIGEMQswCQYDVQQGEwJVUzETMBEGA1UECBMK
6+Q2FsaWZvcm5pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExFjAUBgNVBAoTDURhdGFTdGF4IEluYy4x
7+GjAYBgNVBAsTEURyaXZlcnMgYW5kIFRvb2xzMRYwFAYDVQQDEw1Ecml2ZXIgQ2xpZW50MIIBIjAN
8+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq0J0EoZQnOv2KRrvwA+1ZL9VZ3hDdQMwkDfitoGN
9+B6upvMUZpf8W+ReQmaY6yacYJthHzsZTd3G97Bw81/3VNHQB9PnXGmbupMLVXeFXysSCs1nPEdJl
10+TBbJXWHSh41AE4ejJaoCoTuigKGwI9lTbOOPDz/WMcio9nagsCJdsdG2+TxmR7RlyzEIANJ0wpnL
11+JEIeJmRS2loLVuCU4lZ9hDLN57cP9jEVD4Hk2kJD4Exx7G9HQFH+/63H6XtEDZsJcYldR7yBNsGr
12+pz9CupULCS1R40ePQEIlUXhM4ft/hsljQybLQvvfXNVTvk5WgY7LNaBJy6A/Tfg32SXEn3wUvwID
13+AQABoyEwHzAdBgNVHQ4EFgQUt+JDOeziZzHNYTFU/FL9PhDGqSQwDQYJKoZIhvcNAQELBQADggEB
14+ADOYpa1f9dPcVLq3RiMytajHo3YJ0AQqGRzVgngkeRFSdhyy/y+/8D0/V5s6QbNt/l6x3FxkoiTR
15+1Lptf96eylnS5AkGQTgogJP53cSNrqkDL0IyyvErSiATEXNpBKz6ivY+e5J1GLTfX9Ylu8limzIq
16+Y6YBnr8fMLD6XWraxtzzkJ9NIPhhaz696rxqr8ix6uy0mgxR/7/jUglreimZkLW40/qiABgX7Evw
17+UqpuJWmqNbQP9UXecx/UJ0hdxxxuxkZsoRoQwWYhkeT4aGCLJv/hjiNTfFAt23uHe0LVfW/HqykW
18+KoEj8F08mJVe5ZfpjF974i5qO9PU9XxvLfLjNvo=
19+-----END CERTIFICATE-----
added driver-core/src/test/resources/client.key +28 −0
@@ -0,0 +1,28 @@
1+-----BEGIN PRIVATE KEY-----
2+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCrQnQShlCc6/Yp
3+Gu/AD7Vkv1VneEN1AzCQN+K2gY0Hq6m8xRml/xb5F5CZpjrJpxgm2EfOxlN3cb3s
4+HDzX/dU0dAH0+dcaZu6kwtVd4VfKxIKzWc8R0mVMFsldYdKHjUATh6MlqgKhO6KA
5+obAj2VNs448PP9YxyKj2dqCwIl2x0bb5PGZHtGXLMQgA0nTCmcskQh4mZFLaWgtW
6+4JTiVn2EMs3ntw/2MRUPgeTaQkPgTHHsb0dAUf7/rcfpe0QNmwlxiV1HvIE2waun
7+P0K6lQsJLVHjR49AQiVReEzh+3+GyWNDJstC+99c1VO+TlaBjss1oEnLoD9N+DfZ
8+JcSffBS/AgMBAAECggEAMHATNEoY8skqTmX3+XJ3847KMQGq0qWcTq3/yW7K3KiI
9+0YNNxc1oSfuIQmzpo69G/XWembUuVlItTWKPMufwLW3CP++KD0WdqawRfQQHOKpr
10+7R4xmvDPBb5MJcVNLlmdDekHE9gJ9mBPjeItV3ZYSivygnWjt2DxqQPUXvzZUzlu
11+munh3H5x6ehXVHDYGzosPgTpfmLHdlNfvF4x9bcklMMbCOyoPttXB2uHWOvUIS+/
12+2YEkPmJfZdpudI7RqN75yYi7N8+gpnCTp530zA2yONyZ8THqEG/0nWy+02/zm5sm
13+gs1saYNwXME2IPekZNM/pJh2DtnTcxZaUt84q2nhAQKBgQDi8mgvE8ekbs6DLfKK
14+YAtTuOcLRpuvJqxtiQecqaumzgZnmHtkm6yuDNjieqB6OITudP4NdhPpyvOFJw46
15+zTHMpGqZboxHuxoxMOgmyeiO+cdSwGHobr1zUcT8jVmLH7A+LtL5hHi+733EbCRh
16+sF04Vq9L46Q52mhcZKbs56U8MQKBgQDBLwotnOJH7hZD5sKS0o8/Sfj3pgzXEDpL
17+RfnrBPGhLn+1zhPEYsEW3mKI/yHiOZHNXZMQ6oYmxThg03qKTjaY8OIm8sg/zrlZ
18+M+o3wVnAzayrhw5gZ8DzqioHhEUMOAwwRFXRpfxqj8regrLjE9KaYty8ZYAFtwuH
19+W2S3+MVT7wKBgGQx7XlLXErmeNpFgN1Cxf1ylt7Nj5Jmmp3Jb8jkx9ne/8jg8ylZ
20+6YT2OxLSXONY7Kdyk29SADyp05WnxoqDaUcWF9IhkmFg45FwLC5j2f61nCCWuyMp
21+MQ8mvLdbmHrpxJ/PgGmU6NIzXe1IaU+P07g53S6+FBVOreCMt33ET5khAoGAGgKz
22+ZCDTdsvfw5S2bf5buzHCi9WXtP1CXBA37iTkQ8d2+oucrbx+Mw4ORlPTxBnsP7Jx
23+sr1hAqdbR+4xeZ2+TCliycu2mqDC4/fReWBXLVaEATRWAzT1DdnDfu+YPGTvfzA0
24+Pd4TdmWV8w+19k0c9hyJi/Q+oIZczwTHMt4T85ECgYAe4J0ht6b6kPEG3d9vxmMN
25+T23S+ucYLHnfT1nacTuBZnMphWHhSqf8UJloIGpusxDU84MdAp22Jpd9SfPi9KK9
26+yZY9WDJGeb0Yk7ML1R5GcAAkM78lUw/rS2VfMjQFnnUl2jVMS8adcm8/vHcpkcn7
27+MufMEZzDpeO/aI8nbClktw==
28+-----END PRIVATE KEY-----
modified pom.xml +1 −1
@@ -48,7 +48,7 @@
4848 <log4j.version>1.2.17</log4j.version>
4949 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>
5050 <guava.version>16.0.1</guava.version>
51- <netty.version>4.0.27.Final</netty.version>
51+ <netty.version>4.0.33.Final</netty.version>
5252 <metrics.version>3.1.2</metrics.version>
5353 <snappy.version>1.0.5</snappy.version>
5454 <lz4.version>1.2.0</lz4.version>