Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/javax/net/ssl/Stapling/SSLEngineWithStapling.java
41152 views
1
/*
2
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
// SunJSSE does not support dynamic system properties, no way to re-use
25
// system properties in samevm/agentvm mode.
26
27
/*
28
* @test
29
* @bug 8046321 8153829
30
* @summary OCSP Stapling for TLS
31
* @library ../../../../java/security/testlibrary
32
* @build CertificateBuilder SimpleOCSPServer
33
* @run main/othervm SSLEngineWithStapling
34
*/
35
36
/**
37
* A SSLEngine usage example which simplifies the presentation
38
* by removing the I/O and multi-threading concerns.
39
*
40
* The test creates two SSLEngines, simulating a client and server.
41
* The "transport" layer consists two byte buffers: think of them
42
* as directly connected pipes.
43
*
44
* Note, this is a *very* simple example: real code will be much more
45
* involved. For example, different threading and I/O models could be
46
* used, transport mechanisms could close unexpectedly, and so on.
47
*
48
* When this application runs, notice that several messages
49
* (wrap/unwrap) pass before any application data is consumed or
50
* produced. (For more information, please see the SSL/TLS
51
* specifications.) There may several steps for a successful handshake,
52
* so it's typical to see the following series of operations:
53
*
54
* client server message
55
* ====== ====== =======
56
* wrap() ... ClientHello
57
* ... unwrap() ClientHello
58
* ... wrap() ServerHello/Certificate
59
* unwrap() ... ServerHello/Certificate
60
* wrap() ... ClientKeyExchange
61
* wrap() ... ChangeCipherSpec
62
* wrap() ... Finished
63
* ... unwrap() ClientKeyExchange
64
* ... unwrap() ChangeCipherSpec
65
* ... unwrap() Finished
66
* ... wrap() ChangeCipherSpec
67
* ... wrap() Finished
68
* unwrap() ... ChangeCipherSpec
69
* unwrap() ... Finished
70
*/
71
72
import javax.net.ssl.*;
73
import javax.net.ssl.SSLEngineResult.*;
74
import java.io.*;
75
import java.math.BigInteger;
76
import java.security.*;
77
import java.nio.*;
78
import java.security.cert.CertPathValidatorException;
79
import java.security.cert.PKIXBuilderParameters;
80
import java.security.cert.X509Certificate;
81
import java.security.cert.X509CertSelector;
82
import java.util.ArrayList;
83
import java.util.Collections;
84
import java.util.Date;
85
import java.util.HashMap;
86
import java.util.List;
87
import java.util.Map;
88
import java.util.concurrent.TimeUnit;
89
90
import sun.security.testlibrary.SimpleOCSPServer;
91
import sun.security.testlibrary.CertificateBuilder;
92
93
public class SSLEngineWithStapling {
94
95
/*
96
* Enables logging of the SSLEngine operations.
97
*/
98
private static final boolean logging = true;
99
100
/*
101
* Enables the JSSE system debugging system property:
102
*
103
* -Djavax.net.debug=all
104
*
105
* This gives a lot of low-level information about operations underway,
106
* including specific handshake messages, and might be best examined
107
* after gaining some familiarity with this application.
108
*/
109
private static final boolean debug = true;
110
111
private SSLEngine clientEngine; // client Engine
112
private ByteBuffer clientOut; // write side of clientEngine
113
private ByteBuffer clientIn; // read side of clientEngine
114
115
private SSLEngine serverEngine; // server Engine
116
private ByteBuffer serverOut; // write side of serverEngine
117
private ByteBuffer serverIn; // read side of serverEngine
118
119
/*
120
* For data transport, this example uses local ByteBuffers. This
121
* isn't really useful, but the purpose of this example is to show
122
* SSLEngine concepts, not how to do network transport.
123
*/
124
private ByteBuffer cTOs; // "reliable" transport client->server
125
private ByteBuffer sTOc; // "reliable" transport server->client
126
127
/*
128
* The following is to set up the keystores.
129
*/
130
static final String passwd = "passphrase";
131
static final String ROOT_ALIAS = "root";
132
static final String INT_ALIAS = "intermediate";
133
static final String SSL_ALIAS = "ssl";
134
135
// PKI components we will need for this test
136
static KeyStore rootKeystore; // Root CA Keystore
137
static KeyStore intKeystore; // Intermediate CA Keystore
138
static KeyStore serverKeystore; // SSL Server Keystore
139
static KeyStore trustStore; // SSL Client trust store
140
static SimpleOCSPServer rootOcsp; // Root CA OCSP Responder
141
static int rootOcspPort; // Port number for root OCSP
142
static SimpleOCSPServer intOcsp; // Intermediate CA OCSP Responder
143
static int intOcspPort; // Port number for intermed. OCSP
144
145
// Extra configuration parameters and constants
146
static final String[] TLS13ONLY = new String[] { "TLSv1.3" };
147
static final String[] TLS12MAX =
148
new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" };
149
150
/*
151
* Main entry point for this test.
152
*/
153
public static void main(String args[]) throws Exception {
154
if (debug) {
155
System.setProperty("javax.net.debug", "ssl:handshake");
156
}
157
158
// Create the PKI we will use for the test and start the OCSP servers
159
createPKI();
160
161
// Set the certificate entry in the intermediate OCSP responder
162
// with a revocation date of 8 hours ago.
163
X509Certificate sslCert =
164
(X509Certificate)serverKeystore.getCertificate(SSL_ALIAS);
165
Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =
166
new HashMap<>();
167
revInfo.put(sslCert.getSerialNumber(),
168
new SimpleOCSPServer.CertStatusInfo(
169
SimpleOCSPServer.CertStatus.CERT_STATUS_REVOKED,
170
new Date(System.currentTimeMillis() -
171
TimeUnit.HOURS.toMillis(8))));
172
intOcsp.updateStatusDb(revInfo);
173
174
// Create a list of TLS protocol configurations we can use to
175
// drive tests with different handshaking models.
176
List<String[]> allowedProtList = List.of(TLS12MAX, TLS13ONLY);
177
178
for (String[] protocols : allowedProtList) {
179
SSLEngineWithStapling test = new SSLEngineWithStapling();
180
try {
181
test.runTest(protocols);
182
throw new RuntimeException("Expected failure due to " +
183
"revocation did not occur");
184
} catch (Exception e) {
185
if (!checkClientValidationFailure(e,
186
CertPathValidatorException.BasicReason.REVOKED)) {
187
System.out.println(
188
"*** Didn't find the exception we wanted");
189
throw e;
190
}
191
}
192
}
193
194
System.out.println("Test Passed.");
195
}
196
197
/*
198
* Create an initialized SSLContext to use for these tests.
199
*/
200
public SSLEngineWithStapling() throws Exception {
201
System.setProperty("javax.net.ssl.keyStore", "");
202
System.setProperty("javax.net.ssl.keyStorePassword", "");
203
System.setProperty("javax.net.ssl.trustStore", "");
204
System.setProperty("javax.net.ssl.trustStorePassword", "");
205
206
// Enable OCSP Stapling on both client and server sides, but turn off
207
// client-side OCSP for revocation checking. This ensures that the
208
// revocation information from the test has to come via stapling.
209
System.setProperty("jdk.tls.client.enableStatusRequestExtension",
210
Boolean.toString(true));
211
System.setProperty("jdk.tls.server.enableStatusRequestExtension",
212
Boolean.toString(true));
213
Security.setProperty("ocsp.enable", "false");
214
}
215
216
/*
217
* Run the test.
218
*
219
* Sit in a tight loop, both engines calling wrap/unwrap regardless
220
* of whether data is available or not. We do this until both engines
221
* report back they are closed.
222
*
223
* The main loop handles all of the I/O phases of the SSLEngine's
224
* lifetime:
225
*
226
* initial handshaking
227
* application data transfer
228
* engine closing
229
*
230
* One could easily separate these phases into separate
231
* sections of code.
232
*/
233
private void runTest(String[] protocols) throws Exception {
234
boolean dataDone = false;
235
236
createSSLEngines(protocols);
237
createBuffers();
238
239
SSLEngineResult clientResult; // results from client's last operation
240
SSLEngineResult serverResult; // results from server's last operation
241
242
/*
243
* Examining the SSLEngineResults could be much more involved,
244
* and may alter the overall flow of the application.
245
*
246
* For example, if we received a BUFFER_OVERFLOW when trying
247
* to write to the output pipe, we could reallocate a larger
248
* pipe, but instead we wait for the peer to drain it.
249
*/
250
while (!isEngineClosed(clientEngine) ||
251
!isEngineClosed(serverEngine)) {
252
253
log("================");
254
255
clientResult = clientEngine.wrap(clientOut, cTOs);
256
log("client wrap: ", clientResult);
257
runDelegatedTasks(clientResult, clientEngine);
258
259
serverResult = serverEngine.wrap(serverOut, sTOc);
260
log("server wrap: ", serverResult);
261
runDelegatedTasks(serverResult, serverEngine);
262
263
cTOs.flip();
264
sTOc.flip();
265
266
log("----");
267
268
clientResult = clientEngine.unwrap(sTOc, clientIn);
269
log("client unwrap: ", clientResult);
270
runDelegatedTasks(clientResult, clientEngine);
271
272
serverResult = serverEngine.unwrap(cTOs, serverIn);
273
log("server unwrap: ", serverResult);
274
runDelegatedTasks(serverResult, serverEngine);
275
276
cTOs.compact();
277
sTOc.compact();
278
279
/*
280
* After we've transfered all application data between the client
281
* and server, we close the clientEngine's outbound stream.
282
* This generates a close_notify handshake message, which the
283
* server engine receives and responds by closing itself.
284
*/
285
if (!dataDone && (clientOut.limit() == serverIn.position()) &&
286
(serverOut.limit() == clientIn.position())) {
287
288
/*
289
* A sanity check to ensure we got what was sent.
290
*/
291
checkTransfer(serverOut, clientIn);
292
checkTransfer(clientOut, serverIn);
293
294
log("\tClosing clientEngine's *OUTBOUND*...");
295
clientEngine.closeOutbound();
296
dataDone = true;
297
}
298
}
299
}
300
301
/*
302
* Using the SSLContext created during object creation,
303
* create/configure the SSLEngines we'll use for this test.
304
*/
305
private void createSSLEngines(String[] protocols) throws Exception {
306
// Initialize the KeyManager and TrustManager for the server
307
KeyManagerFactory servKmf = KeyManagerFactory.getInstance("PKIX");
308
servKmf.init(serverKeystore, passwd.toCharArray());
309
TrustManagerFactory servTmf =
310
TrustManagerFactory.getInstance("PKIX");
311
servTmf.init(trustStore);
312
313
// Initialize the TrustManager for the client with revocation checking
314
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustStore,
315
new X509CertSelector());
316
pkixParams.setRevocationEnabled(true);
317
ManagerFactoryParameters mfp =
318
new CertPathTrustManagerParameters(pkixParams);
319
TrustManagerFactory cliTmf =
320
TrustManagerFactory.getInstance("PKIX");
321
cliTmf.init(mfp);
322
323
// Create the SSLContexts from the factories
324
SSLContext servCtx = SSLContext.getInstance("TLS");
325
servCtx.init(servKmf.getKeyManagers(), servTmf.getTrustManagers(),
326
null);
327
SSLContext cliCtx = SSLContext.getInstance("TLS");
328
cliCtx.init(null, cliTmf.getTrustManagers(), null);
329
330
331
/*
332
* Configure the serverEngine to act as a server in the SSL/TLS
333
* handshake.
334
*/
335
serverEngine = servCtx.createSSLEngine();
336
serverEngine.setEnabledProtocols(protocols);
337
serverEngine.setUseClientMode(false);
338
serverEngine.setNeedClientAuth(false);
339
340
/*
341
* Similar to above, but using client mode instead.
342
*/
343
clientEngine = cliCtx.createSSLEngine("client", 80);
344
clientEngine.setEnabledProtocols(protocols);
345
clientEngine.setUseClientMode(true);
346
}
347
348
/*
349
* Create and size the buffers appropriately.
350
*/
351
private void createBuffers() {
352
353
/*
354
* We'll assume the buffer sizes are the same
355
* between client and server.
356
*/
357
SSLSession session = clientEngine.getSession();
358
int appBufferMax = session.getApplicationBufferSize();
359
int netBufferMax = session.getPacketBufferSize();
360
361
/*
362
* We'll make the input buffers a bit bigger than the max needed
363
* size, so that unwrap()s following a successful data transfer
364
* won't generate BUFFER_OVERFLOWS.
365
*
366
* We'll use a mix of direct and indirect ByteBuffers for
367
* tutorial purposes only. In reality, only use direct
368
* ByteBuffers when they give a clear performance enhancement.
369
*/
370
clientIn = ByteBuffer.allocate(appBufferMax + 50);
371
serverIn = ByteBuffer.allocate(appBufferMax + 50);
372
373
cTOs = ByteBuffer.allocateDirect(netBufferMax);
374
sTOc = ByteBuffer.allocateDirect(netBufferMax);
375
376
clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
377
serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
378
}
379
380
/*
381
* If the result indicates that we have outstanding tasks to do,
382
* go ahead and run them in this thread.
383
*/
384
private static void runDelegatedTasks(SSLEngineResult result,
385
SSLEngine engine) throws Exception {
386
387
if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
388
Runnable runnable;
389
while ((runnable = engine.getDelegatedTask()) != null) {
390
log("\trunning delegated task...");
391
runnable.run();
392
}
393
HandshakeStatus hsStatus = engine.getHandshakeStatus();
394
if (hsStatus == HandshakeStatus.NEED_TASK) {
395
throw new Exception(
396
"handshake shouldn't need additional tasks");
397
}
398
log("\tnew HandshakeStatus: " + hsStatus);
399
}
400
}
401
402
private static boolean isEngineClosed(SSLEngine engine) {
403
return (engine.isOutboundDone() && engine.isInboundDone());
404
}
405
406
/*
407
* Simple check to make sure everything came across as expected.
408
*/
409
private static void checkTransfer(ByteBuffer a, ByteBuffer b)
410
throws Exception {
411
a.flip();
412
b.flip();
413
414
if (!a.equals(b)) {
415
throw new Exception("Data didn't transfer cleanly");
416
} else {
417
log("\tData transferred cleanly");
418
}
419
420
a.position(a.limit());
421
b.position(b.limit());
422
a.limit(a.capacity());
423
b.limit(b.capacity());
424
}
425
426
/*
427
* Logging code
428
*/
429
private static boolean resultOnce = true;
430
431
private static void log(String str, SSLEngineResult result) {
432
if (!logging) {
433
return;
434
}
435
if (resultOnce) {
436
resultOnce = false;
437
System.out.println("The format of the SSLEngineResult is: \n" +
438
"\t\"getStatus() / getHandshakeStatus()\" +\n" +
439
"\t\"bytesConsumed() / bytesProduced()\"\n");
440
}
441
HandshakeStatus hsStatus = result.getHandshakeStatus();
442
log(str +
443
result.getStatus() + "/" + hsStatus + ", " +
444
result.bytesConsumed() + "/" + result.bytesProduced() +
445
" bytes");
446
if (hsStatus == HandshakeStatus.FINISHED) {
447
log("\t...ready for application data");
448
}
449
}
450
451
private static void log(String str) {
452
if (logging) {
453
System.out.println(str);
454
}
455
}
456
457
/**
458
* Creates the PKI components necessary for this test, including
459
* Root CA, Intermediate CA and SSL server certificates, the keystores
460
* for each entity, a client trust store, and starts the OCSP responders.
461
*/
462
private static void createPKI() throws Exception {
463
CertificateBuilder cbld = new CertificateBuilder();
464
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
465
keyGen.initialize(2048);
466
KeyStore.Builder keyStoreBuilder =
467
KeyStore.Builder.newInstance("PKCS12", null,
468
new KeyStore.PasswordProtection(passwd.toCharArray()));
469
470
// Generate Root, IntCA, EE keys
471
KeyPair rootCaKP = keyGen.genKeyPair();
472
log("Generated Root CA KeyPair");
473
KeyPair intCaKP = keyGen.genKeyPair();
474
log("Generated Intermediate CA KeyPair");
475
KeyPair sslKP = keyGen.genKeyPair();
476
log("Generated SSL Cert KeyPair");
477
478
// Set up the Root CA Cert
479
cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany");
480
cbld.setPublicKey(rootCaKP.getPublic());
481
cbld.setSerialNumber(new BigInteger("1"));
482
// Make a 3 year validity starting from 60 days ago
483
long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60);
484
long end = start + TimeUnit.DAYS.toMillis(1085);
485
cbld.setValidity(new Date(start), new Date(end));
486
addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic());
487
addCommonCAExts(cbld);
488
// Make our Root CA Cert!
489
X509Certificate rootCert = cbld.build(null, rootCaKP.getPrivate(),
490
"SHA256withRSA");
491
log("Root CA Created:\n" + certInfo(rootCert));
492
493
// Now build a keystore and add the keys and cert
494
rootKeystore = keyStoreBuilder.getKeyStore();
495
java.security.cert.Certificate[] rootChain = {rootCert};
496
rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(),
497
passwd.toCharArray(), rootChain);
498
499
// Now fire up the OCSP responder
500
rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null);
501
rootOcsp.enableLog(logging);
502
rootOcsp.setNextUpdateInterval(3600);
503
rootOcsp.start();
504
505
// Wait 5 seconds for server ready
506
for (int i = 0; (i < 100 && !rootOcsp.isServerReady()); i++) {
507
Thread.sleep(50);
508
}
509
if (!rootOcsp.isServerReady()) {
510
throw new RuntimeException("Server not ready yet");
511
}
512
513
rootOcspPort = rootOcsp.getPort();
514
String rootRespURI = "http://localhost:" + rootOcspPort;
515
log("Root OCSP Responder URI is " + rootRespURI);
516
517
// Now that we have the root keystore and OCSP responder we can
518
// create our intermediate CA.
519
cbld.reset();
520
cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany");
521
cbld.setPublicKey(intCaKP.getPublic());
522
cbld.setSerialNumber(new BigInteger("100"));
523
// Make a 2 year validity starting from 30 days ago
524
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30);
525
end = start + TimeUnit.DAYS.toMillis(730);
526
cbld.setValidity(new Date(start), new Date(end));
527
addCommonExts(cbld, intCaKP.getPublic(), rootCaKP.getPublic());
528
addCommonCAExts(cbld);
529
cbld.addAIAExt(Collections.singletonList(rootRespURI));
530
// Make our Intermediate CA Cert!
531
X509Certificate intCaCert = cbld.build(rootCert, rootCaKP.getPrivate(),
532
"SHA256withRSA");
533
log("Intermediate CA Created:\n" + certInfo(intCaCert));
534
535
// Provide intermediate CA cert revocation info to the Root CA
536
// OCSP responder.
537
Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =
538
new HashMap<>();
539
revInfo.put(intCaCert.getSerialNumber(),
540
new SimpleOCSPServer.CertStatusInfo(
541
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
542
rootOcsp.updateStatusDb(revInfo);
543
544
// Now build a keystore and add the keys, chain and root cert as a TA
545
intKeystore = keyStoreBuilder.getKeyStore();
546
java.security.cert.Certificate[] intChain = {intCaCert, rootCert};
547
intKeystore.setKeyEntry(INT_ALIAS, intCaKP.getPrivate(),
548
passwd.toCharArray(), intChain);
549
intKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
550
551
// Now fire up the Intermediate CA OCSP responder
552
intOcsp = new SimpleOCSPServer(intKeystore, passwd,
553
INT_ALIAS, null);
554
intOcsp.enableLog(logging);
555
intOcsp.setNextUpdateInterval(3600);
556
intOcsp.start();
557
558
// Wait 5 seconds for server ready
559
for (int i = 0; (i < 100 && !intOcsp.isServerReady()); i++) {
560
Thread.sleep(50);
561
}
562
if (!intOcsp.isServerReady()) {
563
throw new RuntimeException("Server not ready yet");
564
}
565
566
intOcspPort = intOcsp.getPort();
567
String intCaRespURI = "http://localhost:" + intOcspPort;
568
log("Intermediate CA OCSP Responder URI is " + intCaRespURI);
569
570
// Last but not least, let's make our SSLCert and add it to its own
571
// Keystore
572
cbld.reset();
573
cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany");
574
cbld.setPublicKey(sslKP.getPublic());
575
cbld.setSerialNumber(new BigInteger("4096"));
576
// Make a 1 year validity starting from 7 days ago
577
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);
578
end = start + TimeUnit.DAYS.toMillis(365);
579
cbld.setValidity(new Date(start), new Date(end));
580
581
// Add extensions
582
addCommonExts(cbld, sslKP.getPublic(), intCaKP.getPublic());
583
boolean[] kuBits = {true, false, true, false, false, false,
584
false, false, false};
585
cbld.addKeyUsageExt(kuBits);
586
List<String> ekuOids = new ArrayList<>();
587
ekuOids.add("1.3.6.1.5.5.7.3.1");
588
ekuOids.add("1.3.6.1.5.5.7.3.2");
589
cbld.addExtendedKeyUsageExt(ekuOids);
590
cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost"));
591
cbld.addAIAExt(Collections.singletonList(intCaRespURI));
592
// Make our SSL Server Cert!
593
X509Certificate sslCert = cbld.build(intCaCert, intCaKP.getPrivate(),
594
"SHA256withRSA");
595
log("SSL Certificate Created:\n" + certInfo(sslCert));
596
597
// Provide SSL server cert revocation info to the Intermeidate CA
598
// OCSP responder.
599
revInfo = new HashMap<>();
600
revInfo.put(sslCert.getSerialNumber(),
601
new SimpleOCSPServer.CertStatusInfo(
602
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
603
intOcsp.updateStatusDb(revInfo);
604
605
// Now build a keystore and add the keys, chain and root cert as a TA
606
serverKeystore = keyStoreBuilder.getKeyStore();
607
java.security.cert.Certificate[] sslChain = {sslCert, intCaCert, rootCert};
608
serverKeystore.setKeyEntry(SSL_ALIAS, sslKP.getPrivate(),
609
passwd.toCharArray(), sslChain);
610
serverKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
611
612
// And finally a Trust Store for the client
613
trustStore = keyStoreBuilder.getKeyStore();
614
trustStore.setCertificateEntry(ROOT_ALIAS, rootCert);
615
}
616
617
private static void addCommonExts(CertificateBuilder cbld,
618
PublicKey subjKey, PublicKey authKey) throws IOException {
619
cbld.addSubjectKeyIdExt(subjKey);
620
cbld.addAuthorityKeyIdExt(authKey);
621
}
622
623
private static void addCommonCAExts(CertificateBuilder cbld)
624
throws IOException {
625
cbld.addBasicConstraintsExt(true, true, -1);
626
// Set key usage bits for digitalSignature, keyCertSign and cRLSign
627
boolean[] kuBitSettings = {true, false, false, false, false, true,
628
true, false, false};
629
cbld.addKeyUsageExt(kuBitSettings);
630
}
631
632
/**
633
* Helper routine that dumps only a few cert fields rather than
634
* the whole toString() output.
635
*
636
* @param cert an X509Certificate to be displayed
637
*
638
* @return the String output of the issuer, subject and
639
* serial number
640
*/
641
private static String certInfo(X509Certificate cert) {
642
StringBuilder sb = new StringBuilder();
643
sb.append("Issuer: ").append(cert.getIssuerX500Principal()).
644
append("\n");
645
sb.append("Subject: ").append(cert.getSubjectX500Principal()).
646
append("\n");
647
sb.append("Serial: ").append(cert.getSerialNumber()).append("\n");
648
return sb.toString();
649
}
650
651
/**
652
* Checks a validation failure to see if it failed for the reason we think
653
* it should. This comes in as an SSLException of some sort, but it
654
* encapsulates a CertPathValidatorException at some point in the
655
* exception stack.
656
*
657
* @param e the exception thrown at the top level
658
* @param reason the underlying CertPathValidatorException BasicReason
659
* we are expecting it to have.
660
*
661
* @return true if the reason matches up, false otherwise.
662
*/
663
static boolean checkClientValidationFailure(Exception e,
664
CertPathValidatorException.BasicReason reason) {
665
boolean result = false;
666
667
// Locate the CertPathValidatorException. If one
668
// Does not exist, then it's an automatic failure of
669
// the test.
670
Throwable curExc = e;
671
CertPathValidatorException cpve = null;
672
while (curExc != null) {
673
if (curExc instanceof CertPathValidatorException) {
674
cpve = (CertPathValidatorException)curExc;
675
}
676
curExc = curExc.getCause();
677
}
678
679
// If we get through the loop and cpve is null then we
680
// we didn't find CPVE and this is a failure
681
if (cpve != null) {
682
if (cpve.getReason() == reason) {
683
result = true;
684
} else {
685
System.out.println("CPVE Reason Mismatch: Expected = " +
686
reason + ", Actual = " + cpve.getReason());
687
}
688
} else {
689
System.out.println("Failed to find an expected CPVE");
690
}
691
692
return result;
693
}
694
}
695
696