-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathClientJSSE.java
More file actions
501 lines (426 loc) · 17.3 KB
/
Copy pathClientJSSE.java
File metadata and controls
501 lines (426 loc) · 17.3 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* ClientJSSE.java
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.Provider;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Arrays;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.provider.jsse.WolfSSLProvider;
import com.wolfssl.WolfSSL;
import java.security.PrivateKey;
import java.security.Security;
import javax.net.ssl.KeyManager;
import javax.net.ssl.X509KeyManager;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
public class ClientJSSE {
public ClientJSSE() {
}
public void run(String[] args) throws Exception {
int ret = 0, input;
byte[] back = new byte[1024];
String readString = null;
String msg = "Too legit to quit";
/* HTTP GET Host appended after command line args */
String httpGetMsg = "GET / HTTP/1.1";
String provider = "wolfJSSE";
KeyStore pKey, cert;
TrustManagerFactory tm = null;
KeyManagerFactory km = null;
ServerSocketFactory srv;
ServerSocket tls;
SSLContext ctx;
BufferedReader inReader = null;
OutputStream outStream = null;
/* config info */
String version;
String cipherList = null; /* default ciphersuite list */
int sslVersion = 3; /* default to TLS 1.2 */
boolean verifyPeer = true; /* verify peer by default */
boolean useSysRoots = false; /* skip CA KeyStore load,
use system default roots */
boolean useEnvVar = false; /* load cert/key from enviornment
variable */
boolean listSuites = false; /* list all supported cipher
suites */
boolean listEnabledProtocols = false; /* show enabled protocols */
boolean putEnabledProtocols = false; /* set enabled protocols */
boolean sendGET = false; /* send HTTP GET */
/* Sleep 10 seconds before and after execution of main example,
* to allow profilers like VisualVM to be attached. */
boolean profileSleep = false;
boolean resumeSession = false; /* try one session resumption */
byte[] firstSessionId = null; /* sess ID of first session */
byte[] resumeSessionId = null; /* sess ID of resumed session */
String pqcAlg = null; /* PQC named group, -pqc */
/* cert info */
String clientJKS = "../provider/client.jks";
String caJKS = "../provider/ca-server.jks";
String clientPswd = "wolfSSL test";
String caPswd = "wolfSSL test";
String keyStoreFormat = "JKS";
/* server (peer) info */
String host = "localhost";
int port = 11111;
/* set/get enabled protocols */
String[] protocols = null;
/* pull in command line options from user */
for (int i = 0; i < args.length; i++)
{
String arg = args[i];
if (arg.equals("-?")) {
printUsage();
} else if (arg.equals("-h")) {
if (args.length < i+2)
printUsage();
host = args[++i];
} else if (arg.equals("-p")) {
if (args.length < i+2)
printUsage();
port = Integer.parseInt(args[++i]);
} else if (arg.equals("-v")) {
if (args.length < i+2)
printUsage();
if (args[i+1].equals("d")) {
i++;
sslVersion = -1;
}
else {
sslVersion = Integer.parseInt(args[++i]);
if (sslVersion < 0 || sslVersion > 4) {
printUsage();
}
}
} else if (arg.equals("-l")) {
if (args.length < i+2)
printUsage();
cipherList = args[++i];
} else if (arg.equals("-c")) {
String[] tmp = args[++i].split(":");
if (tmp.length != 2) {
printUsage();
}
clientJKS = tmp[0];
clientPswd = tmp[1];
} else if (arg.equals("-A")) {
String[] tmp = args[++i].split(":");
if (tmp.length != 2) {
printUsage();
}
caJKS = tmp[0];
caPswd = tmp[1];
} else if (arg.equals("-d")) {
verifyPeer = false;
} else if (arg.equals("-g")) {
sendGET = true;
} else if (arg.equals("-e")) {
listSuites = true;
} else if (arg.equals("-env")) {
useEnvVar = true;
} else if (arg.equals("-getp")) {
listEnabledProtocols = true;
} else if (arg.equals("-setp")) {
putEnabledProtocols = true;
protocols = args[++i].split(" ");
sslVersion = -1;
} else if (arg.equals("-r")) {
resumeSession = true;
} else if (arg.equals("-profile")) {
profileSleep = true;
} else if (arg.equals("-sysca")) {
useSysRoots = true;
} else if (arg.equals("-ksformat")) {
keyStoreFormat = args[++i];
} else if (arg.equals("-pqc")) {
if (args.length < i+2) {
printUsage();
}
pqcAlg = args[++i];
} else {
printUsage();
}
}
switch (sslVersion) {
case -1: version = "TLS"; break;
case 0: version = "SSLv3"; break;
case 1: version = "TLSv1"; break;
case 2: version = "TLSv1.1"; break;
case 3: version = "TLSv1.2"; break;
case 4: version = "TLSv1.3"; break;
default:
printUsage();
return;
}
/* PQC named groups are TLS 1.3 only. Allow only -v 4 (TLS 1.3)
* or -v d (generic TLS, which can negotiate TLS 1.3). Reject
* everything else up front rather than letting the handshake
* fail at the TLS layer. */
if (pqcAlg != null && sslVersion != 4 && sslVersion != -1) {
System.out.println("-pqc requires -v 4 (TLS 1.3) or -v d");
System.exit(1);
}
/* Add host into HTTP GET */
httpGetMsg = String.format("%s\r\nHost: %s\r\n\r\n", httpGetMsg, host);
if (profileSleep) {
System.out.println(
"Sleeping 10 seconds to allow profiler to attach");
Thread.sleep(10000);
}
/* Single -pqc group. Set wolfjsse.enabledSupportedCurves before
* SSLContext is built so provider sees the restriction when
* initializing the session. */
if (pqcAlg != null) {
Security.setProperty("wolfjsse.enabledSupportedCurves", pqcAlg);
System.out.println("Set wolfjsse.enabledSupportedCurves = " +
pqcAlg);
}
/* X509TrustManager that trusts all peer certificates. Used if peer
* authentication (-d) has been passed in */
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(
X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(
X509Certificate[] chain, String authType) {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
/* trust manager (certificates) */
if (verifyPeer) {
tm = TrustManagerFactory.getInstance("SunX509", provider);
if (useSysRoots) {
/* Let wolfJSSE try to find/load default system CA certs */
tm.init((KeyStore)null);
}
else {
cert = KeyStore.getInstance(keyStoreFormat);
cert.load(new FileInputStream(caJKS), caPswd.toCharArray());
tm.init(cert);
}
}
/* load private key */
pKey = KeyStore.getInstance(keyStoreFormat);
pKey.load(new FileInputStream(clientJKS), clientPswd.toCharArray());
km = KeyManagerFactory.getInstance("SunX509", provider);
km.init(pKey, clientPswd.toCharArray());
/* setup context with certificate and private key */
ctx = SSLContext.getInstance(version, provider);
if (verifyPeer) {
ctx.init(km.getKeyManagers(), tm.getTrustManagers(), null);
}
else {
ctx.init(km.getKeyManagers(), trustAllCerts, null);
}
if (listSuites) {
String[] suites = ctx.getDefaultSSLParameters().getCipherSuites();
for (String x : suites) {
System.out.println("\t" + x);
}
return;
}
SocketFactory sf = ctx.getSocketFactory();
/* print enabled protocols if requested */
if (listEnabledProtocols) {
SSLSocket sk = (SSLSocket)sf.createSocket();
String[] prtolists = sk.getEnabledProtocols();
for (String str : prtolists) {
System.out.println("\t" + str);
}
return;
}
SSLSocket sock = (SSLSocket)sf.createSocket(host, port);
/* put enabled protocols if requested */
if (putEnabledProtocols) {
if(protocols != null)
sock.setEnabledProtocols(protocols);
}
System.out.printf("Using SSLContext provider %s\n", ctx.getProvider().
getName());
if (cipherList != null) {
sock.setEnabledCipherSuites(cipherList.split(":"));
}
sock.startHandshake();
firstSessionId = sock.getSession().getId();
showPeer(sock);
inReader = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
outStream = sock.getOutputStream();
if (sendGET) {
outStream.write(httpGetMsg.getBytes());
}
else {
outStream.write(msg.getBytes());
}
System.out.println("Server message : ");
while ((readString = inReader.readLine()) != null) {
System.out.println(readString);
}
inReader.close();
outStream.close();
sock.close();
if (resumeSession) {
System.out.println("\nTrying session resumption...");
sock = (SSLSocket)sf.createSocket(host, port);
if (putEnabledProtocols) {
if(protocols != null)
sock.setEnabledProtocols(protocols);
}
System.out.printf("Using SSLContext provider %s\n",
ctx.getProvider().getName());
if (cipherList != null) {
sock.setEnabledCipherSuites(cipherList.split(":"));
}
sock.startHandshake();
resumeSessionId = sock.getSession().getId();
showPeer(sock);
inReader = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
outStream = sock.getOutputStream();
if (Arrays.equals(firstSessionId, resumeSessionId)) {
System.out.println("Session resumed");
} else {
System.out.println("Session NOT resumed");
}
if (sendGET) {
outStream.write(httpGetMsg.getBytes());
}
else {
outStream.write(msg.getBytes());
}
System.out.println("Server message : ");
while ((readString = inReader.readLine()) != null) {
System.out.println(readString);
}
inReader.close();
outStream.close();
sock.close();
}
if (profileSleep) {
/* Remove provider and set variables to null to help garbage
* collector for profiling */
Security.removeProvider("wolfJSSE");
sock = null;
sf = null;
ctx = null;
km = null;
tm = null;
/* Try and kick start garbage collector before profiling
* heap dump */
System.gc();
System.out.println(
"Sleeping 10 seconds to allow profiler to dump heap");
Thread.sleep(10000);
}
}
private void showPeer(SSLSocket sock) {
int i = 0;
byte[] sessionId = null;
SSLSession session = sock.getSession();
System.out.println("SSL version is " + session.getProtocol());
System.out.println("SSL cipher suite is " + session.getCipherSuite());
sessionId = session.getId();
if (sessionId != null) {
System.out.format("Session ID (%d bytes): ", sessionId.length);
for (i = 0; i < sessionId.length; i++) {
System.out.format("%02x", sessionId[i]);
}
System.out.println("");
}
System.out.println("Session created: " + session.getCreationTime());
System.out.println("Session accessed: " + session.getLastAccessedTime());
if (WolfSSLDebug.DEBUG) {
try {
Certificate[] certs = session.getPeerCertificates();
if (certs != null && certs.length > 0) {
System.out.println(((X509Certificate)certs[0]).toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
WolfSSL.loadLibrary();
Security.addProvider(new WolfSSLProvider());
ClientJSSE client = new ClientJSSE();
try {
client.run(args);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void printUsage() {
System.out.println("Java wolfJSSE example client usage:");
System.out.println("-?\t\tHelp, print this usage");
System.out.println("-h <host>\tHost to connect to, default 127.0.0.1");
System.out.println("-p <num>\tPort to connect to, default 11111");
System.out.println("-v <num>\tSSL version [0-4], SSLv3(0) - " +
"TLS1.3(4)), default 3 : use 'd' for downgrade");
System.out.println("-l <str>\tCipher list");
System.out.println("-d\t\tDisable peer checks");
System.out.println("-g\t\tSend server HTTP GET");
System.out.println("-e\t\tGet all supported cipher suites");
System.out.println("-r\t\tResume session");
System.out.println("-sysca\t\tLoad system CA certs, ignore any passed in");
System.out.println("-getp\t\tGet enabled protocols");
System.out.println("-setp <protocols> \tSet enabled protocols " +
"e.g \"TLSv1.1 TLSv1.2\"");
System.out.println("-c <file>:<password>\tCertificate/key JKS,\t\tdefault " +
"../provider/client.jks:\"wolfSSL test\"");
System.out.println("-A <file>:<password>\tCertificate/key CA JKS file,\tdefault " +
"../provider/ca-server.jks:\"wolfSSL test\"");
System.out.println("-profile\tSleep for 10 sec before/after running " +
"to allow profilers to attach");
System.out.println("-ksformat <str>\tKeyStore format (default: JKS)");
System.out.println("-pqc <alg>\tRestrict key exchange to " +
"specified post-quantum group only, e.g. X25519MLKEM768");
System.exit(1);
}
}