-
Notifications
You must be signed in to change notification settings - Fork 263
/
TLS13AuthenticationTest.java
300 lines (255 loc) · 13.2 KB
/
TLS13AuthenticationTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
* JBoss, Home of Professional Open Source.
* Copyright 2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed 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.wildfly.security.ssl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.security.AccessController;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivilegedAction;
import java.security.Security;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509TrustManager;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.wildfly.security.WildFlyElytronProvider;
import org.wildfly.security.auth.client.AuthenticationContext;
import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient;
import org.wildfly.security.auth.realm.KeyStoreBackedSecurityRealm;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.auth.server.SecurityRealm;
import org.wildfly.security.permission.PermissionVerifier;
import org.wildfly.security.ssl.test.util.CAGenerationTool;
import org.wildfly.security.ssl.test.util.CAGenerationTool.Identity;
import org.wildfly.security.x500.principal.X500AttributePrincipalDecoder;
/**
* Simple test case to test two-way SSL using TLSv1.3.
*
* @author <a href="mailto:fjuma@redhat">Farah Juma</a>
*/
public class TLS13AuthenticationTest {
private static final boolean IS_IBM = System.getProperty("java.vendor").contains("IBM");
private static final char[] PASSWORD = "Elytron".toCharArray();
private static final String CA_JKS_LOCATION = "./target/test-classes/jks";
private static CAGenerationTool caGenerationTool = null;
private static SecurityDomain securityDomain = null;
@BeforeClass
public static void setUp() throws Exception{
Assume.assumeTrue("Skipping TLS13AuthenticationTest suite, tests are not being run on JDK 11.",
System.getProperty("java.specification.version").equals("11"));
caGenerationTool = CAGenerationTool.builder()
.setBaseDir(CA_JKS_LOCATION)
.setRequestIdentities(Identity.LADYBIRD, Identity.SCARAB)
.build();
SecurityRealm securityRealm = new KeyStoreBackedSecurityRealm(loadKeyStore("/jks/beetles.keystore"));
securityDomain = SecurityDomain.builder()
.addRealm("KeystoreRealm", securityRealm)
.build()
.setDefaultRealmName("KeystoreRealm")
.setPrincipalDecoder(new X500AttributePrincipalDecoder("2.5.4.3", 1))
.setPreRealmRewriter((String s) -> s.toLowerCase(Locale.ENGLISH))
.setPermissionMapper((permissionMappable, roles) -> PermissionVerifier.ALL)
.build();
}
@AfterClass
public static void cleanUp() throws IOException {
caGenerationTool.close();
}
@Test
public void testTwoWayTLS13() throws Exception {
final String CIPHER_SUITE = "TLS_AES_128_GCM_SHA256";
SSLContext serverContext = new SSLContextBuilder()
.setSecurityDomain(securityDomain)
.setCipherSuiteSelector(CipherSuiteSelector.fromNamesString(CIPHER_SUITE))
.setKeyManager(getKeyManager("/jks/scarab.keystore"))
.setTrustManager(getCATrustManager())
.setNeedClientAuth(true)
.build().create();
SecurityIdentity identity = performConnectionTest(serverContext, "protocol://test-two-way-tls13.org", "wildfly-ssl-test-config-v1_5.xml", CIPHER_SUITE, true);
assertNotNull(identity);
assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName());
}
@Test
public void testDifferentPreferredTLS13Suites() throws Exception {
final String REQUIRED_CIPHER_SUITE = "TLS_AES_128_GCM_SHA256";
final String PREFERRED_CIPHER_SUITE = "TLS_AES_256_GCM_SHA384";
final String SERVER_CIPHER_SUITE = String.format("%s:%s", PREFERRED_CIPHER_SUITE, REQUIRED_CIPHER_SUITE);
SSLContext serverContext = new SSLContextBuilder()
.setSecurityDomain(securityDomain)
.setCipherSuiteSelector(CipherSuiteSelector.fromNamesString(SERVER_CIPHER_SUITE))
.setKeyManager(getKeyManager("/jks/scarab.keystore"))
.setTrustManager(getCATrustManager())
.setNeedClientAuth(true)
.build().create();
SecurityIdentity identity = performConnectionTest(serverContext, "protocol://test-different-preferred-tls13-suites.org", "wildfly-ssl-test-config-v1_5.xml", REQUIRED_CIPHER_SUITE, true);
assertNotNull(identity);
assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName());
}
@Test
public void testClientTLS12Only() throws Exception {
final String TLS13_CIPHER_SUITE = "TLS_AES_128_GCM_SHA256";
final String TLS12_CIPHER_SUITE = "TLS_RSA_WITH_AES_128_CBC_SHA256"; // TLS v1.2
SSLContext serverContext = new SSLContextBuilder()
.setSecurityDomain(securityDomain)
.setCipherSuiteSelector(CipherSuiteSelector.aggregate(
CipherSuiteSelector.fromNamesString(TLS13_CIPHER_SUITE),
CipherSuiteSelector.fromString(TLS12_CIPHER_SUITE)
))
.setKeyManager(getKeyManager("/jks/scarab.keystore"))
.setTrustManager(getCATrustManager())
.setNeedClientAuth(true)
.build().create();
SecurityIdentity identity = performConnectionTest(serverContext, "protocol://test-client-tls12-only.org", "wildfly-ssl-test-config-v1_5.xml", TLS12_CIPHER_SUITE, false);
assertNotNull(identity);
assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName());
}
@Test
public void testServerTLS12Only() throws Exception {
final String SERVER_CIPHER_SUITE = "TLS_RSA_WITH_AES_128_CBC_SHA256"; // TLS v1.2
SSLContext serverContext = new SSLContextBuilder()
.setSecurityDomain(securityDomain)
.setCipherSuiteSelector(CipherSuiteSelector.fromString(SERVER_CIPHER_SUITE))
.setKeyManager(getKeyManager("/jks/scarab.keystore"))
.setTrustManager(getCATrustManager())
.setNeedClientAuth(true)
.build().create();
SecurityIdentity identity = performConnectionTest(serverContext, "protocol://test-server-tls12-only.org", "wildfly-ssl-test-config-v1_5.xml", SERVER_CIPHER_SUITE, false);
assertNotNull(identity);
assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName());
}
@Test
public void testOneWayTLS13() throws Exception {
final String CIPHER_SUITE = "TLS_AES_128_GCM_SHA256";
SSLContext serverContext = new SSLContextBuilder()
.setCipherSuiteSelector(CipherSuiteSelector.fromNamesString(CIPHER_SUITE))
.setKeyManager(getKeyManager("/jks/scarab.keystore"))
.build().create();
SecurityIdentity identity = performConnectionTest(serverContext, "protocol://test-one-way-tls13.org", "wildfly-ssl-test-config-v1_5.xml", CIPHER_SUITE, true);
assertNull(identity);
}
private SecurityIdentity performConnectionTest(SSLContext serverContext, String clientUri, String clientConfigFileName, String expectedCipherSuite, boolean expectTLS13) throws Exception {
System.setProperty("wildfly.config.url", SSLAuthenticationTest.class.getResource(clientConfigFileName).toExternalForm());
AccessController.doPrivileged((PrivilegedAction<Integer>) () -> Security.insertProviderAt(new WildFlyElytronProvider(), 1));
AuthenticationContext context = AuthenticationContext.getContextManager().get();
AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
SSLContext clientContext = contextConfigurationClient.getSSLContext(URI.create(clientUri), context);
SSLServerSocketFactory sslServerSocketFactory = serverContext.getServerSocketFactory();
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(1111, 10, InetAddress.getLoopbackAddress());
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<SSLSocket> socketFuture = executorService.submit(() -> {
try {
System.out.println("About to connect client");
SSLSocket sslSocket = (SSLSocket) clientContext.getSocketFactory().createSocket(InetAddress.getLoopbackAddress(), 1111);
sslSocket.getSession();
return sslSocket;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
System.out.println("Client connected");
}
});
SSLSocket serverSocket = (SSLSocket) sslServerSocket.accept();
SSLSession serverSession = serverSocket.getSession();
SSLSocket clientSocket = socketFuture.get();
SSLSession clientSession = clientSocket.getSession();
try {
if (expectedCipherSuite != null) {
if(expectTLS13) {
assertEquals("TLSv1.3", serverSession.getProtocol());
assertEquals("TLSv1.3", clientSession.getProtocol());
} else {
assertEquals("TLSv1.2", serverSession.getProtocol());
assertEquals("TLSv1.2", clientSession.getProtocol());
}
assertEquals(expectedCipherSuite, serverSession.getCipherSuite());
assertEquals(expectedCipherSuite, clientSession.getCipherSuite());
}
return (SecurityIdentity) serverSession.getValue(SSLUtils.SSL_SESSION_IDENTITY_KEY);
} finally {
safeClose(serverSocket);
safeClose(clientSocket);
safeClose(sslServerSocket);
}
}
/**
* Get the key manager backed by the specified key store.
*
* @param keystorePath the path to the keystore with X509 private key
* @return the initialised key manager.
*/
private static X509ExtendedKeyManager getKeyManager(final String keystorePath) throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(IS_IBM ? "IbmX509" : "SunX509");
keyManagerFactory.init(loadKeyStore(keystorePath), PASSWORD);
for (KeyManager current : keyManagerFactory.getKeyManagers()) {
if (current instanceof X509ExtendedKeyManager) {
return (X509ExtendedKeyManager) current;
}
}
throw new IllegalStateException("Unable to obtain X509ExtendedKeyManager.");
}
/**
* Get the trust manager that trusts all certificates signed by the certificate authority.
*
* @return the trust manager that trusts all certificates signed by the certificate authority.
* @throws KeyStoreException
*/
private static X509TrustManager getCATrustManager() throws Exception {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(IS_IBM ? "IbmX509" : "SunX509");
trustManagerFactory.init(loadKeyStore("/jks/ca.truststore"));
for (TrustManager current : trustManagerFactory.getTrustManagers()) {
if (current instanceof X509TrustManager) {
return (X509TrustManager) current;
}
}
throw new IllegalStateException("Unable to obtain X509TrustManager.");
}
private static KeyStore loadKeyStore(final String path) throws Exception {
KeyStore keyStore = KeyStore.getInstance("jks");
try (InputStream caTrustStoreFile = SSLAuthenticationTest.class.getResourceAsStream(path)) {
keyStore.load(caTrustStoreFile, PASSWORD);
}
return keyStore;
}
private void safeClose(Closeable closeable) {
try {
closeable.close();
} catch (Exception ignored) {}
}
}