-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSSLTest.java
More file actions
459 lines (399 loc) · 18.4 KB
/
SSLTest.java
File metadata and controls
459 lines (399 loc) · 18.4 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* SSLTest.java
*
* Tests servers for SSL/TLS protocol and cipher support.
*
* Copyright (c) 2015 Christopher Schultz
*
* Christopher Schultz 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.
*/
// Note this class requires [[SSLUtils.java]]
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
/**
* A driver class to test a server's SSL/TLS support.
* <p>
* Usage: java SSLTest [opts] host[:port]
* <p>
* Try "java SSLTest -h" for help.
* <p>
* https://wiki.apache.org/tomcat/tools/SSLTest.java
* <p>
* This tester will attempts to handshake with the target host with all
* available protocols and ciphers and report which ones were accepted and
* which were rejected. An HTTP connection is never fully made, so these
* connections should not flood the host's access log with entries.
*
* @author Christopher Schultz
*/
public class SSLTest {
public static void usage() {
System.out.println("Usage: java " + SSLTest.class + " [opts] host[:port]");
System.out.println();
System.out.println("-sslprotocol Sets the SSL/TLS protocol to be used (e.g. SSL, TLS, SSLv3, TLSv1.2, etc.)");
System.out.println("-enabledprotocols protocols Sets individual SSL/TLS ptotocols that should be enabled (e.g. SSL, TLS, SSLv3, TLSv1.2, etc.)");
System.out.println("-ciphers cipherspec A comma-separated list of SSL/TLS ciphers");
System.out.println("-truststore Sets the trust store for connections");
System.out.println("-truststoretype type Sets the type for the trust store");
System.out.println("-truststorepassword pass Sets the password for the trust store");
System.out.println("-truststorealgorithm alg Sets the algorithm for the trust store");
System.out.println("-truststoreprovider provider Sets the crypto provider for the trust store");
//System.out.println("-skip-ciphers-test Skip the ciphers test step");
System.out.println("-no-check-certificate Ignores certificate errors");
System.out.println("-no-verify-hostname Ignores hostname mismatches");
System.out.println("-unlimited-jce Enable unlimited JCE");
System.out.println("-sni Enable SNI check");
System.out.println("-bouncy Enable Bouncy Castle Crypt");
System.out.println("-h -help --help Shows this help message");
}
public static void main(String[] args)
throws Exception {
System.out.println("Current AES length - " + JCEUtils.getAESMaxKeyLength());
int connectTimeout = 10000;
int readTimeout = 10000;
boolean disableHostnameVerification = true;
boolean disableCertificateChecking = true;
String trustStoreFilename = System.getProperty("javax.net.ssl.trustStore");
String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
String trustStoreAlgorithm = null;
String sslProtocol = "TLS";
String[] sslEnabledProtocols = new String[]{"SSLv2", "SSLv2hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"};
String[] sslCipherSuites = null; // Default = default for protocol
String crlFilename = null;
boolean showCerts = false;
boolean unlimitedJCE = false;
boolean skipCiphersTest = false;
boolean enableSNI = false;
boolean enableBouncyCastle = false;
if (args.length < 1) {
usage();
System.exit(0);
}
int argIndex;
for (argIndex = 0; argIndex < args.length; ++argIndex) {
String arg = args[argIndex];
if (!arg.startsWith("-"))
break;
else if ("--".equals(arg))
break;
else if ("-no-check-certificate".equals(arg))
disableCertificateChecking = true;
else if ("-unlimited-jce".equals(arg)) {
unlimitedJCE = true;
}
else if ("-skip-ciphers-test".equals(arg)) {
skipCiphersTest = true;
}
else if ("-no-verify-hostname".equals(arg))
disableHostnameVerification = true;
else if ("-sslprotocol".equals(arg))
sslProtocol = args[++argIndex];
else if ("-enabledprotocols".equals(arg))
sslEnabledProtocols = args[++argIndex].split("\\s*,\\s*");
else if ("-ciphers".equals(arg))
sslCipherSuites = args[++argIndex].split("\\s*,\\s*");
else if ("-connecttimeout".equals(arg))
connectTimeout = Integer.parseInt(args[++argIndex]);
else if ("-readtimeout".equals(arg))
readTimeout = Integer.parseInt(args[++argIndex]);
else if ("-truststore".equals(arg))
trustStoreFilename = args[++argIndex];
else if ("-truststoretype".equals(arg))
trustStoreType = args[++argIndex];
else if ("-truststorepassword".equals(arg))
trustStorePassword = args[++argIndex];
else if ("-truststoreprovider".equals(arg))
trustStoreProvider = args[++argIndex];
else if ("-truststorealgorithm".equals(arg))
trustStoreAlgorithm = args[++argIndex];
else if ("-showcerts".equals(arg))
showCerts = true;
else if ("-sni".equals(arg)) {
enableSNI = true;
}
else if ("-bouncy".equals(arg)) {
enableBouncyCastle = true;
}
else if ("--help".equals(arg)
|| "-h".equals(arg)
|| "-help".equals(arg)) {
usage();
System.exit(0);
}
else {
System.out.println("Unrecognized option: " + arg);
System.exit(1);
}
}
if (argIndex >= args.length) {
System.out.println("Unexpected additional arguments: "
+ Arrays.asList(args).subList(argIndex, args.length));
usage();
System.exit(1);
}
if (unlimitedJCE) {
JCEUtils.removeRestrictedCryptography();
System.out.println("After Unlimited JCE, AES length - " + JCEUtils.getAESMaxKeyLength());
}
if (enableBouncyCastle) {
try {
//add at runtime the Bouncy Castle Provider
//the provider is available only for this application
Security.addProvider(new BouncyCastleProvider());
//BC is the ID for the Bouncy Castle provider;
if (Security.getProvider("BC") == null) {
System.out.println("!!!Bouncy Castle provider is NOT available");
}
else {
System.out.println("Aha Bouncy Castle provider is available");
}
}
catch (Throwable e) {
}
}
if (disableHostnameVerification)
SSLUtils.disableSSLHostnameVerification();
TrustManager[] trustManagers;
if (disableCertificateChecking
|| "true".equalsIgnoreCase(System.getProperty("disable.ssl.cert.checks"))) {
trustManagers = SSLUtils.getTrustAllCertsTrustManagers();
}
else if (null != trustStoreFilename) {
if (null == trustStoreType)
trustStoreType = "JKS";
trustManagers = SSLUtils.getTrustManagers(trustStoreFilename, trustStorePassword, trustStoreType, trustStoreProvider,
trustStoreAlgorithm, null, crlFilename);
}
else
trustManagers = null;
int port = 443;
String host = args[argIndex];
int pos = host.indexOf(':');
if (pos > 0) {
port = Integer.parseInt(host.substring(pos + 1));
host = host.substring(0, pos);
}
// Enable all algorithms
Security.setProperty("jdk.tls.disabledAlgorithms", "");
List<String> supportedProtocols;
if (null == sslEnabledProtocols) {
// Auto-detect protocols
ArrayList<String> protocols = new ArrayList<String>();
// TODO: Allow the specification of a specific provider (or set?)
for (Provider provider : Security.getProviders()) {
for (Object prop : provider.keySet()) {
String key = (String) prop;
if (key.startsWith("SSLContext.")
&& !key.equals("SSLContext.Default")
&& key.matches(".*[0-9].*"))
protocols.add(key.substring("SSLContext.".length()));
else if (key.startsWith("Alg.Alias.SSLContext.")
&& key.matches(".*[0-9].*"))
protocols.add(key.substring("Alg.Alias.SSLContext.".length()));
}
}
Collections.sort(protocols); // Should give us a nice sort-order by default
System.err.println("Auto-detected client-supported protocols: " + protocols);
supportedProtocols = protocols;
sslEnabledProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
}
else {
supportedProtocols = new ArrayList<String>(Arrays.asList(sslEnabledProtocols));
}
if (!skipCiphersTest) {
// do ciphers test
// todo not done
}
System.out.println("Testing server " + host + ":" + port);
SecureRandom rand = new SecureRandom();
String reportFormat = "%9s %8s %s\n";
System.out.print(String.format(reportFormat, "Supported", "Protocol", "Cipher"));
InetSocketAddress address = new InetSocketAddress(host, port);
for (String protocol : sslEnabledProtocols) {
SSLContext sc;
try {
sc = SSLContext.getInstance(protocol);
}
catch (NoSuchAlgorithmException nsae) {
System.out.print(String.format(reportFormat, "-----", protocol, " Not supported by client"));
supportedProtocols.remove(protocol);
continue;
}
catch (Exception e) {
e.printStackTrace();
continue; // Skip this protocol
}
sc.init(null, null, rand);
// Restrict cipher suites to those specified by sslCipherSuites
HashSet<String> cipherSuites = new HashSet<String>();
cipherSuites.addAll(Arrays.asList(sc.getSocketFactory().getSupportedCipherSuites()));
if (null != sslCipherSuites)
cipherSuites.retainAll(Arrays.asList(sslCipherSuites));
if (cipherSuites.isEmpty()) {
System.err.println("No overlapping cipher suites found for protocol " + protocol);
supportedProtocols.remove(protocol);
continue; // Go to the next protocol
}
for (String cipherSuite : cipherSuites) {
String status;
SSLSocketFactory sf = SSLUtils.getSSLSocketFactory(protocol,
new String[]{protocol},
new String[]{cipherSuite},
rand,
trustManagers);
if (enableSNI && sf instanceof SSLUtils.CustomSSLSocketFactory) {
((SSLUtils.CustomSSLSocketFactory) sf).setExpectedHost(host);
}
Socket sock = null;
try {
//
// Note: SSLSocketFactory has several create() methods.
// Those that take arguments all connect immediately
// and have no options for specifying a connection timeout.
//
// So, we have to create a socket and connect it (with a
// connection timeout), then have the SSLSocketFactory wrap
// the already-connected socket.
//
sock = new Socket();
sock.setSoTimeout(readTimeout);
sock.connect(address, connectTimeout);
// Wrap plain socket in an SSL socket
SSLSocket socket = (SSLSocket) sf.createSocket(sock, host, port, true);
socket.startHandshake();
assert protocol.equals(socket.getSession().getProtocol());
assert cipherSuite.equals(socket.getSession().getCipherSuite());
status = "Accepted";
}
catch (SocketTimeoutException ste) {
status = "Failed";
}
catch (IOException ioe) {
// System.out.println(ioe);
status = "Rejected";
}
catch (Exception e) {
System.out.print(e.getMessage());
status = "Rejected";
}
finally {
if (null != sock) try {
sock.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
System.out.print(String.format(reportFormat,
status,
protocol,
cipherSuite));
}
}
if (supportedProtocols.isEmpty()) {
System.err.println("No protocols ");
}
// Now get generic and allow the server to decide on the protocol and cipher suite
String[] protocolsToTry = supportedProtocols.toArray(new String[supportedProtocols.size()]);
SSLSocketFactory sf = SSLUtils.getSSLSocketFactory(sslProtocol,
protocolsToTry,
sslCipherSuites,
rand,
trustManagers);
if (enableSNI && sf instanceof SSLUtils.CustomSSLSocketFactory) {
((SSLUtils.CustomSSLSocketFactory) sf).setExpectedHost(host);
System.out.println("SNI enabled, expected host - " + host);
}
System.out.println("Finally try with those supported confs:");
System.out.println("\tsslProtocol=" + sslProtocol);
System.out.println("\tprotocols =" + Arrays.toString(protocolsToTry));
System.out.println("\tciphers =" + Arrays.toString(sslCipherSuites));
Socket sock = null;
try {
//
// Note: SSLSocketFactory has several create() methods.
// Those that take arguments all connect immediately
// and have no options for specifying a connection timeout.
//
// So, we have to create a socket and connect it (with a
// connection timeout), then have the SSLSocketFactory wrap
// the already-connected socket.
//
sock = new Socket();
sock.connect(address, connectTimeout);
sock.setSoTimeout(readTimeout);
// Wrap plain socket in an SSL socket
SSLSocket socket = (SSLSocket) sf.createSocket(sock, host, port, true);
socket.startHandshake();
System.out.print("Given this client's capabilities ("
+ supportedProtocols
+ "), the server prefers protocol=");
System.out.print(socket.getSession().getProtocol());
System.out.print(", cipher=");
System.out.println(socket.getSession().getCipherSuite());
if (showCerts) {
for (Certificate cert : socket.getSession().getPeerCertificates()) {
System.out.println("Certificate: " + cert.getType());
if ("X.509".equals(cert.getType())) {
X509Certificate x509 = (X509Certificate) cert;
System.out.println("Subject: " + x509.getSubjectDN());
System.out.println("Issuer: " + x509.getIssuerDN());
System.out.println("Serial: " + x509.getSerialNumber());
// System.out.println("Signature: " + toHexString(x509.getSignature()));
// System.out.println("cert bytes: " + toHexString(cert.getEncoded()));
// System.out.println("cert bytes: " + cert.getPublicKey());
}
else {
System.out.println("Unknown certificate type (" + cert.getType() + "): " + cert);
}
}
}
}
finally {
if (null != sock) try {
sock.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
static final char[] hexChars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'};
static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes)
sb.append(hexChars[(b >> 4) & 0x0f])
.append(hexChars[b & 0x0f]);
return sb.toString();
}
}