32032
|
1 |
/*
|
|
2 |
* Copyright (c) 2015, 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
|
|
30 |
* @summary OCSP Stapling for TLS
|
|
31 |
* @library ../../../../java/security/testlibrary
|
|
32 |
* @build CertificateBuilder SimpleOCSPServer
|
|
33 |
* @run main/othervm HttpsUrlConnClient
|
|
34 |
*/
|
|
35 |
|
|
36 |
import java.io.*;
|
|
37 |
import java.math.BigInteger;
|
|
38 |
import java.security.KeyPair;
|
|
39 |
import java.security.KeyPairGenerator;
|
|
40 |
import java.net.Socket;
|
|
41 |
import java.net.URL;
|
|
42 |
import java.net.HttpURLConnection;
|
|
43 |
import java.net.InetAddress;
|
|
44 |
import javax.net.ssl.*;
|
|
45 |
import java.security.KeyStore;
|
|
46 |
import java.security.PublicKey;
|
|
47 |
import java.security.Security;
|
|
48 |
import java.security.GeneralSecurityException;
|
|
49 |
import java.security.cert.CertPathValidatorException;
|
|
50 |
import java.security.cert.CertPathValidatorException.BasicReason;
|
|
51 |
import java.security.cert.Certificate;
|
|
52 |
import java.security.cert.PKIXBuilderParameters;
|
|
53 |
import java.security.cert.X509CertSelector;
|
|
54 |
import java.security.cert.X509Certificate;
|
|
55 |
import java.security.cert.PKIXRevocationChecker;
|
|
56 |
import java.security.spec.PKCS8EncodedKeySpec;
|
|
57 |
import java.text.SimpleDateFormat;
|
|
58 |
import java.util.*;
|
|
59 |
import java.util.concurrent.TimeUnit;
|
|
60 |
|
|
61 |
import sun.security.testlibrary.SimpleOCSPServer;
|
|
62 |
import sun.security.testlibrary.CertificateBuilder;
|
|
63 |
import sun.security.validator.ValidatorException;
|
|
64 |
|
|
65 |
public class HttpsUrlConnClient {
|
|
66 |
|
|
67 |
/*
|
|
68 |
* =============================================================
|
|
69 |
* Set the various variables needed for the tests, then
|
|
70 |
* specify what tests to run on each side.
|
|
71 |
*/
|
|
72 |
|
|
73 |
static final byte[] LINESEP = { 10 };
|
|
74 |
static final Base64.Encoder B64E = Base64.getMimeEncoder(64, LINESEP);
|
|
75 |
|
|
76 |
// Turn on TLS debugging
|
|
77 |
static boolean debug = true;
|
|
78 |
|
|
79 |
/*
|
|
80 |
* Should we run the client or server in a separate thread?
|
|
81 |
* Both sides can throw exceptions, but do you have a preference
|
|
82 |
* as to which side should be the main thread.
|
|
83 |
*/
|
|
84 |
static boolean separateServerThread = true;
|
|
85 |
Thread clientThread = null;
|
|
86 |
Thread serverThread = null;
|
|
87 |
|
|
88 |
static String passwd = "passphrase";
|
|
89 |
static String ROOT_ALIAS = "root";
|
|
90 |
static String INT_ALIAS = "intermediate";
|
|
91 |
static String SSL_ALIAS = "ssl";
|
|
92 |
|
|
93 |
/*
|
|
94 |
* Is the server ready to serve?
|
|
95 |
*/
|
|
96 |
volatile static boolean serverReady = false;
|
|
97 |
volatile int serverPort = 0;
|
|
98 |
|
|
99 |
volatile Exception serverException = null;
|
|
100 |
volatile Exception clientException = null;
|
|
101 |
|
|
102 |
// PKI components we will need for this test
|
|
103 |
static KeyStore rootKeystore; // Root CA Keystore
|
|
104 |
static KeyStore intKeystore; // Intermediate CA Keystore
|
|
105 |
static KeyStore serverKeystore; // SSL Server Keystore
|
|
106 |
static KeyStore trustStore; // SSL Client trust store
|
|
107 |
static SimpleOCSPServer rootOcsp; // Root CA OCSP Responder
|
|
108 |
static int rootOcspPort; // Port number for root OCSP
|
|
109 |
static SimpleOCSPServer intOcsp; // Intermediate CA OCSP Responder
|
|
110 |
static int intOcspPort; // Port number for intermed. OCSP
|
|
111 |
|
|
112 |
private static final String SIMPLE_WEB_PAGE = "<HTML>\n" +
|
|
113 |
"<HEAD><Title>Web Page!</Title></HEAD>\n" +
|
|
114 |
"<BODY><H1>Web Page!</H1></BODY>\n</HTML>";
|
|
115 |
private static final SimpleDateFormat utcDateFmt =
|
|
116 |
new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
|
|
117 |
/*
|
|
118 |
* If the client or server is doing some kind of object creation
|
|
119 |
* that the other side depends on, and that thread prematurely
|
|
120 |
* exits, you may experience a hang. The test harness will
|
|
121 |
* terminate all hung threads after its timeout has expired,
|
|
122 |
* currently 3 minutes by default, but you might try to be
|
|
123 |
* smart about it....
|
|
124 |
*/
|
|
125 |
public static void main(String[] args) throws Exception {
|
|
126 |
if (debug) {
|
|
127 |
System.setProperty("javax.net.debug", "ssl");
|
|
128 |
}
|
|
129 |
|
|
130 |
System.setProperty("javax.net.ssl.keyStore", "");
|
|
131 |
System.setProperty("javax.net.ssl.keyStorePassword", "");
|
|
132 |
System.setProperty("javax.net.ssl.trustStore", "");
|
|
133 |
System.setProperty("javax.net.ssl.trustStorePassword", "");
|
|
134 |
|
|
135 |
// Create the PKI we will use for the test and start the OCSP servers
|
|
136 |
createPKI();
|
|
137 |
utcDateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
|
|
138 |
|
|
139 |
testPKIXParametersRevEnabled();
|
|
140 |
|
|
141 |
// shut down the OCSP responders before finishing the test
|
|
142 |
intOcsp.stop();
|
|
143 |
rootOcsp.stop();
|
|
144 |
}
|
|
145 |
|
|
146 |
/**
|
|
147 |
* Do a basic connection using PKIXParameters with revocation checking
|
|
148 |
* enabled and client-side OCSP disabled. It will only pass if all
|
|
149 |
* stapled responses are present, valid and have a GOOD status.
|
|
150 |
*/
|
|
151 |
static void testPKIXParametersRevEnabled() throws Exception {
|
|
152 |
ClientParameters cliParams = new ClientParameters();
|
|
153 |
ServerParameters servParams = new ServerParameters();
|
|
154 |
serverReady = false;
|
|
155 |
|
|
156 |
System.out.println("=====================================");
|
|
157 |
System.out.println("Stapling enabled, PKIXParameters with");
|
|
158 |
System.out.println("Revocation checking enabled ");
|
|
159 |
System.out.println("=====================================");
|
|
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 |
// Set up revocation checking on the client with no client-side
|
|
175 |
// OCSP fall-back
|
|
176 |
cliParams.pkixParams = new PKIXBuilderParameters(trustStore,
|
|
177 |
new X509CertSelector());
|
|
178 |
cliParams.pkixParams.setRevocationEnabled(true);
|
|
179 |
Security.setProperty("ocsp.enable", "false");
|
|
180 |
|
|
181 |
HttpsUrlConnClient sslTest = new HttpsUrlConnClient(cliParams,
|
|
182 |
servParams);
|
|
183 |
TestResult tr = sslTest.getResult();
|
|
184 |
if (!checkClientValidationFailure(tr.clientExc, BasicReason.REVOKED)) {
|
|
185 |
if (tr.clientExc != null) {
|
|
186 |
throw tr.clientExc;
|
|
187 |
} else {
|
|
188 |
throw new RuntimeException(
|
|
189 |
"Expected client failure, but the client succeeded");
|
|
190 |
}
|
|
191 |
}
|
|
192 |
|
|
193 |
// In this case the server should also have thrown an exception
|
|
194 |
// because of the client alert
|
|
195 |
if (tr.serverExc instanceof SSLHandshakeException) {
|
|
196 |
if (!tr.serverExc.getMessage().contains(
|
|
197 |
"alert: bad_certificate_status_response")) {
|
|
198 |
throw tr.serverExc;
|
|
199 |
}
|
|
200 |
}
|
|
201 |
|
|
202 |
System.out.println(" PASS");
|
|
203 |
System.out.println("=====================================\n");
|
|
204 |
}
|
|
205 |
|
|
206 |
/*
|
|
207 |
* Define the server side of the test.
|
|
208 |
*
|
|
209 |
* If the server prematurely exits, serverReady will be set to true
|
|
210 |
* to avoid infinite hangs.
|
|
211 |
*/
|
|
212 |
void doServerSide(ServerParameters servParams) throws Exception {
|
|
213 |
|
|
214 |
// Selectively enable or disable the feature
|
|
215 |
System.setProperty("jdk.tls.server.enableStatusRequestExtension",
|
|
216 |
Boolean.toString(servParams.enabled));
|
|
217 |
|
|
218 |
// Set all the other operating parameters
|
|
219 |
System.setProperty("jdk.tls.stapling.cacheSize",
|
|
220 |
Integer.toString(servParams.cacheSize));
|
|
221 |
System.setProperty("jdk.tls.stapling.cacheLifetime",
|
|
222 |
Integer.toString(servParams.cacheLifetime));
|
|
223 |
System.setProperty("jdk.tls.stapling.responseTimeout",
|
|
224 |
Integer.toString(servParams.respTimeout));
|
|
225 |
System.setProperty("jdk.tls.stapling.responderURI", servParams.respUri);
|
|
226 |
System.setProperty("jdk.tls.stapling.responderOverride",
|
|
227 |
Boolean.toString(servParams.respOverride));
|
|
228 |
System.setProperty("jdk.tls.stapling.ignoreExtensions",
|
|
229 |
Boolean.toString(servParams.ignoreExts));
|
|
230 |
|
|
231 |
// Set keystores and trust stores for the server
|
|
232 |
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
|
|
233 |
kmf.init(serverKeystore, passwd.toCharArray());
|
|
234 |
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
|
|
235 |
tmf.init(trustStore);
|
|
236 |
|
|
237 |
SSLContext sslc = SSLContext.getInstance("TLS");
|
|
238 |
sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
|
|
239 |
|
|
240 |
SSLServerSocketFactory sslssf = sslc.getServerSocketFactory();
|
|
241 |
SSLServerSocket sslServerSocket =
|
|
242 |
(SSLServerSocket) sslssf.createServerSocket(serverPort);
|
|
243 |
|
|
244 |
serverPort = sslServerSocket.getLocalPort();
|
|
245 |
log("Server Port is " + serverPort);
|
|
246 |
|
|
247 |
// Dump the private key in PKCS8 format, not encrypted. This
|
|
248 |
// key dump can be used if the traffic was captured using tcpdump
|
|
249 |
// or wireshark to look into the encrypted packets for debug purposes.
|
|
250 |
if (debug) {
|
|
251 |
byte[] keybytes = serverKeystore.getKey(SSL_ALIAS,
|
|
252 |
passwd.toCharArray()).getEncoded();
|
|
253 |
PKCS8EncodedKeySpec p8spec = new PKCS8EncodedKeySpec(keybytes);
|
|
254 |
StringBuilder keyPem = new StringBuilder();
|
|
255 |
keyPem.append("-----BEGIN PRIVATE KEY-----\n");
|
|
256 |
keyPem.append(B64E.encodeToString(p8spec.getEncoded())).append("\n");
|
|
257 |
keyPem.append("-----END PRIVATE KEY-----\n");
|
|
258 |
log("Private key is:\n" + keyPem.toString());
|
|
259 |
}
|
|
260 |
|
|
261 |
/*
|
|
262 |
* Signal Client, we're ready for his connect.
|
|
263 |
*/
|
|
264 |
serverReady = true;
|
|
265 |
|
|
266 |
try (SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
|
|
267 |
BufferedReader in = new BufferedReader(
|
|
268 |
new InputStreamReader(sslSocket.getInputStream()));
|
|
269 |
OutputStream out = sslSocket.getOutputStream()) {
|
|
270 |
StringBuilder hdrBldr = new StringBuilder();
|
|
271 |
String line;
|
|
272 |
while ((line = in.readLine()) != null && !line.isEmpty()) {
|
|
273 |
hdrBldr.append(line).append("\n");
|
|
274 |
}
|
|
275 |
String headerText = hdrBldr.toString();
|
|
276 |
log("Header Received: " + headerText.length() + " bytes\n" +
|
|
277 |
headerText);
|
|
278 |
|
|
279 |
StringBuilder sb = new StringBuilder();
|
|
280 |
sb.append("HTTP/1.0 200 OK\r\n");
|
|
281 |
sb.append("Date: ").append(utcDateFmt.format(new Date())).
|
|
282 |
append("\r\n");
|
|
283 |
sb.append("Content-Type: text/html\r\n");
|
|
284 |
sb.append("Content-Length: ").append(SIMPLE_WEB_PAGE.length());
|
|
285 |
sb.append("\r\n\r\n");
|
|
286 |
out.write(sb.toString().getBytes("UTF-8"));
|
|
287 |
out.write(SIMPLE_WEB_PAGE.getBytes("UTF-8"));
|
|
288 |
out.flush();
|
|
289 |
log("Server replied with:\n" + sb.toString() + SIMPLE_WEB_PAGE);
|
|
290 |
}
|
|
291 |
}
|
|
292 |
|
|
293 |
/*
|
|
294 |
* Define the client side of the test.
|
|
295 |
*
|
|
296 |
* If the server prematurely exits, serverReady will be set to true
|
|
297 |
* to avoid infinite hangs.
|
|
298 |
*/
|
|
299 |
void doClientSide(ClientParameters cliParams) throws Exception {
|
|
300 |
|
|
301 |
/*
|
|
302 |
* Wait for server to get started.
|
|
303 |
*/
|
|
304 |
while (!serverReady) {
|
|
305 |
Thread.sleep(50);
|
|
306 |
}
|
|
307 |
|
|
308 |
// Selectively enable or disable the feature
|
|
309 |
System.setProperty("jdk.tls.client.enableStatusRequestExtension",
|
|
310 |
Boolean.toString(cliParams.enabled));
|
|
311 |
|
|
312 |
HtucSSLSocketFactory sockFac = new HtucSSLSocketFactory(cliParams);
|
|
313 |
HttpsURLConnection.setDefaultSSLSocketFactory(sockFac);
|
|
314 |
URL location = new URL("https://localhost:" + serverPort);
|
|
315 |
HttpsURLConnection tlsConn =
|
|
316 |
(HttpsURLConnection)location.openConnection();
|
|
317 |
tlsConn.setConnectTimeout(5000);
|
|
318 |
tlsConn.setReadTimeout(5000);
|
|
319 |
tlsConn.setDoInput(true);
|
|
320 |
|
|
321 |
try (InputStream in = tlsConn.getInputStream()) {
|
|
322 |
// Check the response
|
|
323 |
if (debug && tlsConn.getResponseCode() !=
|
|
324 |
HttpURLConnection.HTTP_OK) {
|
|
325 |
log("Received HTTP error: " + tlsConn.getResponseCode() +
|
|
326 |
" - " + tlsConn.getResponseMessage());
|
|
327 |
throw new IOException("HTTP error: " +
|
|
328 |
tlsConn.getResponseCode());
|
|
329 |
}
|
|
330 |
|
|
331 |
int contentLength = tlsConn.getContentLength();
|
|
332 |
if (contentLength == -1) {
|
|
333 |
contentLength = Integer.MAX_VALUE;
|
|
334 |
}
|
|
335 |
byte[] response = new byte[contentLength > 2048 ? 2048 : contentLength];
|
|
336 |
int total = 0;
|
|
337 |
while (total < contentLength) {
|
|
338 |
int count = in.read(response, total, response.length - total);
|
|
339 |
if (count < 0)
|
|
340 |
break;
|
|
341 |
|
|
342 |
total += count;
|
|
343 |
log("Read " + count + " bytes (" + total + " total)");
|
|
344 |
if (total >= response.length && total < contentLength) {
|
|
345 |
response = Arrays.copyOf(response, total * 2);
|
|
346 |
}
|
|
347 |
}
|
|
348 |
response = Arrays.copyOf(response, total);
|
|
349 |
String webPage = new String(response, 0, total);
|
|
350 |
if (debug) {
|
|
351 |
log("Web page:\n" + webPage);
|
|
352 |
}
|
|
353 |
}
|
|
354 |
}
|
|
355 |
|
|
356 |
/*
|
|
357 |
* Primary constructor, used to drive remainder of the test.
|
|
358 |
*
|
|
359 |
* Fork off the other side, then do your work.
|
|
360 |
*/
|
|
361 |
HttpsUrlConnClient(ClientParameters cliParams,
|
|
362 |
ServerParameters servParams) throws Exception {
|
|
363 |
Exception startException = null;
|
|
364 |
try {
|
|
365 |
if (separateServerThread) {
|
|
366 |
startServer(servParams, true);
|
|
367 |
startClient(cliParams, false);
|
|
368 |
} else {
|
|
369 |
startClient(cliParams, true);
|
|
370 |
startServer(servParams, false);
|
|
371 |
}
|
|
372 |
} catch (Exception e) {
|
|
373 |
startException = e;
|
|
374 |
}
|
|
375 |
|
|
376 |
/*
|
|
377 |
* Wait for other side to close down.
|
|
378 |
*/
|
|
379 |
if (separateServerThread) {
|
|
380 |
if (serverThread != null) {
|
|
381 |
serverThread.join();
|
|
382 |
}
|
|
383 |
} else {
|
|
384 |
if (clientThread != null) {
|
|
385 |
clientThread.join();
|
|
386 |
}
|
|
387 |
}
|
|
388 |
}
|
|
389 |
|
|
390 |
/**
|
|
391 |
* Checks a validation failure to see if it failed for the reason we think
|
|
392 |
* it should. This comes in as an SSLException of some sort, but it
|
|
393 |
* encapsulates a ValidatorException which in turn encapsulates the
|
|
394 |
* CertPathValidatorException we are interested in.
|
|
395 |
*
|
|
396 |
* @param e the exception thrown at the top level
|
|
397 |
* @param reason the underlying CertPathValidatorException BasicReason
|
|
398 |
* we are expecting it to have.
|
|
399 |
*
|
|
400 |
* @return true if the reason matches up, false otherwise.
|
|
401 |
*/
|
|
402 |
static boolean checkClientValidationFailure(Exception e,
|
|
403 |
BasicReason reason) {
|
|
404 |
boolean result = false;
|
|
405 |
|
|
406 |
if (e instanceof SSLException) {
|
|
407 |
Throwable valExc = e.getCause();
|
|
408 |
if (valExc instanceof sun.security.validator.ValidatorException) {
|
|
409 |
Throwable cause = valExc.getCause();
|
|
410 |
if (cause instanceof CertPathValidatorException) {
|
|
411 |
CertPathValidatorException cpve =
|
|
412 |
(CertPathValidatorException)cause;
|
|
413 |
if (cpve.getReason() == reason) {
|
|
414 |
result = true;
|
|
415 |
}
|
|
416 |
}
|
|
417 |
}
|
|
418 |
}
|
|
419 |
return result;
|
|
420 |
}
|
|
421 |
|
|
422 |
TestResult getResult() {
|
|
423 |
TestResult tr = new TestResult();
|
|
424 |
tr.clientExc = clientException;
|
|
425 |
tr.serverExc = serverException;
|
|
426 |
return tr;
|
|
427 |
}
|
|
428 |
|
|
429 |
final void startServer(ServerParameters servParams, boolean newThread)
|
|
430 |
throws Exception {
|
|
431 |
if (newThread) {
|
|
432 |
serverThread = new Thread() {
|
|
433 |
@Override
|
|
434 |
public void run() {
|
|
435 |
try {
|
|
436 |
doServerSide(servParams);
|
|
437 |
} catch (Exception e) {
|
|
438 |
/*
|
|
439 |
* Our server thread just died.
|
|
440 |
*
|
|
441 |
* Release the client, if not active already...
|
|
442 |
*/
|
|
443 |
System.err.println("Server died...");
|
|
444 |
serverReady = true;
|
|
445 |
serverException = e;
|
|
446 |
}
|
|
447 |
}
|
|
448 |
};
|
|
449 |
serverThread.start();
|
|
450 |
} else {
|
|
451 |
try {
|
|
452 |
doServerSide(servParams);
|
|
453 |
} catch (Exception e) {
|
|
454 |
serverException = e;
|
|
455 |
} finally {
|
|
456 |
serverReady = true;
|
|
457 |
}
|
|
458 |
}
|
|
459 |
}
|
|
460 |
|
|
461 |
final void startClient(ClientParameters cliParams, boolean newThread)
|
|
462 |
throws Exception {
|
|
463 |
if (newThread) {
|
|
464 |
clientThread = new Thread() {
|
|
465 |
@Override
|
|
466 |
public void run() {
|
|
467 |
try {
|
|
468 |
doClientSide(cliParams);
|
|
469 |
} catch (Exception e) {
|
|
470 |
/*
|
|
471 |
* Our client thread just died.
|
|
472 |
*/
|
|
473 |
System.err.println("Client died...");
|
|
474 |
clientException = e;
|
|
475 |
}
|
|
476 |
}
|
|
477 |
};
|
|
478 |
clientThread.start();
|
|
479 |
} else {
|
|
480 |
try {
|
|
481 |
doClientSide(cliParams);
|
|
482 |
} catch (Exception e) {
|
|
483 |
clientException = e;
|
|
484 |
}
|
|
485 |
}
|
|
486 |
}
|
|
487 |
|
|
488 |
/**
|
|
489 |
* Creates the PKI components necessary for this test, including
|
|
490 |
* Root CA, Intermediate CA and SSL server certificates, the keystores
|
|
491 |
* for each entity, a client trust store, and starts the OCSP responders.
|
|
492 |
*/
|
|
493 |
private static void createPKI() throws Exception {
|
|
494 |
CertificateBuilder cbld = new CertificateBuilder();
|
|
495 |
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
|
|
496 |
keyGen.initialize(2048);
|
|
497 |
KeyStore.Builder keyStoreBuilder =
|
|
498 |
KeyStore.Builder.newInstance("PKCS12", null,
|
|
499 |
new KeyStore.PasswordProtection(passwd.toCharArray()));
|
|
500 |
|
|
501 |
// Generate Root, IntCA, EE keys
|
|
502 |
KeyPair rootCaKP = keyGen.genKeyPair();
|
|
503 |
log("Generated Root CA KeyPair");
|
|
504 |
KeyPair intCaKP = keyGen.genKeyPair();
|
|
505 |
log("Generated Intermediate CA KeyPair");
|
|
506 |
KeyPair sslKP = keyGen.genKeyPair();
|
|
507 |
log("Generated SSL Cert KeyPair");
|
|
508 |
|
|
509 |
// Set up the Root CA Cert
|
|
510 |
cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany");
|
|
511 |
cbld.setPublicKey(rootCaKP.getPublic());
|
|
512 |
cbld.setSerialNumber(new BigInteger("1"));
|
|
513 |
// Make a 3 year validity starting from 60 days ago
|
|
514 |
long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60);
|
|
515 |
long end = start + TimeUnit.DAYS.toMillis(1085);
|
|
516 |
cbld.setValidity(new Date(start), new Date(end));
|
|
517 |
addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic());
|
|
518 |
addCommonCAExts(cbld);
|
|
519 |
// Make our Root CA Cert!
|
|
520 |
X509Certificate rootCert = cbld.build(null, rootCaKP.getPrivate(),
|
|
521 |
"SHA256withRSA");
|
|
522 |
log("Root CA Created:\n" + certInfo(rootCert));
|
|
523 |
|
|
524 |
// Now build a keystore and add the keys and cert
|
|
525 |
rootKeystore = keyStoreBuilder.getKeyStore();
|
|
526 |
Certificate[] rootChain = {rootCert};
|
|
527 |
rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(),
|
|
528 |
passwd.toCharArray(), rootChain);
|
|
529 |
|
|
530 |
// Now fire up the OCSP responder
|
|
531 |
rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null);
|
|
532 |
rootOcsp.enableLog(debug);
|
|
533 |
rootOcsp.setNextUpdateInterval(3600);
|
|
534 |
rootOcsp.start();
|
|
535 |
Thread.sleep(1000); // Give the server a second to start up
|
|
536 |
rootOcspPort = rootOcsp.getPort();
|
|
537 |
String rootRespURI = "http://localhost:" + rootOcspPort;
|
|
538 |
log("Root OCSP Responder URI is " + rootRespURI);
|
|
539 |
|
|
540 |
// Now that we have the root keystore and OCSP responder we can
|
|
541 |
// create our intermediate CA.
|
|
542 |
cbld.reset();
|
|
543 |
cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany");
|
|
544 |
cbld.setPublicKey(intCaKP.getPublic());
|
|
545 |
cbld.setSerialNumber(new BigInteger("100"));
|
|
546 |
// Make a 2 year validity starting from 30 days ago
|
|
547 |
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30);
|
|
548 |
end = start + TimeUnit.DAYS.toMillis(730);
|
|
549 |
cbld.setValidity(new Date(start), new Date(end));
|
|
550 |
addCommonExts(cbld, intCaKP.getPublic(), rootCaKP.getPublic());
|
|
551 |
addCommonCAExts(cbld);
|
|
552 |
cbld.addAIAExt(Collections.singletonList(rootRespURI));
|
|
553 |
// Make our Intermediate CA Cert!
|
|
554 |
X509Certificate intCaCert = cbld.build(rootCert, rootCaKP.getPrivate(),
|
|
555 |
"SHA256withRSA");
|
|
556 |
log("Intermediate CA Created:\n" + certInfo(intCaCert));
|
|
557 |
|
|
558 |
// Provide intermediate CA cert revocation info to the Root CA
|
|
559 |
// OCSP responder.
|
|
560 |
Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =
|
|
561 |
new HashMap<>();
|
|
562 |
revInfo.put(intCaCert.getSerialNumber(),
|
|
563 |
new SimpleOCSPServer.CertStatusInfo(
|
|
564 |
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
|
|
565 |
rootOcsp.updateStatusDb(revInfo);
|
|
566 |
|
|
567 |
// Now build a keystore and add the keys, chain and root cert as a TA
|
|
568 |
intKeystore = keyStoreBuilder.getKeyStore();
|
|
569 |
Certificate[] intChain = {intCaCert, rootCert};
|
|
570 |
intKeystore.setKeyEntry(INT_ALIAS, intCaKP.getPrivate(),
|
|
571 |
passwd.toCharArray(), intChain);
|
|
572 |
intKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
|
|
573 |
|
|
574 |
// Now fire up the Intermediate CA OCSP responder
|
|
575 |
intOcsp = new SimpleOCSPServer(intKeystore, passwd,
|
|
576 |
INT_ALIAS, null);
|
|
577 |
intOcsp.enableLog(debug);
|
|
578 |
intOcsp.setNextUpdateInterval(3600);
|
|
579 |
intOcsp.start();
|
|
580 |
Thread.sleep(1000);
|
|
581 |
intOcspPort = intOcsp.getPort();
|
|
582 |
String intCaRespURI = "http://localhost:" + intOcspPort;
|
|
583 |
log("Intermediate CA OCSP Responder URI is " + intCaRespURI);
|
|
584 |
|
|
585 |
// Last but not least, let's make our SSLCert and add it to its own
|
|
586 |
// Keystore
|
|
587 |
cbld.reset();
|
|
588 |
cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany");
|
|
589 |
cbld.setPublicKey(sslKP.getPublic());
|
|
590 |
cbld.setSerialNumber(new BigInteger("4096"));
|
|
591 |
// Make a 1 year validity starting from 7 days ago
|
|
592 |
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);
|
|
593 |
end = start + TimeUnit.DAYS.toMillis(365);
|
|
594 |
cbld.setValidity(new Date(start), new Date(end));
|
|
595 |
|
|
596 |
// Add extensions
|
|
597 |
addCommonExts(cbld, sslKP.getPublic(), intCaKP.getPublic());
|
|
598 |
boolean[] kuBits = {true, false, true, false, false, false,
|
|
599 |
false, false, false};
|
|
600 |
cbld.addKeyUsageExt(kuBits);
|
|
601 |
List<String> ekuOids = new ArrayList<>();
|
|
602 |
ekuOids.add("1.3.6.1.5.5.7.3.1");
|
|
603 |
ekuOids.add("1.3.6.1.5.5.7.3.2");
|
|
604 |
cbld.addExtendedKeyUsageExt(ekuOids);
|
|
605 |
cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost"));
|
|
606 |
cbld.addAIAExt(Collections.singletonList(intCaRespURI));
|
|
607 |
// Make our SSL Server Cert!
|
|
608 |
X509Certificate sslCert = cbld.build(intCaCert, intCaKP.getPrivate(),
|
|
609 |
"SHA256withRSA");
|
|
610 |
log("SSL Certificate Created:\n" + certInfo(sslCert));
|
|
611 |
|
|
612 |
// Provide SSL server cert revocation info to the Intermeidate CA
|
|
613 |
// OCSP responder.
|
|
614 |
revInfo = new HashMap<>();
|
|
615 |
revInfo.put(sslCert.getSerialNumber(),
|
|
616 |
new SimpleOCSPServer.CertStatusInfo(
|
|
617 |
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
|
|
618 |
intOcsp.updateStatusDb(revInfo);
|
|
619 |
|
|
620 |
// Now build a keystore and add the keys, chain and root cert as a TA
|
|
621 |
serverKeystore = keyStoreBuilder.getKeyStore();
|
|
622 |
Certificate[] sslChain = {sslCert, intCaCert, rootCert};
|
|
623 |
serverKeystore.setKeyEntry(SSL_ALIAS, sslKP.getPrivate(),
|
|
624 |
passwd.toCharArray(), sslChain);
|
|
625 |
serverKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
|
|
626 |
|
|
627 |
// And finally a Trust Store for the client
|
|
628 |
trustStore = keyStoreBuilder.getKeyStore();
|
|
629 |
trustStore.setCertificateEntry(ROOT_ALIAS, rootCert);
|
|
630 |
}
|
|
631 |
|
|
632 |
private static void addCommonExts(CertificateBuilder cbld,
|
|
633 |
PublicKey subjKey, PublicKey authKey) throws IOException {
|
|
634 |
cbld.addSubjectKeyIdExt(subjKey);
|
|
635 |
cbld.addAuthorityKeyIdExt(authKey);
|
|
636 |
}
|
|
637 |
|
|
638 |
private static void addCommonCAExts(CertificateBuilder cbld)
|
|
639 |
throws IOException {
|
|
640 |
cbld.addBasicConstraintsExt(true, true, -1);
|
|
641 |
// Set key usage bits for digitalSignature, keyCertSign and cRLSign
|
|
642 |
boolean[] kuBitSettings = {true, false, false, false, false, true,
|
|
643 |
true, false, false};
|
|
644 |
cbld.addKeyUsageExt(kuBitSettings);
|
|
645 |
}
|
|
646 |
|
|
647 |
/**
|
|
648 |
* Helper routine that dumps only a few cert fields rather than
|
|
649 |
* the whole toString() output.
|
|
650 |
*
|
|
651 |
* @param cert an X509Certificate to be displayed
|
|
652 |
*
|
|
653 |
* @return the String output of the issuer, subject and
|
|
654 |
* serial number
|
|
655 |
*/
|
|
656 |
private static String certInfo(X509Certificate cert) {
|
|
657 |
StringBuilder sb = new StringBuilder();
|
|
658 |
sb.append("Issuer: ").append(cert.getIssuerX500Principal()).
|
|
659 |
append("\n");
|
|
660 |
sb.append("Subject: ").append(cert.getSubjectX500Principal()).
|
|
661 |
append("\n");
|
|
662 |
sb.append("Serial: ").append(cert.getSerialNumber()).append("\n");
|
|
663 |
return sb.toString();
|
|
664 |
}
|
|
665 |
|
|
666 |
/**
|
|
667 |
* Log a message on stdout
|
|
668 |
*
|
|
669 |
* @param message The message to log
|
|
670 |
*/
|
|
671 |
private static void log(String message) {
|
|
672 |
if (debug) {
|
|
673 |
System.out.println(message);
|
|
674 |
}
|
|
675 |
}
|
|
676 |
|
|
677 |
// The following two classes are Simple nested class to group a handful
|
|
678 |
// of configuration parameters used before starting a client or server.
|
|
679 |
// We'll just access the data members directly for convenience.
|
|
680 |
static class ClientParameters {
|
|
681 |
boolean enabled = true;
|
|
682 |
PKIXBuilderParameters pkixParams = null;
|
|
683 |
PKIXRevocationChecker revChecker = null;
|
|
684 |
|
|
685 |
ClientParameters() { }
|
|
686 |
}
|
|
687 |
|
|
688 |
static class ServerParameters {
|
|
689 |
boolean enabled = true;
|
|
690 |
int cacheSize = 256;
|
|
691 |
int cacheLifetime = 3600;
|
|
692 |
int respTimeout = 5000;
|
|
693 |
String respUri = "";
|
|
694 |
boolean respOverride = false;
|
|
695 |
boolean ignoreExts = false;
|
|
696 |
|
|
697 |
ServerParameters() { }
|
|
698 |
}
|
|
699 |
|
|
700 |
static class TestResult {
|
|
701 |
Exception serverExc = null;
|
|
702 |
Exception clientExc = null;
|
|
703 |
}
|
|
704 |
|
|
705 |
static class HtucSSLSocketFactory extends SSLSocketFactory {
|
|
706 |
SSLContext sslc = SSLContext.getInstance("TLS");
|
|
707 |
|
|
708 |
HtucSSLSocketFactory(ClientParameters cliParams)
|
|
709 |
throws GeneralSecurityException {
|
|
710 |
super();
|
|
711 |
|
|
712 |
// Create the Trust Manager Factory using the PKIX variant
|
|
713 |
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
|
|
714 |
|
|
715 |
// If we have a customized pkixParameters then use it
|
|
716 |
if (cliParams.pkixParams != null) {
|
|
717 |
// LIf we have a customized PKIXRevocationChecker, add
|
|
718 |
// it to the PKIXBuilderParameters.
|
|
719 |
if (cliParams.revChecker != null) {
|
|
720 |
cliParams.pkixParams.addCertPathChecker(
|
|
721 |
cliParams.revChecker);
|
|
722 |
}
|
|
723 |
|
|
724 |
ManagerFactoryParameters trustParams =
|
|
725 |
new CertPathTrustManagerParameters(
|
|
726 |
cliParams.pkixParams);
|
|
727 |
tmf.init(trustParams);
|
|
728 |
} else {
|
|
729 |
tmf.init(trustStore);
|
|
730 |
}
|
|
731 |
|
|
732 |
sslc.init(null, tmf.getTrustManagers(), null);
|
|
733 |
}
|
|
734 |
|
|
735 |
@Override
|
|
736 |
public Socket createSocket(Socket s, String host, int port,
|
|
737 |
boolean autoClose) throws IOException {
|
|
738 |
Socket sock = sslc.getSocketFactory().createSocket(s, host, port,
|
|
739 |
autoClose);
|
|
740 |
setCiphers(sock);
|
|
741 |
return sock;
|
|
742 |
}
|
|
743 |
|
|
744 |
@Override
|
|
745 |
public Socket createSocket(InetAddress host, int port)
|
|
746 |
throws IOException {
|
|
747 |
Socket sock = sslc.getSocketFactory().createSocket(host, port);
|
|
748 |
setCiphers(sock);
|
|
749 |
return sock;
|
|
750 |
}
|
|
751 |
|
|
752 |
@Override
|
|
753 |
public Socket createSocket(InetAddress host, int port,
|
|
754 |
InetAddress localAddress, int localPort) throws IOException {
|
|
755 |
Socket sock = sslc.getSocketFactory().createSocket(host, port,
|
|
756 |
localAddress, localPort);
|
|
757 |
setCiphers(sock);
|
|
758 |
return sock;
|
|
759 |
}
|
|
760 |
|
|
761 |
@Override
|
|
762 |
public Socket createSocket(String host, int port)
|
|
763 |
throws IOException {
|
|
764 |
Socket sock = sslc.getSocketFactory().createSocket(host, port);
|
|
765 |
setCiphers(sock);
|
|
766 |
return sock;
|
|
767 |
}
|
|
768 |
|
|
769 |
@Override
|
|
770 |
public Socket createSocket(String host, int port,
|
|
771 |
InetAddress localAddress, int localPort)
|
|
772 |
throws IOException {
|
|
773 |
Socket sock = sslc.getSocketFactory().createSocket(host, port,
|
|
774 |
localAddress, localPort);
|
|
775 |
setCiphers(sock);
|
|
776 |
return sock;
|
|
777 |
}
|
|
778 |
|
|
779 |
@Override
|
|
780 |
public String[] getDefaultCipherSuites() {
|
|
781 |
return sslc.getDefaultSSLParameters().getCipherSuites();
|
|
782 |
}
|
|
783 |
|
|
784 |
@Override
|
|
785 |
public String[] getSupportedCipherSuites() {
|
|
786 |
return sslc.getSupportedSSLParameters().getCipherSuites();
|
|
787 |
}
|
|
788 |
|
|
789 |
private static void setCiphers(Socket sock) {
|
|
790 |
if (sock instanceof SSLSocket) {
|
|
791 |
String[] ciphers = { "TLS_RSA_WITH_AES_128_CBC_SHA" };
|
|
792 |
((SSLSocket)sock).setEnabledCipherSuites(ciphers);
|
|
793 |
}
|
|
794 |
}
|
|
795 |
}
|
|
796 |
|
|
797 |
}
|