Path: blob/master/test/jdk/javax/net/ssl/Stapling/HttpsUrlConnClient.java
66645 views
/*1* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223// SunJSSE does not support dynamic system properties, no way to re-use24// system properties in samevm/agentvm mode.2526/*27* @test28* @bug 8046321 815382929* @summary OCSP Stapling for TLS30* @library ../../../../java/security/testlibrary31* @build CertificateBuilder SimpleOCSPServer32* @run main/othervm HttpsUrlConnClient RSA SHA256withRSA33* @run main/othervm HttpsUrlConnClient RSASSA-PSS RSASSA-PSS34*/3536import java.io.*;37import java.math.BigInteger;38import java.security.KeyPair;39import java.security.KeyPairGenerator;40import java.net.Socket;41import java.net.URL;42import java.net.HttpURLConnection;43import java.net.InetAddress;44import javax.net.ssl.*;45import java.security.KeyStore;46import java.security.PublicKey;47import java.security.Security;48import java.security.GeneralSecurityException;49import java.security.cert.CertPathValidatorException;50import java.security.cert.CertPathValidatorException.BasicReason;51import java.security.cert.Certificate;52import java.security.cert.PKIXBuilderParameters;53import java.security.cert.X509CertSelector;54import java.security.cert.X509Certificate;55import java.security.cert.PKIXRevocationChecker;56import java.security.spec.PKCS8EncodedKeySpec;57import java.text.SimpleDateFormat;58import java.util.*;59import java.util.concurrent.TimeUnit;6061import sun.security.testlibrary.SimpleOCSPServer;62import sun.security.testlibrary.CertificateBuilder;6364public class HttpsUrlConnClient {6566/*67* =============================================================68* Set the various variables needed for the tests, then69* specify what tests to run on each side.70*/7172static final byte[] LINESEP = { 10 };73static final Base64.Encoder B64E = Base64.getMimeEncoder(64, LINESEP);7475static String SIGALG;76static String KEYALG;7778// Turn on TLS debugging79static boolean debug = true;8081/*82* Should we run the client or server in a separate thread?83* Both sides can throw exceptions, but do you have a preference84* as to which side should be the main thread.85*/86static boolean separateServerThread = true;87Thread clientThread = null;88Thread serverThread = null;8990static String passwd = "passphrase";91static String ROOT_ALIAS = "root";92static String INT_ALIAS = "intermediate";93static String SSL_ALIAS = "ssl";9495/*96* Is the server ready to serve?97*/98volatile static boolean serverReady = false;99volatile int serverPort = 0;100101volatile Exception serverException = null;102volatile Exception clientException = null;103104// PKI components we will need for this test105static KeyStore rootKeystore; // Root CA Keystore106static KeyStore intKeystore; // Intermediate CA Keystore107static KeyStore serverKeystore; // SSL Server Keystore108static KeyStore trustStore; // SSL Client trust store109static SimpleOCSPServer rootOcsp; // Root CA OCSP Responder110static int rootOcspPort; // Port number for root OCSP111static SimpleOCSPServer intOcsp; // Intermediate CA OCSP Responder112static int intOcspPort; // Port number for intermed. OCSP113114// Extra configuration parameters and constants115static final String[] TLS13ONLY = new String[] { "TLSv1.3" };116static final String[] TLS12MAX =117new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" };118119private static final String SIMPLE_WEB_PAGE = "<HTML>\n" +120"<HEAD><Title>Web Page!</Title></HEAD>\n" +121"<BODY><H1>Web Page!</H1></BODY>\n</HTML>";122private static final SimpleDateFormat utcDateFmt =123new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");124/*125* If the client or server is doing some kind of object creation126* that the other side depends on, and that thread prematurely127* exits, you may experience a hang. The test harness will128* terminate all hung threads after its timeout has expired,129* currently 3 minutes by default, but you might try to be130* smart about it....131*/132public static void main(String[] args) throws Exception {133if (debug) {134System.setProperty("javax.net.debug", "ssl:handshake");135}136137System.setProperty("javax.net.ssl.keyStore", "");138System.setProperty("javax.net.ssl.keyStorePassword", "");139System.setProperty("javax.net.ssl.trustStore", "");140System.setProperty("javax.net.ssl.trustStorePassword", "");141142KEYALG = args[0];143SIGALG = args[1];144145// Create the PKI we will use for the test and start the OCSP servers146createPKI();147utcDateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));148149testPKIXParametersRevEnabled(TLS12MAX);150testPKIXParametersRevEnabled(TLS13ONLY);151152// shut down the OCSP responders before finishing the test153intOcsp.stop();154rootOcsp.stop();155}156157/**158* Do a basic connection using PKIXParameters with revocation checking159* enabled and client-side OCSP disabled. It will only pass if all160* stapled responses are present, valid and have a GOOD status.161*/162static void testPKIXParametersRevEnabled(String[] allowedProts)163throws Exception {164ClientParameters cliParams = new ClientParameters();165cliParams.protocols = allowedProts;166ServerParameters servParams = new ServerParameters();167serverReady = false;168169System.out.println("=====================================");170System.out.println("Stapling enabled, PKIXParameters with");171System.out.println("Revocation checking enabled ");172System.out.println("=====================================");173174// Set the certificate entry in the intermediate OCSP responder175// with a revocation date of 8 hours ago.176X509Certificate sslCert =177(X509Certificate)serverKeystore.getCertificate(SSL_ALIAS);178Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =179new HashMap<>();180revInfo.put(sslCert.getSerialNumber(),181new SimpleOCSPServer.CertStatusInfo(182SimpleOCSPServer.CertStatus.CERT_STATUS_REVOKED,183new Date(System.currentTimeMillis() -184TimeUnit.HOURS.toMillis(8))));185intOcsp.updateStatusDb(revInfo);186187// Set up revocation checking on the client with no client-side188// OCSP fall-back189cliParams.pkixParams = new PKIXBuilderParameters(trustStore,190new X509CertSelector());191cliParams.pkixParams.setRevocationEnabled(true);192Security.setProperty("ocsp.enable", "false");193194HttpsUrlConnClient sslTest = new HttpsUrlConnClient(cliParams,195servParams);196TestResult tr = sslTest.getResult();197if (!checkClientValidationFailure(tr.clientExc, BasicReason.REVOKED)) {198if (tr.clientExc != null) {199throw tr.clientExc;200} else {201throw new RuntimeException(202"Expected client failure, but the client succeeded");203}204}205206// In this case the server should also have thrown an exception207// because of the client alert208if (tr.serverExc instanceof SSLHandshakeException) {209if (!tr.serverExc.getMessage().contains(210"bad_certificate_status_response")) {211throw tr.serverExc;212}213}214215System.out.println(" PASS");216System.out.println("=====================================\n");217}218219/*220* Define the server side of the test.221*222* If the server prematurely exits, serverReady will be set to true223* to avoid infinite hangs.224*/225void doServerSide(ServerParameters servParams) throws Exception {226227// Selectively enable or disable the feature228System.setProperty("jdk.tls.server.enableStatusRequestExtension",229Boolean.toString(servParams.enabled));230231// Set all the other operating parameters232System.setProperty("jdk.tls.stapling.cacheSize",233Integer.toString(servParams.cacheSize));234System.setProperty("jdk.tls.stapling.cacheLifetime",235Integer.toString(servParams.cacheLifetime));236System.setProperty("jdk.tls.stapling.responseTimeout",237Integer.toString(servParams.respTimeout));238System.setProperty("jdk.tls.stapling.responderURI", servParams.respUri);239System.setProperty("jdk.tls.stapling.responderOverride",240Boolean.toString(servParams.respOverride));241System.setProperty("jdk.tls.stapling.ignoreExtensions",242Boolean.toString(servParams.ignoreExts));243244// Set keystores and trust stores for the server245KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");246kmf.init(serverKeystore, passwd.toCharArray());247TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");248tmf.init(trustStore);249250SSLContext sslc = SSLContext.getInstance("TLS");251sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);252253SSLServerSocketFactory sslssf = sslc.getServerSocketFactory();254SSLServerSocket sslServerSocket =255(SSLServerSocket) sslssf.createServerSocket(serverPort);256257serverPort = sslServerSocket.getLocalPort();258log("Server Port is " + serverPort);259260// Dump the private key in PKCS8 format, not encrypted. This261// key dump can be used if the traffic was captured using tcpdump262// or wireshark to look into the encrypted packets for debug purposes.263if (debug) {264byte[] keybytes = serverKeystore.getKey(SSL_ALIAS,265passwd.toCharArray()).getEncoded();266PKCS8EncodedKeySpec p8spec = new PKCS8EncodedKeySpec(keybytes);267StringBuilder keyPem = new StringBuilder();268keyPem.append("-----BEGIN PRIVATE KEY-----\n");269keyPem.append(B64E.encodeToString(p8spec.getEncoded())).append("\n");270keyPem.append("-----END PRIVATE KEY-----\n");271log("Private key is:\n" + keyPem.toString());272}273274/*275* Signal Client, we're ready for his connect.276*/277serverReady = true;278279try (SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();280BufferedReader in = new BufferedReader(281new InputStreamReader(sslSocket.getInputStream()));282OutputStream out = sslSocket.getOutputStream()) {283StringBuilder hdrBldr = new StringBuilder();284String line;285while ((line = in.readLine()) != null && !line.isEmpty()) {286hdrBldr.append(line).append("\n");287}288String headerText = hdrBldr.toString();289log("Header Received: " + headerText.length() + " bytes\n" +290headerText);291292StringBuilder sb = new StringBuilder();293sb.append("HTTP/1.0 200 OK\r\n");294sb.append("Date: ").append(utcDateFmt.format(new Date())).295append("\r\n");296sb.append("Content-Type: text/html\r\n");297sb.append("Content-Length: ").append(SIMPLE_WEB_PAGE.length());298sb.append("\r\n\r\n");299out.write(sb.toString().getBytes("UTF-8"));300out.write(SIMPLE_WEB_PAGE.getBytes("UTF-8"));301out.flush();302log("Server replied with:\n" + sb.toString() + SIMPLE_WEB_PAGE);303}304}305306/*307* Define the client side of the test.308*309* If the server prematurely exits, serverReady will be set to true310* to avoid infinite hangs.311*/312void doClientSide(ClientParameters cliParams) throws Exception {313314// Wait 5 seconds for server ready315for (int i = 0; (i < 100 && !serverReady); i++) {316Thread.sleep(50);317}318if (!serverReady) {319throw new RuntimeException("Server not ready yet");320}321322// Selectively enable or disable the feature323System.setProperty("jdk.tls.client.enableStatusRequestExtension",324Boolean.toString(cliParams.enabled));325326HtucSSLSocketFactory sockFac = new HtucSSLSocketFactory(cliParams);327HttpsURLConnection.setDefaultSSLSocketFactory(sockFac);328URL location = new URL("https://localhost:" + serverPort);329HttpsURLConnection tlsConn =330(HttpsURLConnection)location.openConnection();331tlsConn.setConnectTimeout(5000);332tlsConn.setReadTimeout(5000);333tlsConn.setDoInput(true);334335try (InputStream in = tlsConn.getInputStream()) {336// Check the response337if (debug && tlsConn.getResponseCode() !=338HttpURLConnection.HTTP_OK) {339log("Received HTTP error: " + tlsConn.getResponseCode() +340" - " + tlsConn.getResponseMessage());341throw new IOException("HTTP error: " +342tlsConn.getResponseCode());343}344345int contentLength = tlsConn.getContentLength();346if (contentLength == -1) {347contentLength = Integer.MAX_VALUE;348}349byte[] response = new byte[contentLength > 2048 ? 2048 :350contentLength];351int total = 0;352while (total < contentLength) {353int count = in.read(response, total, response.length - total);354if (count < 0)355break;356357total += count;358log("Read " + count + " bytes (" + total + " total)");359if (total >= response.length && total < contentLength) {360response = Arrays.copyOf(response, total * 2);361}362}363response = Arrays.copyOf(response, total);364String webPage = new String(response, 0, total);365if (debug) {366log("Web page:\n" + webPage);367}368}369}370371/*372* Primary constructor, used to drive remainder of the test.373*374* Fork off the other side, then do your work.375*/376HttpsUrlConnClient(ClientParameters cliParams,377ServerParameters servParams) throws Exception {378Exception startException = null;379try {380if (separateServerThread) {381startServer(servParams, true);382startClient(cliParams, false);383} else {384startClient(cliParams, true);385startServer(servParams, false);386}387} catch (Exception e) {388startException = e;389}390391/*392* Wait for other side to close down.393*/394if (separateServerThread) {395if (serverThread != null) {396serverThread.join();397}398} else {399if (clientThread != null) {400clientThread.join();401}402}403}404405/**406* Checks a validation failure to see if it failed for the reason we think407* it should. This comes in as an SSLException of some sort, but it408* encapsulates a CertPathValidatorException at some point in the409* exception stack.410*411* @param e the exception thrown at the top level412* @param reason the underlying CertPathValidatorException BasicReason413* we are expecting it to have.414*415* @return true if the reason matches up, false otherwise.416*/417static boolean checkClientValidationFailure(Exception e,418BasicReason reason) {419boolean result = false;420421// Locate the CertPathValidatorException. If one422// Does not exist, then it's an automatic failure of423// the test.424Throwable curExc = e;425CertPathValidatorException cpve = null;426while (curExc != null) {427if (curExc instanceof CertPathValidatorException) {428cpve = (CertPathValidatorException)curExc;429}430curExc = curExc.getCause();431}432433// If we get through the loop and cpve is null then we434// we didn't find CPVE and this is a failure435if (cpve != null) {436if (cpve.getReason() == reason) {437result = true;438} else {439System.out.println("CPVE Reason Mismatch: Expected = " +440reason + ", Actual = " + cpve.getReason());441}442} else {443System.out.println("Failed to find an expected CPVE");444}445446return result;447}448449TestResult getResult() {450TestResult tr = new TestResult();451tr.clientExc = clientException;452tr.serverExc = serverException;453return tr;454}455456final void startServer(ServerParameters servParams, boolean newThread)457throws Exception {458if (newThread) {459serverThread = new Thread() {460@Override461public void run() {462try {463doServerSide(servParams);464} catch (Exception e) {465/*466* Our server thread just died.467*468* Release the client, if not active already...469*/470System.err.println("Server died...");471serverReady = true;472serverException = e;473}474}475};476serverThread.start();477} else {478try {479doServerSide(servParams);480} catch (Exception e) {481serverException = e;482} finally {483serverReady = true;484}485}486}487488final void startClient(ClientParameters cliParams, boolean newThread)489throws Exception {490if (newThread) {491clientThread = new Thread() {492@Override493public void run() {494try {495doClientSide(cliParams);496} catch (Exception e) {497/*498* Our client thread just died.499*/500System.err.println("Client died...");501clientException = e;502}503}504};505clientThread.start();506} else {507try {508doClientSide(cliParams);509} catch (Exception e) {510clientException = e;511}512}513}514515/**516* Creates the PKI components necessary for this test, including517* Root CA, Intermediate CA and SSL server certificates, the keystores518* for each entity, a client trust store, and starts the OCSP responders.519*/520private static void createPKI() throws Exception {521CertificateBuilder cbld = new CertificateBuilder();522KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEYALG);523keyGen.initialize(2048);524KeyStore.Builder keyStoreBuilder =525KeyStore.Builder.newInstance("PKCS12", null,526new KeyStore.PasswordProtection(passwd.toCharArray()));527528// Generate Root, IntCA, EE keys529KeyPair rootCaKP = keyGen.genKeyPair();530log("Generated Root CA KeyPair");531KeyPair intCaKP = keyGen.genKeyPair();532log("Generated Intermediate CA KeyPair");533KeyPair sslKP = keyGen.genKeyPair();534log("Generated SSL Cert KeyPair");535536// Set up the Root CA Cert537cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany");538cbld.setPublicKey(rootCaKP.getPublic());539cbld.setSerialNumber(new BigInteger("1"));540// Make a 3 year validity starting from 60 days ago541long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60);542long end = start + TimeUnit.DAYS.toMillis(1085);543cbld.setValidity(new Date(start), new Date(end));544addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic());545addCommonCAExts(cbld);546// Make our Root CA Cert!547X509Certificate rootCert = cbld.build(null, rootCaKP.getPrivate(),548SIGALG);549log("Root CA Created:\n" + certInfo(rootCert));550551// Now build a keystore and add the keys and cert552rootKeystore = keyStoreBuilder.getKeyStore();553Certificate[] rootChain = {rootCert};554rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(),555passwd.toCharArray(), rootChain);556557// Now fire up the OCSP responder558rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null);559rootOcsp.enableLog(debug);560rootOcsp.setNextUpdateInterval(3600);561rootOcsp.start();562563// Wait 5 seconds for server ready564for (int i = 0; (i < 100 && !rootOcsp.isServerReady()); i++) {565Thread.sleep(50);566}567if (!rootOcsp.isServerReady()) {568throw new RuntimeException("Server not ready yet");569}570571rootOcspPort = rootOcsp.getPort();572String rootRespURI = "http://localhost:" + rootOcspPort;573log("Root OCSP Responder URI is " + rootRespURI);574575// Now that we have the root keystore and OCSP responder we can576// create our intermediate CA.577cbld.reset();578cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany");579cbld.setPublicKey(intCaKP.getPublic());580cbld.setSerialNumber(new BigInteger("100"));581// Make a 2 year validity starting from 30 days ago582start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30);583end = start + TimeUnit.DAYS.toMillis(730);584cbld.setValidity(new Date(start), new Date(end));585addCommonExts(cbld, intCaKP.getPublic(), rootCaKP.getPublic());586addCommonCAExts(cbld);587cbld.addAIAExt(Collections.singletonList(rootRespURI));588// Make our Intermediate CA Cert!589X509Certificate intCaCert = cbld.build(rootCert, rootCaKP.getPrivate(),590SIGALG);591log("Intermediate CA Created:\n" + certInfo(intCaCert));592593// Provide intermediate CA cert revocation info to the Root CA594// OCSP responder.595Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =596new HashMap<>();597revInfo.put(intCaCert.getSerialNumber(),598new SimpleOCSPServer.CertStatusInfo(599SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));600rootOcsp.updateStatusDb(revInfo);601602// Now build a keystore and add the keys, chain and root cert as a TA603intKeystore = keyStoreBuilder.getKeyStore();604Certificate[] intChain = {intCaCert, rootCert};605intKeystore.setKeyEntry(INT_ALIAS, intCaKP.getPrivate(),606passwd.toCharArray(), intChain);607intKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);608609// Now fire up the Intermediate CA OCSP responder610intOcsp = new SimpleOCSPServer(intKeystore, passwd,611INT_ALIAS, null);612intOcsp.enableLog(debug);613intOcsp.setNextUpdateInterval(3600);614intOcsp.start();615616// Wait 5 seconds for server ready617for (int i = 0; (i < 100 && !intOcsp.isServerReady()); i++) {618Thread.sleep(50);619}620if (!intOcsp.isServerReady()) {621throw new RuntimeException("Server not ready yet");622}623624intOcspPort = intOcsp.getPort();625String intCaRespURI = "http://localhost:" + intOcspPort;626log("Intermediate CA OCSP Responder URI is " + intCaRespURI);627628// Last but not least, let's make our SSLCert and add it to its own629// Keystore630cbld.reset();631cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany");632cbld.setPublicKey(sslKP.getPublic());633cbld.setSerialNumber(new BigInteger("4096"));634// Make a 1 year validity starting from 7 days ago635start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);636end = start + TimeUnit.DAYS.toMillis(365);637cbld.setValidity(new Date(start), new Date(end));638639// Add extensions640addCommonExts(cbld, sslKP.getPublic(), intCaKP.getPublic());641boolean[] kuBits = {true, false, true, false, false, false,642false, false, false};643cbld.addKeyUsageExt(kuBits);644List<String> ekuOids = new ArrayList<>();645ekuOids.add("1.3.6.1.5.5.7.3.1");646ekuOids.add("1.3.6.1.5.5.7.3.2");647cbld.addExtendedKeyUsageExt(ekuOids);648cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost"));649cbld.addAIAExt(Collections.singletonList(intCaRespURI));650// Make our SSL Server Cert!651X509Certificate sslCert = cbld.build(intCaCert, intCaKP.getPrivate(),652SIGALG);653log("SSL Certificate Created:\n" + certInfo(sslCert));654655// Provide SSL server cert revocation info to the Intermeidate CA656// OCSP responder.657revInfo = new HashMap<>();658revInfo.put(sslCert.getSerialNumber(),659new SimpleOCSPServer.CertStatusInfo(660SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));661intOcsp.updateStatusDb(revInfo);662663// Now build a keystore and add the keys, chain and root cert as a TA664serverKeystore = keyStoreBuilder.getKeyStore();665Certificate[] sslChain = {sslCert, intCaCert, rootCert};666serverKeystore.setKeyEntry(SSL_ALIAS, sslKP.getPrivate(),667passwd.toCharArray(), sslChain);668serverKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);669670// And finally a Trust Store for the client671trustStore = keyStoreBuilder.getKeyStore();672trustStore.setCertificateEntry(ROOT_ALIAS, rootCert);673}674675private static void addCommonExts(CertificateBuilder cbld,676PublicKey subjKey, PublicKey authKey) throws IOException {677cbld.addSubjectKeyIdExt(subjKey);678cbld.addAuthorityKeyIdExt(authKey);679}680681private static void addCommonCAExts(CertificateBuilder cbld)682throws IOException {683cbld.addBasicConstraintsExt(true, true, -1);684// Set key usage bits for digitalSignature, keyCertSign and cRLSign685boolean[] kuBitSettings = {true, false, false, false, false, true,686true, false, false};687cbld.addKeyUsageExt(kuBitSettings);688}689690/**691* Helper routine that dumps only a few cert fields rather than692* the whole toString() output.693*694* @param cert an X509Certificate to be displayed695*696* @return the String output of the issuer, subject and697* serial number698*/699private static String certInfo(X509Certificate cert) {700StringBuilder sb = new StringBuilder();701sb.append("Issuer: ").append(cert.getIssuerX500Principal()).702append("\n");703sb.append("Subject: ").append(cert.getSubjectX500Principal()).704append("\n");705sb.append("Serial: ").append(cert.getSerialNumber()).append("\n");706return sb.toString();707}708709/**710* Log a message on stdout711*712* @param message The message to log713*/714private static void log(String message) {715if (debug) {716System.out.println(message);717}718}719720// The following two classes are Simple nested class to group a handful721// of configuration parameters used before starting a client or server.722// We'll just access the data members directly for convenience.723static class ClientParameters {724boolean enabled = true;725PKIXBuilderParameters pkixParams = null;726PKIXRevocationChecker revChecker = null;727String[] protocols = null;728String[] cipherSuites = null;729730ClientParameters() { }731}732733static class ServerParameters {734boolean enabled = true;735int cacheSize = 256;736int cacheLifetime = 3600;737int respTimeout = 5000;738String respUri = "";739boolean respOverride = false;740boolean ignoreExts = false;741742ServerParameters() { }743}744745static class TestResult {746Exception serverExc = null;747Exception clientExc = null;748749@Override750public String toString() {751StringBuilder sb = new StringBuilder();752sb.append("Test Result:\n").753append("\tServer Exc = ").append(serverExc).append("\n").754append("\tClient Exc = ").append(clientExc).append("\n");755return sb.toString();756}757}758759static class HtucSSLSocketFactory extends SSLSocketFactory {760ClientParameters params;761SSLContext sslc = SSLContext.getInstance("TLS");762763HtucSSLSocketFactory(ClientParameters cliParams)764throws GeneralSecurityException {765super();766767// Create the Trust Manager Factory using the PKIX variant768TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");769770// If we have a customized pkixParameters then use it771if (cliParams.pkixParams != null) {772// LIf we have a customized PKIXRevocationChecker, add773// it to the PKIXBuilderParameters.774if (cliParams.revChecker != null) {775cliParams.pkixParams.addCertPathChecker(776cliParams.revChecker);777}778779ManagerFactoryParameters trustParams =780new CertPathTrustManagerParameters(781cliParams.pkixParams);782tmf.init(trustParams);783} else {784tmf.init(trustStore);785}786787sslc.init(null, tmf.getTrustManagers(), null);788params = cliParams;789}790791@Override792public Socket createSocket(Socket s, String host, int port,793boolean autoClose) throws IOException {794Socket sock = sslc.getSocketFactory().createSocket(s, host, port,795autoClose);796customizeSocket(sock);797return sock;798}799800@Override801public Socket createSocket(InetAddress host, int port)802throws IOException {803Socket sock = sslc.getSocketFactory().createSocket(host, port);804customizeSocket(sock);805return sock;806}807808@Override809public Socket createSocket(InetAddress host, int port,810InetAddress localAddress, int localPort) throws IOException {811Socket sock = sslc.getSocketFactory().createSocket(host, port,812localAddress, localPort);813customizeSocket(sock);814return sock;815}816817@Override818public Socket createSocket(String host, int port)819throws IOException {820Socket sock = sslc.getSocketFactory().createSocket(host, port);821customizeSocket(sock);822return sock;823}824825@Override826public Socket createSocket(String host, int port,827InetAddress localAddress, int localPort)828throws IOException {829Socket sock = sslc.getSocketFactory().createSocket(host, port,830localAddress, localPort);831customizeSocket(sock);832return sock;833}834835@Override836public String[] getDefaultCipherSuites() {837return sslc.getDefaultSSLParameters().getCipherSuites();838}839840@Override841public String[] getSupportedCipherSuites() {842return sslc.getSupportedSSLParameters().getCipherSuites();843}844845private void customizeSocket(Socket sock) {846if (sock instanceof SSLSocket) {847SSLSocket sslSock = (SSLSocket)sock;848if (params.protocols != null) {849sslSock.setEnabledProtocols(params.protocols);850}851if (params.cipherSuites != null) {852sslSock.setEnabledCipherSuites(params.cipherSuites);853}854}855}856}857858}859860861