Mercurial > hg > openjdk > jdk8u > jdk
changeset 14144:6c6e8ab540a1
8245653: Remove 8u TLS tests
Reviewed-by: mbalao
author | abakhtin |
---|---|
date | Tue, 25 Aug 2020 18:03:27 +0300 |
parents | 3ec03c289ff2 |
children | a39036fa30bb |
files | test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java test/javax/net/ssl/FixingJavadocs/ComURLNulls.java test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java test/javax/net/ssl/SSLEngine/Arrays.java test/javax/net/ssl/SSLEngine/CheckStatus.java test/javax/net/ssl/SSLEngine/ConnectionTest.java test/javax/net/ssl/SSLEngine/ExtendedKeyEngine.java test/javax/net/ssl/SSLEngine/IllegalRecordVersion.java test/javax/net/ssl/SSLEngine/LargeBufs.java test/javax/net/ssl/SSLEngine/NoAuthClientAuth.java test/javax/net/ssl/SSLSession/SessionCacheSizeTests.java test/javax/net/ssl/SSLSession/SessionTimeOutTests.java test/javax/net/ssl/SSLSession/testEnabledProtocols.java test/javax/net/ssl/ServerName/SSLSocketExplorerFailure.java test/javax/net/ssl/ServerName/SSLSocketSNISensitive.java test/javax/net/ssl/TLS/CipherTestUtils.java test/javax/net/ssl/TLS/JSSEClient.java test/javax/net/ssl/TLS/JSSEServer.java test/javax/net/ssl/TLS/TLSClientPropertyTest.java test/javax/net/ssl/TLS/TestJSSE.java test/javax/net/ssl/TLSv11/ExportableBlockCipher.java test/javax/net/ssl/TLSv11/ExportableStreamCipher.java test/javax/net/ssl/TLSv12/DisabledShortDSAKeys.java test/javax/net/ssl/TLSv12/DisabledShortRSAKeys.java test/javax/net/ssl/TLSv12/ShortRSAKey512.java test/javax/net/ssl/TLSv12/ShortRSAKeyGCM.java test/javax/net/ssl/TLSv12/SignatureAlgorithms.java test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java test/javax/net/ssl/ciphersuites/ECCurvesconstraints.java test/javax/net/ssl/etc/README test/javax/net/ssl/etc/keystore test/javax/net/ssl/etc/truststore test/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java test/javax/net/ssl/sanity/ciphersuites/CipherSuitesInOrder.java test/javax/net/ssl/sanity/interop/CipherTest.java test/javax/net/ssl/sanity/interop/ClientJSSEServerJSSE.java test/javax/net/ssl/sanity/interop/JSSEClient.java test/javax/net/ssl/sanity/interop/JSSEServer.java test/javax/net/ssl/templates/SSLEngineTemplate.java test/javax/net/ssl/templates/SSLSocketSSLEngineTemplate.java test/javax/net/ssl/templates/SSLSocketTemplate.java test/sun/net/www/protocol/https/HttpsClient/OriginServer.java test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java test/sun/net/www/protocol/https/HttpsURLConnection/DNSIdentities.java test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressDNSIdentities.java test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressIPIdentities.java test/sun/net/www/protocol/https/HttpsURLConnection/IPIdentities.java test/sun/net/www/protocol/https/HttpsURLConnection/Identities.java test/sun/net/www/protocol/https/HttpsURLConnection/ReadTimeout.java test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java test/sun/net/www/protocol/https/NewImpl/ComHostnameVerifier.java test/sun/security/pkcs11/sslecc/CipherTest.java test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java test/sun/security/pkcs11/sslecc/JSSEClient.java test/sun/security/pkcs11/sslecc/JSSEServer.java test/sun/security/ssl/AppInputStream/ReadBlocksClose.java test/sun/security/ssl/AppInputStream/ReadHandshake.java test/sun/security/ssl/AppOutputStream/NoExceptionOnClose.java test/sun/security/ssl/CertPathRestrictions/JSSEServer.java test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java test/sun/security/ssl/CipherSuite/SSL_NULL.java test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java test/sun/security/ssl/DHKeyExchange/LegacyDHEKeyExchange.java test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.sh test/sun/security/ssl/GenSSLConfigs/main.java test/sun/security/ssl/HandshakeOutStream/NullCerts.java test/sun/security/ssl/InputRecord/SSLSocketTimeoutNulls.java test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java test/sun/security/ssl/SSLContextImpl/CustomizedDefaultProtocols.java test/sun/security/ssl/SSLContextImpl/DefaultEnabledProtocols.java test/sun/security/ssl/SSLContextImpl/MD2InTrustAnchor.java test/sun/security/ssl/SSLContextImpl/NoOldVersionContext.java test/sun/security/ssl/SSLContextImpl/TrustTrustedCert.java test/sun/security/ssl/SSLEngineImpl/CloseEngineException.java test/sun/security/ssl/SSLEngineImpl/CloseInboundException.java test/sun/security/ssl/SSLEngineImpl/CloseStart.java test/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java test/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java test/sun/security/ssl/SSLEngineImpl/SSLEngineBadBufferArrayAccess.java test/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java test/sun/security/ssl/SSLSocketImpl/AsyncSSLSocketClose.java test/sun/security/ssl/SSLSocketImpl/CheckMethods.java test/sun/security/ssl/SSLSocketImpl/ClientTimeout.java test/sun/security/ssl/SSLSocketImpl/InvalidateServerSessionRenegotiate.java test/sun/security/ssl/SSLSocketImpl/NoImpactServerRenego.java test/sun/security/ssl/SSLSocketImpl/NonAutoClose.java test/sun/security/ssl/SSLSocketImpl/RejectClientRenego.java test/sun/security/ssl/SSLSocketImpl/SSLSocketImplThrowsWrongExceptions.java test/sun/security/ssl/SSLSocketImpl/SetClientMode.java test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java test/sun/security/ssl/ServerHandshaker/GetPeerHostClient.java test/sun/security/ssl/SessionIdCollisionTest.java test/sun/security/ssl/SocketCreation/SocketCreation.java test/sun/security/ssl/X509TrustManagerImpl/BasicConstraints.java test/sun/security/ssl/X509TrustManagerImpl/CertRequestOverflow.java test/sun/security/ssl/X509TrustManagerImpl/ClientServer.java test/sun/security/ssl/X509TrustManagerImpl/SelfIssuedCert.java test/sun/security/ssl/X509TrustManagerImpl/Symantec/Distrust.java test/sun/security/ssl/templates/SSLSocketTemplate.java |
diffstat | 102 files changed, 1 insertions(+), 30749 deletions(-) [+] |
line wrap: on
line diff
--- a/test/javax/net/ssl/ALPN/SSLEngineAlpnTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,583 +0,0 @@ -/* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 8051498 8145849 8170282 - * @summary JEP 244: TLS Application-Layer Protocol Negotiation Extension - * @compile MyX509ExtendedKeyManager.java - * - * @run main/othervm SSLEngineAlpnTest h2 UNUSED h2 h2 - * @run main/othervm SSLEngineAlpnTest h2 UNUSED h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 UNUSED h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest http/1.1,h2 UNUSED h2,http/1.1 http/1.1 - * @run main/othervm SSLEngineAlpnTest h4,h3,h2 UNUSED h1,h2 h2 - * @run main/othervm SSLEngineAlpnTest EMPTY UNUSED h2,http/1.1 NONE - * @run main/othervm SSLEngineAlpnTest h2 UNUSED EMPTY NONE - * @run main/othervm SSLEngineAlpnTest H2 UNUSED h2 ERROR - * @run main/othervm SSLEngineAlpnTest h2 UNUSED http/1.1 ERROR - * - * @run main/othervm SSLEngineAlpnTest UNUSED h2 h2 h2 - * @run main/othervm SSLEngineAlpnTest UNUSED h2 h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest UNUSED h2 http/1.1,h2 h2 - * @run main/othervm SSLEngineAlpnTest UNUSED http/1.1 h2,http/1.1 http/1.1 - * @run main/othervm SSLEngineAlpnTest UNUSED EMPTY h2,http/1.1 NONE - * @run main/othervm SSLEngineAlpnTest UNUSED h2 EMPTY NONE - * @run main/othervm SSLEngineAlpnTest UNUSED H2 h2 ERROR - * @run main/othervm SSLEngineAlpnTest UNUSED h2 http/1.1 ERROR - * - * @run main/othervm SSLEngineAlpnTest h2 h2 h2 h2 - * @run main/othervm SSLEngineAlpnTest H2 h2 h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 http/1.1 h2,http/1.1 http/1.1 - * @run main/othervm SSLEngineAlpnTest http/1.1,h2 h2 h2,http/1.1 h2 - * @run main/othervm SSLEngineAlpnTest EMPTY h2 h2 h2 - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 EMPTY http/1.1 NONE - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 h2 EMPTY NONE - * @run main/othervm SSLEngineAlpnTest UNUSED UNUSED http/1.1,h2 NONE - * @run main/othervm SSLEngineAlpnTest h2 h2 http/1.1 ERROR - * @run main/othervm SSLEngineAlpnTest h2,http/1.1 H2 http/1.1 ERROR - */ -/** - * A simple SSLEngine-based client/server that demonstrates the proposed API - * changes for JEP 244 in support of the TLS ALPN extension (RFC 7301). - * - * Usage: - * java SSLEngineAlpnTest <server-APs> <callback-AP> <client-APs> <result> - * - * where: - * EMPTY indicates that ALPN is disabled - * UNUSED indicates that no ALPN values are supplied (server-side only) - * ERROR indicates that an exception is expected - * NONE indicates that no ALPN is expected - * - * This example is based on our standard SSLEngineTemplate. - * - * The immediate consumer of ALPN will be HTTP/2 (RFC 7540), aka H2. The H2 IETF - * Working Group wanted to use TLSv1.3+ as the secure transport mechanism, but - * TLSv1.3 wasn't ready. The H2 folk agreed to a compromise that only TLSv1.2+ - * can be used, and that if TLSv1.2 was selected, non-TLSv.1.3-approved - * ciphersuites would be blacklisted and their use discouraged. - * - * In order to support connections that might negotiate either HTTP/1.1 and H2, - * the guidance from the IETF Working Group is that the H2 ciphersuites be - * prioritized/tried first. - */ - -/* - * The original SSLEngineTemplate comments follow. - * - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - */ -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -import java.util.Arrays; - -public class SSLEngineAlpnTest { - - /* - * Enables logging of the SSLEngine operations. - */ - private static final boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static final boolean debug = false; - - private static boolean hasServerAPs; // whether server APs are present - private static boolean hasCallback; // whether a callback is present - - private final SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static final String pathToStores = "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename - = System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + keyStoreFile; - private static final String trustFilename - = System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - System.out.println("Test args: " + Arrays.toString(args)); - - // Validate parameters - if (args.length != 4) { - throw new Exception("Invalid number of test parameters"); - } - - hasServerAPs = !args[0].equals("UNUSED"); // are server APs being used? - hasCallback = !args[1].equals("UNUSED"); // is callback being used? - - SSLEngineAlpnTest test = new SSLEngineAlpnTest(args[3]); - try { - test.runTest(convert(args[0]), args[1], convert(args[2]), args[3]); - } catch (SSLHandshakeException she) { - if (args[3].equals("ERROR")) { - System.out.println("Caught the expected exception: " + she); - } else { - throw she; - } - } - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public SSLEngineAlpnTest(String expectedAP) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - KeyManager [] kms = kmf.getKeyManagers(); - if (!(kms[0] instanceof X509ExtendedKeyManager)) { - throw new Exception("kms[0] not X509ExtendedKeyManager"); - } - - kms = new KeyManager[] { new MyX509ExtendedKeyManager( - (X509ExtendedKeyManager) kms[0], expectedAP, - !hasCallback && hasServerAPs) }; - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kms, tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Convert a comma-separated list into an array of strings. - */ - private static String[] convert(String list) { - if (list.equals("UNUSED")) { - return null; - } - - if (list.equals("EMPTY")) { - return new String[0]; - } - - String[] strings; - if (list.indexOf(',') > 0) { - strings = list.split(","); - } else { - strings = new String[]{ list }; - } - - return strings; - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest(String[] serverAPs, String callbackAP, - String[] clientAPs, String expectedAP) throws Exception { - - boolean dataDone = false; - - createSSLEngines(serverAPs, callbackAP, clientAPs); - createBuffers(); - - SSLEngineResult clientResult; // results from client's last operation - SSLEngineResult serverResult; // results from server's last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - while (!isEngineClosed(clientEngine) - || !isEngineClosed(serverEngine)) { - - log("================"); - - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - checkAPResult(clientEngine, clientResult, expectedAP); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - checkAPResult(serverEngine, serverResult, expectedAP); - - cTOs.flip(); - sTOc.flip(); - - log("----"); - - clientResult = clientEngine.unwrap(sTOc, clientIn); - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - checkAPResult(clientEngine, clientResult, expectedAP); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - checkAPResult(serverEngine, serverResult, expectedAP); - - cTOs.compact(); - sTOc.compact(); - - /* - * After we've transfered all application data between the client - * and server, we close the clientEngine's outbound stream. - * This generates a close_notify handshake message, which the - * server engine receives and responds by closing itself. - */ - if (!dataDone && (clientOut.limit() == serverIn.position()) - && (serverOut.limit() == clientIn.position())) { - - /* - * A sanity check to ensure we got what was sent. - */ - checkTransfer(serverOut, clientIn); - checkTransfer(clientOut, serverIn); - - log("\tClosing clientEngine's *OUTBOUND*..."); - clientEngine.closeOutbound(); - dataDone = true; - } - } - } - - /* - * Check that the resulting connection meets our defined ALPN - * criteria. If we were connecting to a non-JSSE implementation, - * the server might have negotiated something we shouldn't accept. - * - * If we were expecting an ALPN value from server, let's make sure - * the conditions match. - */ - private static void checkAPResult(SSLEngine engine, SSLEngineResult result, - String expectedAP) throws Exception { - - if (result.getHandshakeStatus() != HandshakeStatus.FINISHED) { - return; - } - - if (engine.getHandshakeApplicationProtocol() != null) { - throw new Exception ("getHandshakeApplicationProtocol() should " - + "return null after the handshake is completed"); - } - - String ap = engine.getApplicationProtocol(); - System.out.println("Application Protocol: \"" + ap + "\""); - - if (ap == null) { - throw new Exception( - "Handshake was completed but null was received"); - } - if (expectedAP.equals("NONE")) { - if (!ap.isEmpty()) { - throw new Exception("Expected no ALPN value"); - } else { - System.out.println("No ALPN value negotiated, as expected"); - } - } else if (!expectedAP.equals(ap)) { - throw new Exception(expectedAP + - " ALPN value not available on negotiated connection"); - } - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines(String[] serverAPs, String callbackAP, - String[] clientAPs) throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - - SSLParameters sslp = serverEngine.getSSLParameters(); - - sslp.setNeedClientAuth(true); - - /* - * The default ciphersuite ordering from the SSLContext may not - * reflect "h2" ciphersuites as being preferred, additionally the - * client may not send them in an appropriate order. We could resort - * the suite list if so desired. - */ - String[] suites = sslp.getCipherSuites(); - sslp.setCipherSuites(suites); - if (serverAPs != null) { - sslp.setApplicationProtocols(serverAPs); - } - sslp.setUseCipherSuitesOrder(true); // Set server side order - - serverEngine.setSSLParameters(sslp); - - // check that no callback has been registered - if (serverEngine.getHandshakeApplicationProtocolSelector() != null) { - throw new Exception("getHandshakeApplicationProtocolSelector() " + - "should return null"); - } - - if (hasCallback) { - serverEngine.setHandshakeApplicationProtocolSelector( - (sslEngine, clientProtocols) -> { - return callbackAP.equals("EMPTY") ? "" : callbackAP; - }); - - // check that the callback can be retrieved - if (serverEngine.getHandshakeApplicationProtocolSelector() - == null) { - throw new Exception("getHandshakeApplicationProtocolSelector()" - + " should return non-null"); - } - } - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - sslp = clientEngine.getSSLParameters(); - if (clientAPs != null) { - sslp.setApplicationProtocols(clientAPs); - } - clientEngine.setSSLParameters(sslp); - - if ((clientEngine.getHandshakeApplicationProtocol() != null) || - (serverEngine.getHandshakeApplicationProtocol() != null)) { - throw new Exception ("getHandshakeApplicationProtocol() should " - + "return null before the handshake starts"); - } - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" - + "\t\"getStatus() / getHandshakeStatus()\" +\n" - + "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str - + result.getStatus() + "/" + hsStatus + ", " - + result.bytesConsumed() + "/" + result.bytesProduced() - + " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/FixingJavadocs/ComURLNulls.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4387882 4451038 - * @summary Need to revisit the javadocs for JSSE, especially the - * promoted classes, and HttpsURLConnection.getCipherSuite throws - * NullPointerException - * @run main/othervm ComURLNulls - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.net.*; -import java.io.*; -import javax.net.ssl.*; -import com.sun.net.ssl.HttpsURLConnection; -import com.sun.net.ssl.HostnameVerifier; - -/* - * Tests that the com null argument changes made it in ok. - */ - -public class ComURLNulls { - - public static void main(String[] args) throws Exception { - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - System.setProperty("java.protocol.handler.pkgs", - "com.sun.net.ssl.internal.www.protocol"); - /** - * This test does not establish any connection to the specified - * URL, hence a dummy URL is used. - */ - URL foobar = new URL("https://example.com/"); - - HttpsURLConnection urlc = - (HttpsURLConnection) foobar.openConnection(); - - try { - urlc.getCipherSuite(); - } catch (IllegalStateException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.getServerCertificateChain(); - } catch (IllegalStateException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setDefaultHostnameVerifier(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setHostnameVerifier(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setDefaultSSLSocketFactory(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - urlc.setSSLSocketFactory(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception"); - System.out.println(e.getMessage()); - } - System.out.println("TESTS PASSED"); - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } -}
--- a/test/javax/net/ssl/FixingJavadocs/SSLSessionNulls.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4387882 - * @summary Need to revisit the javadocs for JSSE, especially the - * promoted classes. - * @run main/othervm SSLSessionNulls - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class SSLSessionNulls { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - SSLSession sslSession = sslSocket.getSession(); - - try { - sslSession.getValue(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - sslSession.putValue(null, null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - try { - sslSession.removeValue(null); - } catch (IllegalArgumentException e) { - System.out.print("Caught proper exception: "); - System.out.println(e.getMessage()); - } - - String [] names = sslSession.getValueNames(); - if ((names == null) || (names.length != 0)) { - throw new IOException( - "getValueNames didn't return 0-length arrary"); - } - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SSLSessionNulls(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSessionNulls() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/javax/net/ssl/SSLEngine/Arrays.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,294 +0,0 @@ -/* - * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 5019096 - * @summary Add scatter/gather APIs for SSLEngine - * - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class Arrays { - - private static boolean debug = false; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer [] appOutArray1; - private ByteBuffer [] appInArray1; - - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - } - - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - log("================"); - - result1 = ssle1.wrap(appOutArray1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); - log(""); - - log("wrap2: " + result2); - log("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - log("----"); - - result1 = ssle1.unwrap(twoToOne, appInArray1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); - log(""); - - log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!dataDone) { - boolean done = true; - - for (int i = 0; i < appOutArray1.length; i++) { - if (appOutArray1[i].remaining() != 0) { - done = false; - } - } - - if (appOut2.remaining() != 0) { - done = false; - } - - if (done) { - log("Closing ssle1's *OUTBOUND*..."); - for (int i = 0; i < appOutArray1.length; i++) { - appOutArray1[i].rewind(); - } - ssle1.closeOutbound(); - dataDone = true; - } - } - } - checkTransfer(appOutArray1, appIn2); - appInArray1[appInArray1.length - 1].limit( - appInArray1[appInArray1.length - 1].position()); - checkTransfer(appInArray1, appOut2); - } - - public static void main(String args[]) throws Exception { - - Arrays test; - - test = new Arrays(); - - test.createSSLEngines(); - - test.runTest(); - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public Arrays() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - ByteBuffer strBB = ByteBuffer.wrap( - "Hi Engine2, I'm SSLEngine1, So Be it" .getBytes()); - - strBB.position(0); - strBB.limit(5); - ByteBuffer appOut1a = strBB.slice(); - - strBB.position(5); - strBB.limit(15); - ByteBuffer appOut1b = strBB.slice(); - - strBB.position(15); - strBB.limit(strBB.capacity()); - ByteBuffer appOut1c = strBB.slice(); - - strBB.rewind(); - - appOutArray1 = new ByteBuffer [] { appOut1a, appOut1b, appOut1c }; - - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - ByteBuffer appIn1a = ByteBuffer.allocateDirect(5); - ByteBuffer appIn1b = ByteBuffer.allocateDirect(10); - ByteBuffer appIn1c = ByteBuffer.allocateDirect(appBufferMax + 50); - appInArray1 = new ByteBuffer [] { appIn1a, appIn1b, appIn1c }; - - log("AppOut1a = " + appOut1a); - log("AppOut1a = " + appOut1b); - log("AppOut1a = " + appOut1c); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer [] a, ByteBuffer b) - throws Exception { - - b.flip(); - - for (int i = 0; i < a.length; i++) { - a[i].rewind(); - - b.limit(b.position() + a[i].remaining()); - - if (!a[i].equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } - - b.position(b.limit()); - } - - log("Data transferred cleanly"); - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/SSLEngine/CheckStatus.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,729 +0,0 @@ -/* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4948079 - * @summary SSLEngineResult needs updating [none yet] - * - * This is a simple hack to test a bunch of conditions and check - * their return codes. - * - * @run main/othervm -Djsse.enableCBCProtection=false CheckStatus - * - * @author Brad Wetmore - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class CheckStatus { - - private static boolean debug = true; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine("server", 2); - ssle2.setUseClientMode(false); - } - - private boolean isHandshaking(SSLEngine e) { - return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING); - } - - private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut, - SSLEngineResult result, - Status status, HandshakeStatus hsStatus, - int consumed, int produced) - throws Exception { - - if ((status != null) && (result.getStatus() != status)) { - throw new Exception("Unexpected Status: need = " + status + - " got = " + result.getStatus()); - } - - if ((hsStatus != null) && (result.getHandshakeStatus() != hsStatus)) { - throw new Exception("Unexpected hsStatus: need = " + hsStatus + - " got = " + result.getHandshakeStatus()); - } - - if ((consumed != -1) && (consumed != result.bytesConsumed())) { - throw new Exception("Unexpected consumed: need = " + consumed + - " got = " + result.bytesConsumed()); - } - - if ((produced != -1) && (produced != result.bytesProduced())) { - throw new Exception("Unexpected produced: need = " + produced + - " got = " + result.bytesProduced()); - } - - if ((consumed != -1) && (bbIn.position() != result.bytesConsumed())) { - throw new Exception("Consumed " + bbIn.position() + - " != " + consumed); - } - - if ((produced != -1) && (bbOut.position() != result.bytesProduced())) { - throw new Exception("produced " + bbOut.position() + - " != " + produced); - } - } - - private void test() throws Exception { - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - String [] suite1 = new String [] { - "SSL_RSA_WITH_RC4_128_MD5" }; - String [] suite2 = new String [] { - "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA" }; - - ssle1.setEnabledCipherSuites(suite1); - ssle2.setEnabledCipherSuites(suite1); - - log("================"); - - log("unexpected empty unwrap"); - twoToOne.limit(0); - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, 0); - twoToOne.limit(twoToOne.capacity()); - - log("======================================"); - log("client hello"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - - oneToTwo.compact(); - - log("Check for unwrap when wrap needed"); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_WRAP, 0, 0); - - log("======================================"); - log("ServerHello"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0); - twoToOne.compact(); - - runDelegatedTasks(ssle1); - - log("======================================"); - log("Key Exchange"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - - oneToTwo.compact(); - - log("======================================"); - log("CCS"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, - result1.bytesProduced(), 0); - - oneToTwo.compact(); - - log("======================================"); - log("Finished"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_WRAP, result1.bytesProduced(), 0); - - oneToTwo.compact(); - - log("======================================"); - log("CCS"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("======================================"); - log("FINISHED"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.FINISHED, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("======================================"); - log("Check Session/Ciphers"); - - String suite = ssle1.getSession().getCipherSuite(); - if (!suite.equals(suite1[0])) { - throw new Exception("suites not equal: " + suite + "/" + - suite1[0]); - } - - suite = ssle2.getSession().getCipherSuite(); - if (!suite.equals(suite1[0])) { - throw new Exception("suites not equal: " + suite + "/" + - suite1[0]); - } - - log("======================================"); - log("DATA"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut1.capacity(), -1); - oneToTwo.flip(); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut2.capacity(), -1); - twoToOne.flip(); - - SSLEngineResult result3 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result3, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - result2.bytesProduced(), result2.bytesConsumed()); - twoToOne.compact(); - - SSLEngineResult result4 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result4, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - result1.bytesProduced(), result1.bytesConsumed()); - oneToTwo.compact(); - - appIn1.clear(); - appIn2.clear(); - appOut1.rewind(); - appOut2.rewind(); - - log("======================================"); - log("RENEGOTIATE"); - - ssle2.getSession().invalidate(); - ssle2.setNeedClientAuth(true); - - ssle1.setEnabledCipherSuites(suite2); - ssle2.setEnabledCipherSuites(suite2); - - ssle2.beginHandshake(); - - log("======================================"); - log("HelloRequest"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0); - twoToOne.compact(); - - runDelegatedTasks(ssle1); - - log("======================================"); - log("ClientHello"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - - oneToTwo.compact(); - - log("======================================"); - log("CLIENT->SERVER DATA IN MIDDLE OF HANDSHAKE"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, - appOut1.capacity(), -1); - oneToTwo.flip(); - - result4 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result4, - Status.OK, HandshakeStatus.NEED_WRAP, - result1.bytesProduced(), result1.bytesConsumed()); - oneToTwo.compact(); - - appIn2.clear(); - appOut1.rewind(); - - log("======================================"); - log("ServerHello"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0); - twoToOne.compact(); - - runDelegatedTasks(ssle1); - - log("======================================"); - log("SERVER->CLIENT DATA IN MIDDLE OF HANDSHAKE"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, - appOut2.capacity(), -1); - twoToOne.flip(); - - result3 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result3, - Status.OK, HandshakeStatus.NEED_WRAP, - result2.bytesProduced(), result2.bytesConsumed()); - twoToOne.compact(); - - appIn1.clear(); - appOut2.rewind(); - - log("======================================"); - log("Client Cert"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - - oneToTwo.compact(); - - log("======================================"); - log("Key Exchange"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, - result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - - oneToTwo.compact(); - - log("======================================"); - log("CCS"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, - result1.bytesProduced(), 0); - - oneToTwo.compact(); - - log("======================================"); - log("Finished"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_WRAP, result1.bytesProduced(), 0); - - oneToTwo.compact(); - - log("======================================"); - log("CCS"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("======================================"); - log("FINISHED"); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.FINISHED, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("======================================"); - log("Check Session/Ciphers"); - - suite = ssle1.getSession().getCipherSuite(); - if (!suite.equals(suite2[0])) { - throw new Exception("suites not equal: " + suite + "/" + - suite2[0]); - } - - suite = ssle2.getSession().getCipherSuite(); - if (!suite.equals(suite2[0])) { - throw new Exception("suites not equal: " + suite + "/" + - suite2[0]); - } - - log("======================================"); - log("DATA USING NEW SESSION"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut1.capacity(), -1); - oneToTwo.flip(); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut2.capacity(), -1); - twoToOne.flip(); - - result3 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result3, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - result2.bytesProduced(), result2.bytesConsumed()); - twoToOne.compact(); - - result4 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result4, - Status.OK, HandshakeStatus.NOT_HANDSHAKING, - result1.bytesProduced(), result1.bytesConsumed()); - oneToTwo.compact(); - - appIn1.clear(); - appIn2.clear(); - appOut1.rewind(); - appOut2.rewind(); - - log("======================================"); - log("CN"); - - if (isHandshaking(ssle1)) { - throw new Exception("ssle1 IS handshaking"); - } - - if (isHandshaking(ssle2)) { - throw new Exception("ssle2 IS handshaking"); - } - - ssle2.closeOutbound(); - - if (!isHandshaking(ssle2)) { - throw new Exception("ssle1 IS NOT handshaking"); - } - - appOut1.rewind(); - appOut2.rewind(); - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.CLOSED, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); - - if (ssle1.isInboundDone()) { - throw new Exception("ssle1 inboundDone"); - } - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.CLOSED, HandshakeStatus.NEED_WRAP, - result2.bytesProduced(), 0); - twoToOne.compact(); - - if (!ssle1.isInboundDone()) { - throw new Exception("ssle1 inboundDone"); - } - - if (!isHandshaking(ssle1)) { - throw new Exception("ssle1 IS NOT handshaking"); - } - - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.CLOSED, HandshakeStatus.NEED_UNWRAP, 0, 0); - twoToOne.flip(); - - log("======================================"); - log("CN response"); - - if (ssle1.isOutboundDone()) { - throw new Exception("ssle1 outboundDone"); - } - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, 0, -1); - - if (!ssle1.isOutboundDone()) { - throw new Exception("ssle1 outboundDone is NOT done"); - } - - if (isHandshaking(ssle1)) { - throw new Exception("ssle1 IS handshaking"); - } - - oneToTwo.flip(); - - if (!ssle2.isOutboundDone()) { - throw new Exception("ssle1 outboundDone"); - } - - if (ssle2.isInboundDone()) { - throw new Exception("ssle1 inboundDone"); - } - - result2 = ssle2.unwrap(oneToTwo, appIn2); - - checkResult(oneToTwo, appIn2, result2, - Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - result1.bytesProduced(), 0); - - if (!ssle2.isOutboundDone()) { - throw new Exception("ssle1 outboundDone is NOT done"); - } - - if (!ssle2.isInboundDone()) { - throw new Exception("ssle1 inboundDone is NOT done"); - } - - if (isHandshaking(ssle2)) { - throw new Exception("ssle1 IS handshaking"); - } - - oneToTwo.compact(); - } - - public static void main(String args[]) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - CheckStatus cs; - - cs = new CheckStatus(); - - cs.createSSLEngines(); - - cs.test(); - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public CheckStatus() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngine engine) throws Exception { - - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/SSLEngine/ConnectionTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,684 +0,0 @@ -/* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4495742 - * @summary Add non-blocking SSL/TLS functionality, usable with any - * I/O abstraction - * - * This is a bit hacky, meant to test various conditions. The main - * thing I wanted to do with this was to do buffer reads/writes - * when buffers were not empty. (buffer.position() = 10) - * The code could certainly be tightened up a lot. - * - * @author Brad Wetmore - * - * @run main/othervm ConnectionTest - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class ConnectionTest { - - private SSLContext sslc; - private SSLEngine ssle1; - private SSLEngine ssle2; - - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appIn1, appOut1; - private ByteBuffer appIn2, appOut2; - private ByteBuffer oneToTwo, twoToOne; - private ByteBuffer emptyBuffer; - - private ByteBuffer oneToTwoShifter, twoToOneShifter; - - private String hostname = "hostname"; - private int portNumber = 77; - - public ConnectionTest() - throws Exception { - - sslc = getSSLContext(); - ssle1 = sslc.createSSLEngine(hostname, portNumber); - ssle2 = sslc.createSSLEngine(); - - ssle1.setEnabledCipherSuites(new String [] { - "SSL_RSA_WITH_RC4_128_MD5"}); - - ssle2.setEnabledCipherSuites(new String [] { - "SSL_RSA_WITH_RC4_128_MD5"}); - - createBuffers(); - } - - private SSLContext getSSLContext() throws Exception { - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 10); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 10); - - appIn1.position(10); - appIn2.position(10); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax + 10); - twoToOne = ByteBuffer.allocateDirect(netBufferMax + 10); - - oneToTwo.position(10); - twoToOne.position(10); - oneToTwoShifter = oneToTwo.slice(); - twoToOneShifter = twoToOne.slice(); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - emptyBuffer = ByteBuffer.allocate(10); - emptyBuffer.limit(5); - emptyBuffer.position(emptyBuffer.limit()); - - System.out.println("AppOut1 = " + appOut1); - System.out.println("AppOut2 = " + appOut2); - System.out.println(); - } - - private void checkResult(SSLEngineResult result, Status status, - HandshakeStatus hsStatus, int consumed, int produced, - boolean done) throws Exception { - - if ((status != null) && (result.getStatus() != status)) { - throw new Exception("Unexpected Status: need = " + status + - " got = " + result.getStatus()); - } - - if ((hsStatus != null) && (result.getHandshakeStatus() != hsStatus)) { - throw new Exception("Unexpected hsStatus: need = " + hsStatus + - " got = " + result.getHandshakeStatus()); - } - - if ((consumed != -1) && (consumed != result.bytesConsumed())) { - throw new Exception("Unexpected consumed: need = " + consumed + - " got = " + result.bytesConsumed()); - } - - if ((produced != -1) && (produced != result.bytesProduced())) { - throw new Exception("Unexpected produced: need = " + produced + - " got = " + result.bytesProduced()); - } - - if (done && (hsStatus == HandshakeStatus.FINISHED)) { - throw new Exception( - "Handshake already reported finished"); - } - - } - - private boolean isHandshaking(SSLEngine e) { - return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING); - } - - private void test() throws Exception { - ssle1.setUseClientMode(true); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - - System.out.println("Testing for early unwrap/wrap"); - SSLEngineResult result1 = ssle1.unwrap(twoToOne, appIn1); - SSLEngineResult result2 = ssle2.wrap(appOut2, oneToTwo); - - /* - * These should not consume/produce data, because they - * are client and server, respectively, and don't - * start handshaking this way. - */ - checkResult(result1, Status.OK, HandshakeStatus.NEED_WRAP, - 0, 0, false); - checkResult(result2, Status.OK, HandshakeStatus.NEED_UNWRAP, - 0, 0, false); - - System.out.println("Doing Initial Handshake"); - - boolean done1 = false; - boolean done2 = false; - - /* - * Do initial handshaking - */ - while (isHandshaking(ssle1) || - isHandshaking(ssle2)) { - - System.out.println("================"); - - result1 = ssle1.wrap(emptyBuffer, oneToTwo); - checkResult(result1, null, null, 0, -1, done1); - result2 = ssle2.wrap(emptyBuffer, twoToOne); - checkResult(result2, null, null, 0, -1, done2); - - if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done1 = true; - } - - if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done2 = true; - } - - System.out.println("wrap1 = " + result1); - System.out.println("wrap2 = " + result2); - - if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle1.getDelegatedTask()) != null) { - runnable.run(); - } - } - - if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle2.getDelegatedTask()) != null) { - runnable.run(); - } - } - - oneToTwo.flip(); - twoToOne.flip(); - - oneToTwo.position(10); - twoToOne.position(10); - - System.out.println("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, null, null, -1, 0, done1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, null, null, -1, 0, done2); - - if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done1 = true; - } - - if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done2 = true; - } - - if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle1.getDelegatedTask()) != null) { - runnable.run(); - } - } - - if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle2.getDelegatedTask()) != null) { - runnable.run(); - } - } - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - oneToTwoShifter.position(oneToTwo.position() - 10); - oneToTwoShifter.limit(oneToTwo.limit() - 10); - twoToOneShifter.position(twoToOne.position() - 10); - twoToOneShifter.limit(twoToOne.limit() - 10); - oneToTwoShifter.compact(); - twoToOneShifter.compact(); - oneToTwo.position(oneToTwoShifter.position() + 10); - oneToTwo.limit(oneToTwoShifter.limit() + 10); - twoToOne.position(twoToOneShifter.position() + 10); - twoToOne.limit(twoToOneShifter.limit() + 10); - } - - System.out.println("\nDONE HANDSHAKING"); - System.out.println("================"); - - if (!done1 || !done2) { - throw new Exception("Both should be true:\n" + - " done1 = " + done1 + " done2 = " + done2); - } - - String host = ssle1.getPeerHost(); - int port = ssle1.getPeerPort(); - if (!host.equals(hostname) || (port != portNumber)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - host = ssle2.getPeerHost(); - port = ssle2.getPeerPort(); - if ((host != null) || (port != -1)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - SSLSession ssls1 = ssle1.getSession(); - - host = ssls1.getPeerHost(); - port = ssls1.getPeerPort(); - if (!host.equals(hostname) || (port != portNumber)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - SSLSession ssls2 = ssle2.getSession(); - - host = ssls2.getPeerHost(); - port = ssls2.getPeerPort(); - if ((host != null) || (port != -1)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - /* - * Should be able to write/read a small buffer like this. - */ - int appOut1Len = appOut1.remaining(); - int appOut2Len = appOut2.remaining(); - int net1Len; - int net2Len; - - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(result1, Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut1Len, -1, false); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(result2, Status.OK, HandshakeStatus.NOT_HANDSHAKING, - appOut2Len, -1, false); - net1Len = result1.bytesProduced(); - net2Len = result2.bytesProduced(); - - System.out.println("wrap1 = " + result1); - System.out.println("wrap2 = " + result2); - - oneToTwo.flip(); - twoToOne.flip(); - - oneToTwo.position(10); - twoToOne.position(10); - - System.out.println("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, Status.OK, HandshakeStatus.NOT_HANDSHAKING, - net2Len, appOut2Len, false); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, Status.OK, HandshakeStatus.NOT_HANDSHAKING, - net1Len, appOut1Len, false); - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - oneToTwoShifter.position(oneToTwo.position() - 10); - oneToTwoShifter.limit(oneToTwo.limit() - 10); - twoToOneShifter.position(twoToOne.position() - 10); - twoToOneShifter.limit(twoToOne.limit() - 10); - oneToTwoShifter.compact(); - twoToOneShifter.compact(); - oneToTwo.position(oneToTwoShifter.position() + 10); - oneToTwo.limit(oneToTwoShifter.limit() + 10); - twoToOne.position(twoToOneShifter.position() + 10); - twoToOne.limit(twoToOneShifter.limit() + 10); - - ssls2.invalidate(); - ssle2.beginHandshake(); - - System.out.println("\nRENEGOTIATING"); - System.out.println("============="); - - done1 = false; - done2 = false; - - appIn1.clear(); - appIn2.clear(); - - /* - * Do a quick test to see if this can do a switch - * into client mode, at this point, you shouldn't be able - * to switch back. - */ - try { - System.out.println("Try to change client mode"); - ssle2.setUseClientMode(true); - throw new Exception("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { - System.out.println("Caught correct IllegalArgumentException"); - } - - while (isHandshaking(ssle1) || - isHandshaking(ssle2)) { - - System.out.println("================"); - - result1 = ssle1.wrap(emptyBuffer, oneToTwo); - checkResult(result1, null, null, 0, -1, done1); - result2 = ssle2.wrap(emptyBuffer, twoToOne); - checkResult(result2, null, null, 0, -1, done2); - - if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done1 = true; - } - - if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done2 = true; - } - - System.out.println("wrap1 = " + result1); - System.out.println("wrap2 = " + result2); - - if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle1.getDelegatedTask()) != null) { - runnable.run(); - } - } - - if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle2.getDelegatedTask()) != null) { - runnable.run(); - } - } - - oneToTwo.flip(); - twoToOne.flip(); - - oneToTwo.position(10); - twoToOne.position(10); - - System.out.println("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, null, null, -1, 0, done1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, null, null, -1, 0, done2); - - if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done1 = true; - } - - if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) { - done2 = true; - } - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle1.getDelegatedTask()) != null) { - runnable.run(); - } - } - - if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = ssle2.getDelegatedTask()) != null) { - runnable.run(); - } - } - - oneToTwoShifter.position(oneToTwo.position() - 10); - oneToTwoShifter.limit(oneToTwo.limit() - 10); - twoToOneShifter.position(twoToOne.position() - 10); - twoToOneShifter.limit(twoToOne.limit() - 10); - oneToTwoShifter.compact(); - twoToOneShifter.compact(); - oneToTwo.position(oneToTwoShifter.position() + 10); - oneToTwo.limit(oneToTwoShifter.limit() + 10); - twoToOne.position(twoToOneShifter.position() + 10); - twoToOne.limit(twoToOneShifter.limit() + 10); - } - - host = ssle1.getPeerHost(); - port = ssle1.getPeerPort(); - if (!host.equals(hostname) || (port != portNumber)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - host = ssle2.getPeerHost(); - port = ssle2.getPeerPort(); - if ((host != null) || (port != -1)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - SSLSession ssls3 = ssle2.getSession(); - - host = ssls1.getPeerHost(); - port = ssls1.getPeerPort(); - if (!host.equals(hostname) || (port != portNumber)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - SSLSession ssls4 = ssle2.getSession(); - - host = ssls2.getPeerHost(); - port = ssls2.getPeerPort(); - if ((host != null) || (port != -1)) { - throw new Exception("unexpected host/port " + host + ":" + port); - } - - System.out.println("\nDoing close"); - System.out.println("==========="); - - ssle1.closeOutbound(); - ssle2.closeOutbound(); - - oneToTwo.flip(); - twoToOne.flip(); - oneToTwo.position(10); - twoToOne.position(10); - - appIn1.clear(); - appIn2.clear(); - - System.out.println("LAST UNWRAP"); - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, Status.BUFFER_UNDERFLOW, - HandshakeStatus.NEED_WRAP, 0, 0, false); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, Status.BUFFER_UNDERFLOW, - HandshakeStatus.NEED_WRAP, 0, 0, false); - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - oneToTwoShifter.position(oneToTwo.position() - 10); - oneToTwoShifter.limit(oneToTwo.limit() - 10); - twoToOneShifter.position(twoToOne.position() - 10); - twoToOneShifter.limit(twoToOne.limit() - 10); - oneToTwoShifter.compact(); - twoToOneShifter.compact(); - oneToTwo.position(oneToTwoShifter.position() + 10); - oneToTwo.limit(oneToTwoShifter.limit() + 10); - twoToOne.position(twoToOneShifter.position() + 10); - twoToOne.limit(twoToOneShifter.limit() + 10); - - System.out.println("LAST WRAP"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(result1, Status.CLOSED, HandshakeStatus.NEED_UNWRAP, - 0, -1, false); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(result2, Status.CLOSED, HandshakeStatus.NEED_UNWRAP, - 0, -1, false); - - System.out.println("wrap1 = " + result1); - System.out.println("wrap2 = " + result2); - - net1Len = result1.bytesProduced(); - net2Len = result2.bytesProduced(); - - oneToTwo.flip(); - twoToOne.flip(); - - oneToTwo.position(10); - twoToOne.position(10); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - net1Len, 0, false); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - net2Len, 0, false); - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - oneToTwoShifter.position(oneToTwo.position() - 10); - oneToTwoShifter.limit(oneToTwo.limit() - 10); - twoToOneShifter.position(twoToOne.position() - 10); - twoToOneShifter.limit(twoToOne.limit() - 10); - oneToTwoShifter.compact(); - twoToOneShifter.compact(); - oneToTwo.position(oneToTwoShifter.position() + 10); - oneToTwo.limit(oneToTwoShifter.limit() + 10); - twoToOne.position(twoToOneShifter.position() + 10); - twoToOne.limit(twoToOneShifter.limit() + 10); - - System.out.println("EXTRA WRAP"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - 0, 0, false); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - 0, 0, false); - - System.out.println("wrap1 = " + result1); - System.out.println("wrap2 = " + result2); - - oneToTwo.flip(); - twoToOne.flip(); - oneToTwo.position(10); - twoToOne.position(10); - - System.out.println("EXTRA UNWRAP"); - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - 0, 0, false); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING, - 0, 0, false); - - System.out.println("unwrap1 = " + result1); - System.out.println("unwrap2 = " + result2); - - checkSession(ssls1, ssls2, ssls3, ssls4); - System.out.println(ssle1); - System.out.println(ssle2); - } - - private static void checkSession(SSLSession ssls1, SSLSession ssls2, - SSLSession ssls3, SSLSession ssls4) throws Exception { - System.out.println("\nSession Info for SSLEngine1"); - System.out.println(ssls1); - System.out.println(ssls1.getCreationTime()); - String peer1 = ssls1.getPeerHost(); - System.out.println(peer1); - String protocol1 = ssls1.getProtocol(); - System.out.println(protocol1); - java.security.cert.Certificate cert1 = ssls1.getPeerCertificates()[0]; - System.out.println(cert1); - String ciphersuite1 = ssls1.getCipherSuite(); - System.out.println(ciphersuite1); - System.out.println(); - - System.out.println("\nSession Info for SSLEngine2"); - System.out.println(ssls2); - System.out.println(ssls2.getCreationTime()); - String peer2 = ssls2.getPeerHost(); - System.out.println(peer2); - String protocol2 = ssls2.getProtocol(); - System.out.println(protocol2); - java.security.cert.Certificate cert2 = ssls2.getPeerCertificates()[0]; - System.out.println(cert2); - String ciphersuite2 = ssls2.getCipherSuite(); - System.out.println(ciphersuite2); - System.out.println(); - - if (peer1.equals(peer2)) { - throw new Exception("peer hostnames not equal"); - } - - if (!protocol1.equals(protocol2)) { - throw new Exception("protocols not equal"); - } - - if (!cert1.equals(cert2)) { - throw new Exception("certs not equal"); - } - - if (!ciphersuite1.equals(ciphersuite2)) { - throw new Exception("ciphersuites not equal"); - } - - System.out.println("\nSession Info for SSLEngine3"); - System.out.println(ssls3); - System.out.println("\nSession Info for SSLEngine4"); - System.out.println(ssls4); - - if (ssls3.equals(ssls1) || ssls4.equals(ssls2)) { - throw new Exception("sessions should not be equals"); - } - } - - public static void main(String args[]) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - ConnectionTest ct = new ConnectionTest(); - ct.test(); - } -}
--- a/test/javax/net/ssl/SSLEngine/ExtendedKeyEngine.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4981697 - * @summary Rework the X509KeyManager to avoid incompatibility issues - * @author Brad R. Wetmore - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class ExtendedKeyEngine { - - private static boolean debug = false; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - } - - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - log("================"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); - log(""); - - log("wrap2: " + result2); - log("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - log("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); - log(""); - - log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { - - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); - - log("Closing ssle1's *OUTBOUND*..."); - ssle1.closeOutbound(); - dataDone = true; - } - } - } - - public static void main(String args[]) throws Exception { - - ExtendedKeyEngine test; - - System.out.println("This test should run to completion"); - test = new ExtendedKeyEngine(true); - test.createSSLEngines(); - test.runTest(); - System.out.println("Done!"); - - System.out.println("This test should fail with a Handshake Error"); - test = new ExtendedKeyEngine(false); - test.createSSLEngines(); - - try { - test.runTest(); - } catch (SSLHandshakeException e) { - System.out.println( - "Caught proper exception, should be 'no suites in common'"); - e.printStackTrace(); - } - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public ExtendedKeyEngine(boolean abs) throws Exception { - sslc = getSSLContext(keyFilename, trustFilename, abs); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile, - boolean abs) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - KeyManager [] kms = kmf.getKeyManagers(); - if (abs) { - kms = new KeyManager [] { - new MyX509ExtendedKeyManager((X509ExtendedKeyManager)kms[0]) - }; - } else { - kms = new KeyManager [] { - new MyX509KeyManager((X509KeyManager)kms[0]) - }; - } - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - TrustManager [] tms = tmf.getTrustManagers(); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kms, tms, null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/SSLEngine/IllegalRecordVersion.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// This test case relies on updated static security property, no way to re-use -// security property in samevm/agentvm mode. - -/* - * @test - * @bug 8042449 - * @summary Issue for negative byte major record version - * - * @run main/othervm IllegalRecordVersion - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class IllegalRecordVersion { - - public static void main(String args[]) throws Exception { - SSLContext context = SSLContext.getDefault(); - - SSLEngine cliEngine = context.createSSLEngine(); - cliEngine.setUseClientMode(true); - SSLEngine srvEngine = context.createSSLEngine(); - srvEngine.setUseClientMode(false); - - SSLSession session = cliEngine.getSession(); - int netBufferMax = session.getPacketBufferSize(); - int appBufferMax = session.getApplicationBufferSize(); - - ByteBuffer cliToSrv = ByteBuffer.allocateDirect(netBufferMax); - ByteBuffer srvIBuff = ByteBuffer.allocateDirect(appBufferMax + 50); - ByteBuffer cliOBuff = ByteBuffer.wrap("I'm client".getBytes()); - - - System.out.println("client hello (record version(0xa9, 0xa2))"); - SSLEngineResult cliRes = cliEngine.wrap(cliOBuff, cliToSrv); - System.out.println("Client wrap result: " + cliRes); - cliToSrv.flip(); - if (cliToSrv.limit() > 5) { - cliToSrv.put(1, (byte)0xa9); - cliToSrv.put(2, (byte)0xa2); - } - - try { - srvEngine.unwrap(cliToSrv, srvIBuff); - throw new Exception( - "Cannot catch the unsupported record version issue"); - } catch (SSLException e) { - // get the expected exception - } - } -}
--- a/test/javax/net/ssl/SSLEngine/LargeBufs.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4495742 - * @summary Add non-blocking SSL/TLS functionality, usable with any - * I/O abstraction - * - * This is to test larger buffer arrays, and make sure the maximum - * is being passed. - * - * @run main/othervm -Djsse.enableCBCProtection=false LargeBufs - * - * @author Brad R. Wetmore - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -import java.util.Random; - -public class LargeBufs { - - private static boolean debug = false; - - private SSLContext sslc; - static private SSLEngine ssle1; // client - static private SSLEngine ssle2; // server - - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - private int appBufferMax; - private int netBufferMax; - private int OFFSET = 37; - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - } - - private void runTest(String cipher) throws Exception { - boolean dataDone = false; - - createSSLEngines(); - - System.out.println("Using " + cipher); - ssle1.setEnabledCipherSuites(new String [] { cipher }); - ssle2.setEnabledCipherSuites(new String [] { cipher }); - - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - log("================"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - if ((result1.bytesConsumed() != 0) && - (result1.bytesConsumed() != appBufferMax) && - (result1.bytesConsumed() != OFFSET)) { - throw new Exception("result1: " + result1); - } - - if ((result2.bytesConsumed() != 0) && - (result2.bytesConsumed() != appBufferMax) && - (result2.bytesConsumed() != 2 * OFFSET)) { - throw new Exception("result1: " + result1); - } - - log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); - log(""); - - log("wrap2: " + result2); - log("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - log("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - if ((result1.bytesProduced() != 0) && - (result1.bytesProduced() != appBufferMax) && - (result1.bytesProduced() != 2 * OFFSET)) { - throw new Exception("result1: " + result1); - } - - if ((result2.bytesProduced() != 0) && - (result2.bytesProduced() != appBufferMax) && - (result2.bytesProduced() != OFFSET)) { - throw new Exception("result1: " + result1); - } - - log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); - log(""); - - log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { - - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); - - log("Closing ssle1's *OUTBOUND*..."); - ssle1.closeOutbound(); - dataDone = true; - } - } - } - - public static void main(String args[]) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - LargeBufs test; - - test = new LargeBufs(); - test.runTest("SSL_RSA_WITH_RC4_128_MD5"); - - test = new LargeBufs(); - test.runTest("SSL_RSA_WITH_3DES_EDE_CBC_SHA"); - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public LargeBufs() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - - // The maximum application buffer should calculate like - // appBufferMax = session.getApplicationBufferSize(); - // however, the getApplicationBufferSize() doesn't guarantee - // that the ability to concume or produce applicaton data upto - // the size. 16384 is the default JSSE implementation maximum - // application size that could be consumed and produced. - appBufferMax = 16384; - netBufferMax = session.getPacketBufferSize(); - - Random random = new Random(); - byte [] one = new byte [appBufferMax * 5 + OFFSET]; - byte [] two = new byte [appBufferMax * 5 + 2 * OFFSET]; - - random.nextBytes(one); - random.nextBytes(two); - - appOut1 = ByteBuffer.wrap(one); - appOut2 = ByteBuffer.wrap(two); - - appIn1 = ByteBuffer.allocate(appBufferMax * 6); - appIn2 = ByteBuffer.allocate(appBufferMax * 6); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - System.out.println("Testing arrays of: " + one.length + - " and " + two.length); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/SSLEngine/NoAuthClientAuth.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,399 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4495742 - * @summary Demonstrate SSLEngine switch from no client auth to client auth. - * @run main/othervm NoAuthClientAuth - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * - * @author Brad R. Wetmore - */ - -/** - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - * - * In this example, we do a rehandshake and make sure that completes - * correctly. - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class NoAuthClientAuth { - - /* - * Enables logging of the SSLEngine operations. - */ - private static boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static boolean debug = false; - - private SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - NoAuthClientAuth test = new NoAuthClientAuth(); - test.runTest(); - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public NoAuthClientAuth() throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest() throws Exception { - - createSSLEngines(); - createBuffers(); - - SSLEngineResult clientResult; // results from client's last operation - SSLEngineResult serverResult; // results from server's last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - int hsCompleted = 0; - while (!isEngineClosed(clientEngine) || - !isEngineClosed(serverEngine)) { - - log("================"); - - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - clientOut.rewind(); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - serverOut.rewind(); - - // Jeanfrancois: - // Here is the main rehandshaking step. - if (serverResult.getHandshakeStatus() == - HandshakeStatus.FINISHED) { - hsCompleted++; - log("\t" + hsCompleted + " handshake completed"); - if (hsCompleted == 1) { - try { - serverEngine.getSession().getPeerCertificates(); - throw new Exception("Should have got exception"); - } catch (SSLPeerUnverifiedException e) { - System.out.println("Caught proper exception." + e); - } - log("\tInvalidating session, setting client auth, " + - " starting rehandshake"); - serverEngine.getSession().invalidate(); - serverEngine.setNeedClientAuth(true); - serverEngine.beginHandshake(); - } else if (hsCompleted == 2) { - java.security.cert.Certificate [] certs = - serverEngine.getSession().getPeerCertificates(); - System.out.println("Client Certificate(s) received"); - for (java.security.cert.Certificate c : certs) { - System.out.println(c); - } - log("Closing server."); - serverEngine.closeOutbound(); - } // nothing. - } - - cTOs.flip(); - sTOc.flip(); - - log("----"); - - clientResult = clientEngine.unwrap(sTOc, clientIn); - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - clientIn.clear(); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - serverIn.clear(); - - cTOs.compact(); - sTOc.compact(); - } - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(false); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" + - "\t\"getStatus() / getHandshakeStatus()\" +\n" + - "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str + - result.getStatus() + "/" + hsStatus + ", " + - result.bytesConsumed() + "/" + result.bytesProduced() + - " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/SSLSession/SessionCacheSizeTests.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,480 +0,0 @@ -/* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4366807 - * @summary Need new APIs to get/set session timeout and session cache size. - * @run main/othervm SessionCacheSizeTests - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.util.*; -import java.security.*; - -/** - * Session cache size tests cover the following cases: - * 1. Effect of system property javax.net.ssl.SessionCacheSize (this - * property is not documented for public). - * 2. Reducing the cache size, results in uncaching of sessions if #of - * sessions present exceeds the new size. - * 3. Increasing the cache size, results in accomodating new sessions if the - * number of cached sessions is the current size limit. - * - * Invairant for passing this test is, at any given time, - * #cached_sessions <= current_cache_size , for current_cache_size > 0 - */ - -public class SessionCacheSizeTests { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - - /* - * A limit on the number of connections at any given time - */ - static int MAX_ACTIVE_CONNECTIONS = 4; - - void doServerSide(int serverPort, int serverConns) throws Exception { - - try (SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort)) { - - // timeout to accept a connection - sslServerSocket.setSoTimeout(45000); - - // make sure createdPorts++ is atomic - synchronized(serverPorts) { - serverPorts[createdPorts++] = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - if (createdPorts == serverPorts.length) { - serverReady = true; - } - } - int read = 0; - int nConnections = 0; - - /* - * Divide the max connections among the available server ports. - * The use of more than one server port ensures creation of more - * than one session. - */ - SSLSession sessions [] = new SSLSession [serverConns]; - SSLSessionContext sessCtx = sslctx.getServerSessionContext(); - - while (nConnections < serverConns) { - try (SSLSocket sslSocket = - (SSLSocket)sslServerSocket.accept()) { - sslSocket.setSoTimeout(90000); // timeout to read - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - read = sslIS.read(); - sessions[nConnections] = sslSocket.getSession(); - sslOS.write(85); - sslOS.flush(); - nConnections++; - } - } - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - int nConnections = 0; - SSLSocket sslSockets[] = new SSLSocket [MAX_ACTIVE_CONNECTIONS]; - Vector sessions = new Vector(); - SSLSessionContext sessCtx = sslctx.getClientSessionContext(); - sessCtx.setSessionTimeout(0); // no limit - - while (nConnections < (MAX_ACTIVE_CONNECTIONS - 1)) { - // divide the connections among the available server ports - sslSockets[nConnections] = (SSLSocket) sslsf. - createSocket("localhost", - serverPorts [nConnections % (serverPorts.length)]); - InputStream sslIS = sslSockets[nConnections].getInputStream(); - OutputStream sslOS = sslSockets[nConnections].getOutputStream(); - sslOS.write(237); - sslOS.flush(); - int read = sslIS.read(); - SSLSession sess = sslSockets[nConnections].getSession(); - if (!sessions.contains(sess)) - sessions.add(sess); - nConnections++; - } - System.out.println("Current cacheSize is set to: " + - sessCtx.getSessionCacheSize()); - System.out.println(); - System.out.println("Currently cached Sessions......"); - System.out.println("============================================" - + "============================"); - System.out.println("Session " - + " Session-last-accessTime"); - System.out.println("============================================" - + "============================"); - checkCachedSessions(sessCtx, nConnections); - // Change session cache size - sessCtx.setSessionCacheSize(2); - System.out.println("Session cache size changed to: " - + sessCtx.getSessionCacheSize()); - System.out.println(); - checkCachedSessions(sessCtx, nConnections); - - // Test the effect of increasing the cache size - sessCtx.setSessionCacheSize(3); - System.out.println("Session cache size changed to: " - + sessCtx.getSessionCacheSize()); - // create a new session - sslSockets[nConnections] = (SSLSocket) sslsf. - createSocket("localhost", - serverPorts [nConnections % (serverPorts.length)]); - InputStream sslIS = sslSockets[nConnections].getInputStream(); - OutputStream sslOS = sslSockets[nConnections].getOutputStream(); - sslOS.write(237); - sslOS.flush(); - int read = sslIS.read(); - SSLSession sess = sslSockets[nConnections].getSession(); - if (!sessions.contains(sess)) - sessions.add(sess); - nConnections++; - - // test the number of sessions cached against the cache size - checkCachedSessions(sessCtx, nConnections); - - for (int i = 0; i < nConnections; i++) { - sslSockets[i].close(); - } - System.out.println("Session cache size tests passed"); - } - - void checkCachedSessions(SSLSessionContext sessCtx, - int nConn) throws Exception { - int nSessions = 0; - Enumeration e = sessCtx.getIds(); - int cacheSize = sessCtx.getSessionCacheSize(); - SSLSession sess; - - while (e.hasMoreElements()) { - sess = sessCtx.getSession((byte[]) e.nextElement()); - long lastAccessedTime = sess.getLastAccessedTime(); - System.out.println(sess + " " - + new Date(lastAccessedTime)); - - nSessions++; - } - System.out.println("--------------------------------------------" - + "----------------------------"); - if ((cacheSize > 0) && (nSessions > cacheSize)) { - - // close all active connections before exiting - for (int conn = nConn; conn < MAX_ACTIVE_CONNECTIONS; conn++) { - SSLSocket s = (SSLSocket) sslsf.createSocket("localhost", - serverPorts [conn % (serverPorts.length)]); - s.close(); - } - throw new Exception("Session cache size test failed," - + " current cache size: " + cacheSize + " #sessions cached: " - + nSessions); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - /* - * #of ports > 1, guarantees creation of more than one session. - * Using four ports (one per each connection), we are able to create - * alteast four sessions. - */ - int serverPorts[] = new int[]{0, 0, 0, 0}; // MAX_ACTIVE_CONNECTIONS: 4 - int createdPorts = 0; - static SSLServerSocketFactory sslssf; - static SSLSocketFactory sslsf; - static SSLContext sslctx; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - // test the effect of javax.net.ssl.sessionCacheSize - System.setProperty("javax.net.ssl.sessionCacheSize", String.valueOf(0)); - - sslctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(keyFilename), passwd.toCharArray()); - kmf.init(ks, passwd.toCharArray()); - sslctx.init(kmf.getKeyManagers(), null, null); - sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory(); - sslsf = (SSLSocketFactory) sslctx.getSocketFactory(); - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SessionCacheSizeTests(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SessionCacheSizeTests() throws Exception { - /* - * create the SSLServerSocket and SSLSocket factories - */ - - /* - * Divide the max connections among the available server ports. - * The use of more than one server port ensures creation of more - * than one session. - */ - int serverConns = MAX_ACTIVE_CONNECTIONS / (serverPorts.length); - int remainingConns = MAX_ACTIVE_CONNECTIONS % (serverPorts.length); - - Exception startException = null; - try { - if (separateServerThread) { - for (int i = 0; i < serverPorts.length; i++) { - // distribute remaining connections among the - // available ports - if (i < remainingConns) - startServer(serverPorts[i], (serverConns + 1), true); - else - startServer(serverPorts[i], serverConns, true); - } - startClient(false); - } else { - startClient(true); - for (int i = 0; i < serverPorts.length; i++) { - if (i < remainingConns) - startServer(serverPorts[i], (serverConns + 1), false); - else - startServer(serverPorts[i], serverConns, false); - } - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(final int port, final int nConns, - boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(port, nConns); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - e.printStackTrace(); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(port, nConns); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) - throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/SSLSession/SessionTimeOutTests.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,494 +0,0 @@ -/* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 4366807 - * @summary Need new APIs to get/set session timeout and session cache size. - * @run main/othervm SessionTimeOutTests - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.util.*; -import java.security.*; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Session reuse time-out tests cover the cases below: - * 1. general test, i.e timeout is set to x and session invalidates when - * its lifetime exceeds x. - * 2. Effect of changing the timeout limit. - * The test suite does not cover the default timeout(24 hours) usage. This - * case has been tested independetly. - * - * Invairant for passing this test is, at any given time, - * lifetime of a session < current_session_timeout, such that - * current_session_timeout > 0, for all sessions cached by the session - * context. - */ - -public class SessionTimeOutTests { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - private static int PORTS = 3; - - /* - * Is the server ready to serve? - */ - AtomicInteger serverReady = new AtomicInteger(PORTS); - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to zero - * to avoid infinite hangs. - */ - - /* - * A limit on the number of connections at any given time - */ - static int MAX_ACTIVE_CONNECTIONS = 3; - - void doServerSide(int serverPort, int serverConns) throws Exception { - - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - int slot = createdPorts.getAndIncrement(); - serverPorts[slot] = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady.getAndDecrement(); - int read = 0; - int nConnections = 0; - SSLSession sessions [] = new SSLSession [serverConns]; - - while (nConnections < serverConns) { - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - read = sslIS.read(); - sessions[nConnections] = sslSocket.getSession(); - sslOS.write(85); - sslOS.flush(); - sslSocket.close(); - nConnections++; - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to zero - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (serverReady.get() > 0) { - Thread.sleep(50); - } - - int nConnections = 0; - SSLSocket sslSockets[] = new SSLSocket [MAX_ACTIVE_CONNECTIONS]; - Vector sessions = new Vector(); - SSLSessionContext sessCtx = sslctx.getClientSessionContext(); - - sessCtx.setSessionTimeout(10); // in secs - int timeout = sessCtx.getSessionTimeout(); - while (nConnections < MAX_ACTIVE_CONNECTIONS) { - // divide the connections among the available server ports - sslSockets[nConnections] = (SSLSocket) sslsf. - createSocket("localhost", - serverPorts [nConnections % (serverPorts.length)]); - InputStream sslIS = sslSockets[nConnections].getInputStream(); - OutputStream sslOS = sslSockets[nConnections].getOutputStream(); - sslOS.write(237); - sslOS.flush(); - int read = sslIS.read(); - SSLSession sess = sslSockets[nConnections].getSession(); - if (!sessions.contains(sess)) - sessions.add(sess); - nConnections++; - } - System.out.println(); - System.out.println("Current timeout is set to: " + timeout); - System.out.println("Testing SSLSessionContext.getSession()......"); - System.out.println("========================================" - + "======================="); - System.out.println("Session " - + "Session- Session"); - System.out.println(" " - + "lifetime timedout?"); - System.out.println("========================================" - + "======================="); - - for (int i = 0; i < sessions.size(); i++) { - SSLSession session = (SSLSession) sessions.elementAt(i); - long currentTime = System.currentTimeMillis(); - long creationTime = session.getCreationTime(); - long lifetime = (currentTime - creationTime) / 1000; - - System.out.print(session + " " + lifetime + " "); - if (sessCtx.getSession(session.getId()) == null) { - if (lifetime < timeout) - // sessions can be garbage collected before the timeout - // limit is reached - System.out.println("Invalidated before timeout"); - else - System.out.println("YES"); - } else { - System.out.println("NO"); - if ((timeout != 0) && (lifetime > timeout)) { - throw new Exception("Session timeout test failed for the" - + " obove session"); - } - } - // change the timeout - if (i == ((sessions.size()) / 2)) { - System.out.println(); - sessCtx.setSessionTimeout(2); // in secs - timeout = sessCtx.getSessionTimeout(); - System.out.println("timeout is changed to: " + timeout); - System.out.println(); - } - } - - // check the ids returned by the enumerator - Enumeration e = sessCtx.getIds(); - System.out.println("----------------------------------------" - + "-----------------------"); - System.out.println("Testing SSLSessionContext.getId()......"); - System.out.println(); - - SSLSession nextSess = null; - SSLSession sess; - for (int i = 0; i < sessions.size(); i++) { - sess = (SSLSession)sessions.elementAt(i); - String isTimedout = "YES"; - long currentTime = System.currentTimeMillis(); - long creationTime = sess.getCreationTime(); - long lifetime = (currentTime - creationTime) / 1000; - - if (nextSess != null) { - if (isEqualSessionId(nextSess.getId(), sess.getId())) { - isTimedout = "NO"; - nextSess = null; - } - } else if (e.hasMoreElements()) { - nextSess = sessCtx.getSession((byte[]) e.nextElement()); - if ((nextSess != null) && isEqualSessionId(nextSess.getId(), - sess.getId())) { - nextSess = null; - isTimedout = "NO"; - } - } - - /* - * A session not invalidated even after it's timeout? - */ - if ((timeout != 0) && (lifetime > timeout) && - (isTimedout.equals("NO"))) { - throw new Exception("Session timeout test failed for session: " - + sess + " lifetime: " + lifetime); - } - System.out.print(sess + " " + lifetime); - if (((timeout == 0) || (lifetime < timeout)) && - (isTimedout == "YES")) { - isTimedout = "Invalidated before timeout"; - } - - System.out.println(" " + isTimedout); - } - for (int i = 0; i < nConnections; i++) { - sslSockets[i].close(); - } - System.out.println("----------------------------------------" - + "-----------------------"); - System.out.println("Session timeout test passed"); - } - - boolean isEqualSessionId(byte[] id1, byte[] id2) { - if (id1.length != id2.length) - return false; - else { - for (int i = 0; i < id1.length; i++) { - if (id1[i] != id2[i]) { - return false; - } - } - return true; - } - } - - - /* - * ============================================================= - * The remainder is just support stuff - */ - - int serverPorts[] = new int[PORTS]; - AtomicInteger createdPorts = new AtomicInteger(0); - static SSLServerSocketFactory sslssf; - static SSLSocketFactory sslsf; - static SSLContext sslctx; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - sslctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(keyFilename), passwd.toCharArray()); - kmf.init(ks, passwd.toCharArray()); - sslctx.init(kmf.getKeyManagers(), null, null); - sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory(); - sslsf = (SSLSocketFactory) sslctx.getSocketFactory(); - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SessionTimeOutTests(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SessionTimeOutTests() throws Exception { - - /* - * create the SSLServerSocket and SSLSocket factories - */ - - /* - * Divide the max connections among the available server ports. - * The use of more than one server port ensures creation of more - * than one session. - */ - int serverConns = MAX_ACTIVE_CONNECTIONS / (serverPorts.length); - int remainingConns = MAX_ACTIVE_CONNECTIONS % (serverPorts.length); - - Exception startException = null; - try { - if (separateServerThread) { - for (int i = 0; i < serverPorts.length; i++) { - // distribute remaining connections among the - // vailable ports - if (i < remainingConns) - startServer(serverPorts[i], (serverConns + 1), true); - else - startServer(serverPorts[i], serverConns, true); - } - startClient(false); - } else { - startClient(true); - for (int i = 0; i < serverPorts.length; i++) { - if (i < remainingConns) - startServer(serverPorts[i], (serverConns + 1), false); - else - startServer(serverPorts[i], serverConns, false); - } - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(final int port, final int nConns, - boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(port, nConns); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - e.printStackTrace(); - serverReady.set(0); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(port, nConns); - } catch (Exception e) { - serverException = e; - } finally { - serverReady.set(0); - } - } - } - - void startClient(boolean newThread) - throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/SSLSession/testEnabledProtocols.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4416068 4478803 4479736 - * @summary 4273544 JSSE request for function forceV3ClientHello() - * 4479736 setEnabledProtocols API does not work correctly - * 4478803 Need APIs to determine the protocol versions used in an SSL - * session - * 4701722 protocol mismatch exceptions should be consistent between - * SSLv3 and TLSv1 - * @run main/othervm testEnabledProtocols - * @author Ram Marti - */ - -import java.io.*; -import java.net.*; -import java.util.*; -import java.security.*; -import javax.net.ssl.*; -import java.security.cert.*; - -public class testEnabledProtocols { - - /* - * For each of the valid protocols combinations, start a server thread - * that sets up an SSLServerSocket supporting that protocol. Then run - * a client thread that attemps to open a connection with all - * possible protocol combinataion. Verify that we get handshake - * exceptions correctly. Whenever the connection is established - * successfully, verify that the negotiated protocol was correct. - * See results file in this directory for complete results. - */ - - static final String[][] protocolStrings = { - {"TLSv1"}, - {"TLSv1", "SSLv2Hello"}, - {"TLSv1", "SSLv3"}, - {"SSLv3", "SSLv2Hello"}, - {"SSLv3"}, - {"TLSv1", "SSLv3", "SSLv2Hello"} - }; - - static final boolean [][] eXceptionArray = { - // Do we expect exception? Protocols supported by the server - { false, true, false, true, true, true }, // TLSv1 - { false, false, false, true, true, false}, // TLSv1,SSLv2Hello - { false, true, false, true, false, true }, // TLSv1,SSLv3 - { true, true, false, false, false, false}, // SSLv3, SSLv2Hello - { true, true, false, true, false, true }, // SSLv3 - { false, false, false, false, false, false } // TLSv1,SSLv3,SSLv2Hello - }; - - static final String[][] protocolSelected = { - // TLSv1 - { "TLSv1", null, "TLSv1", null, null, null }, - - // TLSv1,SSLv2Hello - { "TLSv1", "TLSv1", "TLSv1", null, null, "TLSv1"}, - - // TLSv1,SSLv3 - { "TLSv1", null, "TLSv1", null, "SSLv3", null }, - - // SSLv3, SSLv2Hello - { null, null, "SSLv3", "SSLv3", "SSLv3", "SSLv3"}, - - // SSLv3 - { null, null, "SSLv3", null, "SSLv3", null }, - - // TLSv1,SSLv3,SSLv2Hello - { "TLSv1", "TLSv1", "TLSv1", "SSLv3", "SSLv3", "TLSv1" } - - }; - - /* - * Where do we find the keystores? - */ - final static String pathToStores = "../etc"; - static String passwd = "passphrase"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - final static boolean debug = false; - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - new testEnabledProtocols(); - } - - testEnabledProtocols() throws Exception { - /* - * Start the tests. - */ - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - // sslServerSocket.setNeedClientAuth(true); - - for (int i = 0; i < protocolStrings.length; i++) { - String [] serverProtocols = protocolStrings[i]; - startServer ss = new startServer(serverProtocols, - sslServerSocket, protocolStrings.length); - ss.setDaemon(true); - ss.start(); - for (int j = 0; j < protocolStrings.length; j++) { - String [] clientProtocols = protocolStrings[j]; - startClient sc = new startClient( - clientProtocols, serverProtocols, - eXceptionArray[i][j], protocolSelected[i][j]); - sc.start(); - sc.join(); - if (clientException != null) { - ss.requestStop(); - throw clientException; - } - } - ss.requestStop(); - System.out.println("Waiting for the server to complete"); - ss.join(); - } - } - - class startServer extends Thread { - private String[] enabledP = null; - SSLServerSocket sslServerSocket = null; - int numExpConns; - volatile boolean stopRequested = false; - - public startServer(String[] enabledProtocols, - SSLServerSocket sslServerSocket, - int numExpConns) { - super("Server Thread"); - serverReady = false; - enabledP = enabledProtocols; - this.sslServerSocket = sslServerSocket; - sslServerSocket.setEnabledProtocols(enabledP); - this.numExpConns = numExpConns; - } - - public void requestStop() { - stopRequested = true; - } - - public void run() { - int conns = 0; - while (!stopRequested) { - SSLSocket socket = null; - try { - serverReady = true; - socket = (SSLSocket)sslServerSocket.accept(); - conns++; - - // set ready to false. this is just to make the - // client wait and synchronise exception messages - serverReady = false; - socket.startHandshake(); - SSLSession session = socket.getSession(); - session.invalidate(); - - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - out.write(280); - in.read(); - - socket.close(); - // sleep for a while so that the server thread can be - // stopped - Thread.sleep(30); - } catch (SSLHandshakeException se) { - // ignore it; this is part of the testing - // log it for debugging - System.out.println("Server SSLHandshakeException:"); - se.printStackTrace(System.out); - } catch (java.io.InterruptedIOException ioe) { - // must have been interrupted, no harm - break; - } catch (java.lang.InterruptedException ie) { - // must have been interrupted, no harm - break; - } catch (Exception e) { - System.out.println("Server exception:"); - e.printStackTrace(System.out); - throw new RuntimeException(e); - } finally { - try { - if (socket != null) { - socket.close(); - } - } catch (IOException e) { - // ignore - } - } - if (conns >= numExpConns) { - break; - } - } - } - } - - private static void showProtocols(String name, String[] protocols) { - System.out.println("Enabled protocols on the " + name + " are: " + Arrays.asList(protocols)); - } - - class startClient extends Thread { - boolean hsCompleted = false; - boolean exceptionExpected = false; - private String[] enabledP = null; - private String[] serverP = null; // used to print the result - private String protocolToUse = null; - - startClient(String[] enabledProtocol, - String[] serverP, - boolean eXception, - String protocol) throws Exception { - super("Client Thread"); - this.enabledP = enabledProtocol; - this.serverP = serverP; - this.exceptionExpected = eXception; - this.protocolToUse = protocol; - } - - public void run() { - SSLSocket sslSocket = null; - try { - while (!serverReady) { - Thread.sleep(50); - } - System.out.flush(); - System.out.println("=== Starting new test run ==="); - showProtocols("server", serverP); - showProtocols("client", enabledP); - - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - sslSocket.setEnabledProtocols(enabledP); - sslSocket.startHandshake(); - - SSLSession session = sslSocket.getSession(); - session.invalidate(); - String protocolName = session.getProtocol(); - System.out.println("Protocol name after getSession is " + - protocolName); - - if (protocolName.equals(protocolToUse)) { - System.out.println("** Success **"); - } else { - System.out.println("** FAILURE ** "); - throw new RuntimeException - ("expected protocol " + protocolToUse + - " but using " + protocolName); - } - - InputStream in = sslSocket.getInputStream(); - OutputStream out = sslSocket.getOutputStream(); - in.read(); - out.write(280); - - sslSocket.close(); - - } catch (SSLHandshakeException e) { - if (!exceptionExpected) { - System.out.println("Client got UNEXPECTED SSLHandshakeException:"); - e.printStackTrace(System.out); - System.out.println("** FAILURE **"); - clientException = e; - } else { - System.out.println("Client got expected SSLHandshakeException:"); - e.printStackTrace(System.out); - System.out.println("** Success **"); - } - } catch (RuntimeException e) { - clientException = e; - } catch (Exception e) { - System.out.println("Client got UNEXPECTED Exception:"); - e.printStackTrace(System.out); - System.out.println("** FAILURE **"); - clientException = e; - } - } - } - -}
--- a/test/javax/net/ssl/ServerName/SSLSocketExplorerFailure.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/** - * @test - * @bug 7068321 - * @summary Support TLS Server Name Indication (SNI) Extension in JSSE Server - * @library ../templates - * @build SSLCapabilities SSLExplorer - * @run main/othervm SSLSocketExplorerFailure SSLv2Hello,SSLv3 - * @run main/othervm SSLSocketExplorerFailure SSLv3 - * @run main/othervm SSLSocketExplorerFailure TLSv1 - * @run main/othervm SSLSocketExplorerFailure TLSv1.1 - * @run main/othervm SSLSocketExplorerFailure TLSv1.2 - */ - -import java.io.*; -import java.nio.*; -import java.nio.channels.*; -import java.util.*; -import java.net.*; -import javax.net.ssl.*; - -public class SSLSocketExplorerFailure { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - - ServerSocket serverSocket = new ServerSocket(serverPort); - - // Signal Client, we're ready for his connect. - serverPort = serverSocket.getLocalPort(); - serverReady = true; - - Socket socket = serverSocket.accept(); - InputStream ins = socket.getInputStream(); - - byte[] buffer = new byte[0xFF]; - int position = 0; - SSLCapabilities capabilities = null; - boolean failed = false; - try { - // Read the header of TLS record - while (position < SSLExplorer.RECORD_HEADER_SIZE) { - int count = SSLExplorer.RECORD_HEADER_SIZE - position; - int n = ins.read(buffer, position, count); - if (n < 0) { - throw new Exception("unexpected end of stream!"); - } - position += n; - } - - int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position); - if (buffer.length < recordLength) { - buffer = Arrays.copyOf(buffer, recordLength); - } - - while (position < recordLength) { - int count = recordLength - position; - int n = ins.read(buffer, position, count); - if (n < 0) { - throw new Exception("unexpected end of stream!"); - } - position += n; - } - - capabilities = SSLExplorer.explore(buffer, 0, recordLength);; - if (capabilities != null) { - System.out.println("Record version: " + - capabilities.getRecordVersion()); - System.out.println("Hello version: " + - capabilities.getHelloVersion()); - } - - // want an I/O exception - throw new IOException("We just want a I/O exception"); - } catch (Exception e) { - failed = true; - } - - // off course, the above explore failed. Faile to failure handler - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - ByteArrayInputStream bais = - new ByteArrayInputStream(buffer, 0, position); - SSLSocket sslSocket = (SSLSocket)sslsf.createSocket(socket, bais, true); - - try { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - if (!failed) { - sslOS.write(85); - sslOS.flush(); - } else { - sslSocket.close(); - } - } catch (Exception e) { - System.out.println("server exception " + e); - } finally { - sslSocket.close(); - serverSocket.close(); - } - } - - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - // enable the specified TLS protocol - sslSocket.setEnabledProtocols(supportedProtocols); - - try { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } catch (Exception e) { - System.out.println("client exception " + e); - } finally { - sslSocket.close(); - } - } - - private static String[] supportedProtocols; // supported protocols - - private static void parseArguments(String[] args) { - supportedProtocols = args[0].split(","); - } - - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new SSLSocketExplorerFailure(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketExplorerFailure() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/ServerName/SSLSocketSNISensitive.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,577 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7068321 - * @summary Support TLS Server Name Indication (SNI) Extension in JSSE Server - * @run main/othervm SSLSocketSNISensitive PKIX www.example.com - * @run main/othervm SSLSocketSNISensitive SunX509 www.example.com - * @run main/othervm SSLSocketSNISensitive PKIX www.example.net - * @run main/othervm SSLSocketSNISensitive SunX509 www.example.net - * @run main/othervm SSLSocketSNISensitive PKIX www.invalid.com - * @run main/othervm SSLSocketSNISensitive SunX509 www.invalid.com - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class SSLSocketSNISensitive { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNDE3MTIwNjA3WhcNMzMwMzI4MTIwNjA3WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBANY+7Enp+1S566kLcKk+qe4Ki6BxaHGZ+v7r\n" + - "vLksx9IQZCbAEf4YLbrZhKzKD3SPIJXyxPFwknAknIh3Knk8mViOZks7T8L3GnJr\n" + - "TBaVvDyTzDJum/QYiahfO2qpfN/Oya2UILmqsBAeLyWpzbQsAyWBXfoUtkOUgnzK\n" + - "fk6QAKYrAgMBAAGjgaUwgaIwHQYDVR0OBBYEFEtmQi7jT1ijXOafPsfkrLwSVu9e\n" + - "MGMGA1UdIwRcMFqAFEtmQi7jT1ijXOafPsfkrLwSVu9eoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEAkKWxMc4+ODk5WwLXXweB8/IKfVfrizNn0KLEgsZ6xNXFIXDpiPGAFcgl\n" + - "MzFO424JgyvUulsUc/X16Cnuwwntkk6KUG7vEV7h4o9sAV7Cax3gfQE/EZFb4ybn\n" + - "aBm1UsujMKd/ovqbbbxJbmOWzCeo0QfIGleDEyh3NBBZ0i11Kiw=\n" + - "-----END CERTIFICATE-----"; - - // web server certificate, www.example.com - static String targetCertStr_A = - "-----BEGIN CERTIFICATE-----\n" + - "MIICVTCCAb6gAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNDE3MTIwNjA4WhcNMzIwMTAzMTIwNjA4WjBVMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxGDAWBgNV\n" + - "BAMTD3d3dy5leGFtcGxlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\n" + - "4zFp3PZNzsd3ZwG6FNNWO9eSN+UBymlf8oCwpKJM2tIinmMWvWIXnlx/2UXIfSAq\n" + - "QEG3aXkAFyEiGGpQlBbqcfrESsHsiz2pnnm5dG2v/eS0Bwz1jmcuNmwnh3UQw2Vl\n" + - "+BLk8ukdrLjiCT8jARiHExYf1Xg+wUqQ9y8NV26hdaUCAwEAAaNPME0wCwYDVR0P\n" + - "BAQDAgPoMB0GA1UdDgQWBBQwtx+gqzn2w4y82brXlp7tqBYEZDAfBgNVHSMEGDAW\n" + - "gBRLZkIu409Yo1zmnz7H5Ky8ElbvXjANBgkqhkiG9w0BAQQFAAOBgQAJWo8B6Ud+\n" + - "/OU+UcZLihlfMX02OSlK2ZB7mfqpj2G3JT9yb0A+VbY3uuajmaYYIIxl3kXGz/n8\n" + - "M2Q/Ux/MDxG+IFKHC26Kuj4dAQgzjq2pILVPTE2QnaQTNCsgVZtTaC47SG9FRSoC\n" + - "qvnIvn/oTpKSqus76I1cR4joDtiV2OEuVw==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8 - static String targetPrivateKey_A = - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOMxadz2Tc7Hd2cB\n" + - "uhTTVjvXkjflAcppX/KAsKSiTNrSIp5jFr1iF55cf9lFyH0gKkBBt2l5ABchIhhq\n" + - "UJQW6nH6xErB7Is9qZ55uXRtr/3ktAcM9Y5nLjZsJ4d1EMNlZfgS5PLpHay44gk/\n" + - "IwEYhxMWH9V4PsFKkPcvDVduoXWlAgMBAAECgYAqX2nuIyXp3fvgA0twXOYlbRRB\n" + - "Rn3qAXM6qFPJsNeCrFR2k+aG1cev6nKR1FkLNTeMGnWZv06MAcr5IML8i7WXyG4C\n" + - "LY/C0gedn94FDKFlln+bTENwQTGjn4lKysDA+IuNpasTeMCajbic+dPByhIdTOjZ\n" + - "iMCyxbLfpk40zQopVQJBAPyfGmkeHB3GjdbdgujWCGKb2UxBa4O8dy3O4l2yizTn\n" + - "uUqMGcwGY4ciNSVvZQ7jKo4vDmkSuYib4/woPChaNfMCQQDmO0BQuSWYGNtSwV35\n" + - "lafZfX1dNCLKm1iNA6A12evXgvQiE9WT4mqionig0VZW16HtiY4/BkHOcos/K9Um\n" + - "ARQHAkA8mkaRtSF1my5nv1gqVz5Hua+VdZQ/VDUbDiiL5cszc+ulkJqXsWirAG/T\n" + - "fTe3LJQG7A7+8fkEZrF4yoY0AAA1AkEAotokezULj5N9iAL5SzL9wIzQYV4ggfny\n" + - "YATBjXXxKccakwQ+ndWZIiMUeoS4ssLialhTgucVI0fIkU2a/r/ifwJAc6e+5Pvh\n" + - "MghQj/U788Od/v6rgqz/NGsduZ7uilCMcWiwA73OR2MHMH/OIuoofuEPrfuV9isV\n" + - "xVXhgpKfP/pdOA=="; - - // web server certificate, www.example.net - static String targetCertStr_B = - "-----BEGIN CERTIFICATE-----\n" + - "MIICVTCCAb6gAwIBAgIBBDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNDE3MTIwNjA5WhcNMzIwMTAzMTIwNjA5WjBVMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxGDAWBgNV\n" + - "BAMTD3d3dy5leGFtcGxlLm5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\n" + - "2VlzF1fvWYczDChrUeJiLJ1M/dIShCaOTfYGiXfQGEZCAWTacUclwr+rVMnZ75/c\n" + - "wwg5pNdXRijxMil8DBTS1gFcIFQhosLHvzIAe6ULlg/xB+/L6KBz+NTWfo/2KF6t\n" + - "xatmcToNrCcwi7eUOfbzQje65Tizs56jJYem2m7Rk0ECAwEAAaNPME0wCwYDVR0P\n" + - "BAQDAgPoMB0GA1UdDgQWBBQT/FR0cAWcZQ7h0X79KGki34OSQjAfBgNVHSMEGDAW\n" + - "gBRLZkIu409Yo1zmnz7H5Ky8ElbvXjANBgkqhkiG9w0BAQQFAAOBgQB67cPIT6fz\n" + - "6Ws8fBpYgW2ad4ci66i1WduBD9CpGFE+jRK2feRj6hvYBXocKj0AMWUFIEB2E3hA\n" + - "oIjxcf1GxIpHVl9DjlhxqXbA0Ktl7/NGNRlDSLTizOTl3FB1mMTlOGvXDVmpcFhl\n" + - "HuoP1hYvhTsBwPx5igGNchuPtDIUzL2mXw==\n" + - "-----END CERTIFICATE-----"; - - static String targetPrivateKey_B = - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANlZcxdX71mHMwwo\n" + - "a1HiYiydTP3SEoQmjk32Bol30BhGQgFk2nFHJcK/q1TJ2e+f3MMIOaTXV0Yo8TIp\n" + - "fAwU0tYBXCBUIaLCx78yAHulC5YP8Qfvy+igc/jU1n6P9ihercWrZnE6DawnMIu3\n" + - "lDn280I3uuU4s7OeoyWHptpu0ZNBAgMBAAECgYEAl19H26sfhD+32rDPxZCgBShs\n" + - "dZ33zVe45i0Bcn4iTLWpxKTDyf7eGps4rO2DvfKdYqt40ggzvSZIjUH9JcDe8GmG\n" + - "d3m0ILB7pg4jsFlpyeHpTO8grPLxA1G9s3o0DoFpz/rooqgFfe/DrRDmRoOSkgfV\n" + - "/gseIbgJHRO/Ctyvdh0CQQD6uFd0HxhH1jl/JzvPzIH4LSnPcdEh9zsMEb6uzh75\n" + - "9qL+IHD5N2I/pYZTKqDFIwhJf701+LKag55AX/zrDt7rAkEA3e00AbnwanDMa6Wj\n" + - "+gFekUQveSVra38LiihzCkyVvQpFjbiF1rUhSNQ0dpU5/hmrYF0C6H9VXAesfkUY\n" + - "WhpDgwJAYjgZOop77piDycZK7isFt32p5XSHIzFBVocVFlH1XKM8UyXOXDNQL/Le\n" + - "XnJSrSf+NRzvuNcG0PVC56Ey6brXpQJAY4M4vcltt5zq3R5CQBmbGRJ1IyKXX3Vx\n" + - "bDslEqoyvri7ZYgnY5aG3UxiVgYmIf3KrgQnCLAIS6MZQumiuMxsFwJAK5pEG063\n" + - "9ngUof4fDMvZphqZjZR1zMKz/V/9ge0DWBINaqFgsgebNu+MyImsC8C6WKjGmV/2\n" + - "f1MY0D7sC2vU/Q=="; - - // web server certificate, www.invalid.com - static String targetCertStr_C = - "-----BEGIN CERTIFICATE-----\n" + - "MIICVTCCAb6gAwIBAgIBAzANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNDE3MTIwNjA5WhcNMzIwMTAzMTIwNjA5WjBVMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxGDAWBgNV\n" + - "BAMTD3d3dy5pbnZhbGlkLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\n" + - "q6MyQwzCr2nJ41l0frmHL0qULSyW51MhevBC+1W28i0LE/efrmpwV3LdnlQEGFak\n" + - "DLDwtnff3iru8dSMcA7KdWVkivsE7ZTP+qFDaWBAy7XXiSsv6yZ2Nh4jJb0YcD28\n" + - "45zk2nAl5Az1/PuoTi1vpQxzFZKuBm1HGgz3MEZvBvMCAwEAAaNPME0wCwYDVR0P\n" + - "BAQDAgPoMB0GA1UdDgQWBBRRMifrND015Nm8N6gV5X7cg1YjjjAfBgNVHSMEGDAW\n" + - "gBRLZkIu409Yo1zmnz7H5Ky8ElbvXjANBgkqhkiG9w0BAQQFAAOBgQBjkUO6Ri/B\n" + - "uDC2gDMIyL5+NTe/1dPPQYM4HhCNa/KQYvU5lzCKO9Vpa+i+nyrUNNXUu8Tkyq4Y\n" + - "A+aGSm6+FT/i9rFwkYUdorBtD3KfQiwTIWrVERXBkWI5iZNaVZhx0TFy4vUpf65d\n" + - "QtwkbHpC66fdKc2EdLXkuY9KkmtZZJJ7YA==\n" + - "-----END CERTIFICATE-----"; - - static String targetPrivateKey_C = - "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKujMkMMwq9pyeNZ\n" + - "dH65hy9KlC0sludTIXrwQvtVtvItCxP3n65qcFdy3Z5UBBhWpAyw8LZ3394q7vHU\n" + - "jHAOynVlZIr7BO2Uz/qhQ2lgQMu114krL+smdjYeIyW9GHA9vOOc5NpwJeQM9fz7\n" + - "qE4tb6UMcxWSrgZtRxoM9zBGbwbzAgMBAAECgYASJDK40Y12Wvki1Z6xkkyOnBRj\n" + - "XfYpRykfxGtgA2RN3qLwHlk7Zzaul46DIKA6LlYynTUkJDF+Ww1cdDnP0lBlwcmM\n" + - "iD0ck3zYyYBLhQHuVbkK3SYE+ANRhM0icvvqANP2at/U4awQcPNEae/KCiecLNu3\n" + - "CJGqyhPDdrEAqPuJGQJBAN46pQC6l3yrcSYE2s53jSmsm2HVVOFlFXjU6k/RMTxG\n" + - "FfDJtGUAOQ37rPQ06ugr/gjLAmmPp+FXozaBdA32D80CQQDFuGRgv3WYqbglIcRL\n" + - "JRs6xlj9w1F97s/aiUenuwhIPNiUoRbV7mnNuZ/sGF0svOVE7SazRjuFX6UqL9Y9\n" + - "HzG/AkEA170pCI8cl4w8eUNHRB9trGKEKjMXhwVCFh7lJf2ZBcGodSzr8w2HVhrZ\n" + - "Ke7hiemDYffrbJ1oxmv05+o+x3r0lQJBAL6adVm2+FyFMFnLZXmzeb59O4jWY5bt\n" + - "Qz6/HG6bpO5OidMuP99YCHMkQQDOs/PO3Y5GuAoW6IY4n/Y9S2B80+0CQBl1/H9/\n" + - "0n/vrb6vW6Azds49tuS82RFAnOhtwTyBEajs08WF8rZQ3WD2RHJnH0+jjfL0anIp\n" + - "dQBSeNN7s7b6rRk="; - - // This is a certificate for client - static String targetCertStr_D= - "-----BEGIN CERTIFICATE-----\n" + - "MIICVDCCAb2gAwIBAgIBBTANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNDE3MTIwNjEwWhcNMzIwMTAzMTIwNjEwWjBUMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxFzAVBgNV\n" + - "BAMTDkludGVyT3AgVGVzdGVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDo\n" + - "Q/KoAIAC2ljFfW2KwjnxTzi4NQJeUuk2seqKpsAY8x4O5dvixzUl6142zmljapqi\n" + - "bJloQVpfB+CEc5/l4h5gzGRVzkuqP1oPzDrpZ5GsvmvuHenV/TzCIgX1cLETzQVt\n" + - "6Rk06okoBPnw3hDJEJiEc1Rv7HCE8p/p+SaiHrskwwIDAQABo08wTTALBgNVHQ8E\n" + - "BAMCA+gwHQYDVR0OBBYEFPr91O33RIGfFSqza2AwQIgE4QswMB8GA1UdIwQYMBaA\n" + - "FEtmQi7jT1ijXOafPsfkrLwSVu9eMA0GCSqGSIb3DQEBBAUAA4GBANIDFYgAhoj3\n" + - "B8u1YpqeoEp2Lt9TwrYBshaIrbmBPCwCGio0JIsoov3n8BCSg5F+8MnOtPl+TjeO\n" + - "0Ug+7guPdCk/wg8YNxLHgSsQlpcNJDjWiErqmUPVrg5BPPQb65qMund6KTmMN0y6\n" + - "4EbSmxRpZO/N0/5oK4umTk0EeXKNekBj\n" + - "-----END CERTIFICATE-----"; - - static String targetPrivateKey_D = - "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOhD8qgAgALaWMV9\n" + - "bYrCOfFPOLg1Al5S6Tax6oqmwBjzHg7l2+LHNSXrXjbOaWNqmqJsmWhBWl8H4IRz\n" + - "n+XiHmDMZFXOS6o/Wg/MOulnkay+a+4d6dX9PMIiBfVwsRPNBW3pGTTqiSgE+fDe\n" + - "EMkQmIRzVG/scITyn+n5JqIeuyTDAgMBAAECgYBw37yIKp4LRONJLnhSq6sO+0n8\n" + - "Mz6waiiN/Q6XTQwj09pysQAYCGlqwSRrDAqpVsBJWO+Ae+oYLrLMi4hUZnwN75v3\n" + - "pe1nXlrD11RmPLXwBxqFxNSvAs2FgLHZEtwHI7Bn8KybT/8bGkQ8csLceInYtMDD\n" + - "MuTyy2KRk/pj60zIKQJBAPgebQiAH6viFQ88AwHaNvQhlUfwmSC1i6f8LVoeqaHC\n" + - "lnP0LJBwlyDeeEInhHrCR2ibnCB6I/Pig+49XQgabK8CQQDvpJwuGEbsOO+3rkJJ\n" + - "OpOw4toG0QJZdRnT6l8I6BlboQRZSfFh+lGGahvFXkxc4KdUpJ7QPtXU7HHk6Huk\n" + - "8RYtAkA9CW8VGj+wTuuTVdX/jKjcIa7RhbSFwWNbrcOSWdys+Gt+luCnn6rt4QyA\n" + - "aaxDbquWZkFgE+voQR7nap0KM0XtAkAznd0WAJymHM1lXt9gLoHJQ9N6TGKZKiPa\n" + - "BU1a+cMcfV4WbVrUo7oTnZ9Fr73681iXXq3mZOJh7lvJ1llreZIxAkBEnbiTgEf4\n" + - "tvku68jHcRbRPmdS7CBSWNEBaHLOm4pUSTcxVTKKMHw7vmM5/UYUxJ8QNKCYxn6O\n" + - "+vtiBwBawwzN"; - - static String[] serverCerts = {targetCertStr_A, - targetCertStr_B, targetCertStr_C}; - static String[] serverKeys = {targetPrivateKey_A, - targetPrivateKey_B, targetPrivateKey_C}; - static String[] clientCerts = {targetCertStr_D}; - static String[] clientKeys = {targetPrivateKey_D}; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(false); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - try { - sslSocket.setSoTimeout(5000); - sslSocket.setSoLinger(true, 5); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - SSLSession session = sslSocket.getSession(); - checkCertificate(session.getLocalCertificates(), - clientRequestedHostname); - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(true); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - SNIHostName serverName = new SNIHostName(clientRequestedHostname); - List<SNIServerName> serverNames = new ArrayList<>(1); - serverNames.add(serverName); - SSLParameters params = sslSocket.getSSLParameters(); - params.setServerNames(serverNames); - sslSocket.setSSLParameters(params); - - try { - sslSocket.setSoTimeout(5000); - sslSocket.setSoLinger(true, 5); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - SSLSession session = sslSocket.getSession(); - checkCertificate(session.getPeerCertificates(), - clientRequestedHostname); - } finally { - sslSocket.close(); - } - } - - private static void checkCertificate(Certificate[] certs, - String hostname) throws Exception { - if (certs != null && certs.length != 0) { - X509Certificate x509Cert = (X509Certificate)certs[0]; - - String subject = x509Cert.getSubjectX500Principal().getName(); - - if (!subject.contains(hostname)) { - throw new Exception( - "Not the expected certificate: " + subject); - } - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String clientRequestedHostname; // server name indication - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - clientRequestedHostname = args[1]; - } - - private static SSLContext generateSSLContext(boolean isClient) - throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - ByteArrayInputStream is = - new ByteArrayInputStream(trustedCertStr.getBytes()); - Certificate trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - - String[] certStrs = null; - String[] keyStrs = null; - if (isClient) { - certStrs = clientCerts; - keyStrs = clientKeys; - } else { - certStrs = serverCerts; - keyStrs = serverKeys; - } - - for (int i = 0; i < certStrs.length; i++) { - // generate the private key. - String keySpecStr = keyStrs[i]; - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - String keyCertStr = certStrs[i]; - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - - // import the key entry. - ks.setKeyEntry("key-entry-" + i, priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - - return ctx; - } - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new SSLSocketSNISensitive(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketSNISensitive() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died, because of " + e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died, because of " + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLS/CipherTestUtils.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,689 +0,0 @@ -/** - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License version 2 only, as published by - * the Free Software Foundation. - * - * This code 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 version 2 for more - * details (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU General Public License version 2 - * along with this work; if not, write to the Free Software Foundation, Inc., 51 - * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or - * visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.security.KeyFactory; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.List; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509ExtendedKeyManager; -import javax.net.ssl.X509TrustManager; - -/** - * Test that all ciphersuites work in all versions and all client authentication - * types. The way this is setup the server is stateless and all checking is done - * on the client side. - */ - -public class CipherTestUtils { - - public static final int TIMEOUT = 20 * 1000; - public static final SecureRandom secureRandom = new SecureRandom(); - public static char[] PASSWORD = "passphrase".toCharArray(); - private static final List<TestParameters> TESTS = new ArrayList<>(3); - private static final List<Exception> EXCEPTIONS - = Collections.synchronizedList(new ArrayList<>(1)); - private static final String CLIENT_PUBLIC_KEY - = "-----BEGIN CERTIFICATE-----\n" - + "MIICtTCCAh4CCQDkYJ46DMcGRjANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n" - + "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n" - + "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n" - + "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n" - + "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n" - + "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n" - + "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n" - + "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IENsaWVudCAoMTAyNCBiaXQg\n" - + "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAm5rwjmhO7Nwd5GWs+KvQ\n" - + "UnDiqpRDvRriOUFdF0rCI2Op24C+iwUMDGxPsgP7VkUpOdJhw3c72aP0CAWcZ5dN\n" - + "UCW7WVDAxnogCahLCir1jjoGdEjiNGOy0L9sypsM9UvBzJN8uvXsxsTZX4Z88cKU\n" - + "G7RUvN8LQ88zDljk5zr3c2MCAwEAATANBgkqhkiG9w0BAQUFAAOBgQA7LUDrzHln\n" - + "EXuGmwZeeroACB6DVtkClMskF/Pj5GnTxoeNN9DggycX/eOeIDKRloHuMpBeZPJH\n" - + "NUwFu4LB6HBDeldQD9iRp8zD/fPakOdN+1Gk5hciIZZJ5hQmeCl7Va2Gr64vUqZG\n" - + "MkVU755t+7ByLgzWuhPhhsX9QCuPR5FjvQ==\n" - + "-----END CERTIFICATE-----"; - - private static final String CLIENT_PRIVATE_KEY - = "-----BEGIN PRIVATE KEY-----\n" - + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJua8I5oTuzcHeRl\n" - + "rPir0FJw4qqUQ70a4jlBXRdKwiNjqduAvosFDAxsT7ID+1ZFKTnSYcN3O9mj9AgF\n" - + "nGeXTVAlu1lQwMZ6IAmoSwoq9Y46BnRI4jRjstC/bMqbDPVLwcyTfLr17MbE2V+G\n" - + "fPHClBu0VLzfC0PPMw5Y5Oc693NjAgMBAAECgYA5w73zj8Nk6J3sMNaShe3S/PcY\n" - + "TewLopRCnwI46FbDnnbq9pNFtnzvi7HWKuY983THc1M5peTA+b1Y0QRr7F4Vg4x9\n" - + "9UM0B/tZcIIcJJ3LS+9fXKCbYLQWq5F05JqeZu+i+QLmJFO5+2p7laeQ4oQfW7QE\n" - + "YR4u2mSaLe0SsqHvOQJBAMhgcye9C6pJO0eo2/VtRxAXI7zxNAIjHwKo1cva7bhu\n" - + "GdrMaEAJBAsMJ1GEk7/WDI+3KEbTjQdfIJuAvOR4FXUCQQDGzNn/tl2k93v/ugyM\n" - + "/tBhCKDipYDIbyJMoG2AOtOGmCsiGo5L7idO4OAcm/QiHBQMXjFIVgTUcH8MhGj4\n" - + "blJ3AkA5fUqsxRV6tuYWKkFpif/QgwMS65VDY7Y6+hvVECwSNSyf1PO4I54QWV1S\n" - + "ixok+RHDjgY1Q+77hXSCiQ4o8rcdAkBHvjfR+5sx5IpgUGElJPRIgFenU3j1XH3x\n" - + "T1gVFaWuhg3S4eiGaGzRH4BhcrqY8K8fg4Kfi0N08yA2gTZsqUujAkEAjuNPTuKx\n" - + "ti0LXI09kbGUqOpRMm1zW5TD6LFeEaUN6oxrSZI2YUvu7VyotAqsxX5O0u0f3VQw\n" - + "ySF0Q1oZ6qu7cg==\n" - + "-----END PRIVATE KEY-----"; - private static final String SERVER_PUBLIC_KEY - = "-----BEGIN CERTIFICATE-----\n" - + "MIICtTCCAh4CCQDkYJ46DMcGRTANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n" - + "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n" - + "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n" - + "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n" - + "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n" - + "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n" - + "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n" - + "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IFNlcnZlciAoMTAyNCBiaXQg\n" - + "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArsHHeZ1O67yuxQKDSAOC\n" - + "Xm271ViwBrXkxe5cvhG8MCCem6Z3XeZ/m6c2ucRwLaQxnmG1m0G6/OYaUXTivjcG\n" - + "/K4bc1I+yjghAWQNLBtsOiP9w0LKibg3TSDehpeuuz/lmB5A4HMqQr8KkY4K7peD\n" - + "1QkJ2Dn3zhbwQ/0d8f5CCbkCAwEAATANBgkqhkiG9w0BAQUFAAOBgQBOd8XojEnu\n" - + "eTUHBwqfmnvRQvbICFDNbbL4KuX/JNPSy1WMGAEbNCTLZ+5yP69js8aUYqAk5vVf\n" - + "dWRLU3MDiEzW7zxE1ubuKWjVuyGbG8Me0G01Hw+evBcZqB64Fz3OFISVfQh7MqE/\n" - + "O0AeakRMH350FRLNl4o6KBSXmF/AADfqQQ==\n" - + "-----END CERTIFICATE-----"; - - private static final String SERVER_PRIVATE_KEY - = "-----BEGIN PRIVATE KEY-----\n" - + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK7Bx3mdTuu8rsUC\n" - + "g0gDgl5tu9VYsAa15MXuXL4RvDAgnpumd13mf5unNrnEcC2kMZ5htZtBuvzmGlF0\n" - + "4r43BvyuG3NSPso4IQFkDSwbbDoj/cNCyom4N00g3oaXrrs/5ZgeQOBzKkK/CpGO\n" - + "Cu6Xg9UJCdg5984W8EP9HfH+Qgm5AgMBAAECgYAXUv+3qJo+9mjxHHu/IdDFn6nB\n" - + "ONwNmTtWe5DfQWi3l7LznU0zOC9x6+hu9NvwC4kf1XSyqxw04tVCZ/JXZurEmEBz\n" - + "YtcQ5idRQDkKYXEDOeVUfvtHO6xilzrhPKxxd0GG/sei2pozikkqnYF3OcP0qL+a\n" - + "3nWixZQBRoF2nIRLcQJBAN97TJBr0XTRmE7OCKLUy1+ws7vZB9uQ2efHMsgwOpsY\n" - + "3cEW5qd95hrxLU72sBeu9loHQgBrT2Q3OAxnsPXmgO0CQQDIL3u9kS/O3Ukx+n1H\n" - + "JdPFQCRxrDm/vtJpQEmq+mLqxxnxCFRIYQ2ieAPokBxWeMDtdWJGD3VxhahjPfZm\n" - + "5K59AkEAuDVl0tVMfUIWjT5/F9jXGjUIsZofQ/iN5OLpFOHMLPO+Nd6umPjJpwON\n" - + "GT11wM/S+DprSPUrJ6vsYy1FTCuHsQJBAMXtnO07xgdE6AAQaRmVnyMiXmY+IQMj\n" - + "CyuhsrToyDDWFyIoWB0QSMjg3QxuoHYnAqpGK5qV4ksSGgG13BCz/okCQQCRHTgn\n" - + "DuFG2f7GYLFjI4NaTEzHGp+J9LiNYY1kYYLonpwAC3Z5hzJVanYT3/g23AUZ/fdF\n" - + "v5PDIViuPo5ZB1eD\n" - + "-----END PRIVATE KEY-----"; - - private static final String CA_PUBLIC_KEY - = "-----BEGIN CERTIFICATE-----\n" - + "MIIDCDCCAnGgAwIBAgIJAIYlGfwNBY6NMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n" - + "VQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAd\n" - + "BgNVBAoMFlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNy\n" - + "b3N5c3RlbXMgTGFib3JhdG9yaWVzMR8wHQYDVQQDDBZUZXN0IENBICgxMDI0IGJp\n" - + "dCBSU0EpMB4XDTA5MDQyNzA0MDQwOFoXDTEzMDYwNTA0MDQwOFowgZwxCzAJBgNV\n" - + "BAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEfMB0G\n" - + "A1UECgwWU3VuIE1pY3Jvc3lzdGVtcywgSW5jLjEmMCQGA1UECwwdU3VuIE1pY3Jv\n" - + "c3lzdGVtcyBMYWJvcmF0b3JpZXMxHzAdBgNVBAMMFlRlc3QgQ0EgKDEwMjQgYml0\n" - + "IFJTQSkwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOK4DJxxb0XX6MJ1CVjp\n" - + "9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+gdcOA\n" - + "GRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4z1q8\n" - + "LYbxyMVD1XNNNymvPM44OjsBAgMBAAGjUDBOMB0GA1UdDgQWBBT27BLUflmfdtbi\n" - + "WTgjwWnoxop2MTAfBgNVHSMEGDAWgBT27BLUflmfdtbiWTgjwWnoxop2MTAMBgNV\n" - + "HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAEQELNzhZpjnSgigd+QJ6I/3CPDo\n" - + "SDkMLdP1BHlT/DkMIZvABm+M09ePNlWiLYCNCsL9nWmX0gw0rFDKsTklZyKTUzaM\n" - + "oy/AZCrAaoIc6SO5m1xE1RMyVxd/Y/kg6cbfWxxCJFlMeU5rsSdC97HTE/lDyuoh\n" - + "BmlOBB7SdR+1ScjA\n" - + "-----END CERTIFICATE-----"; - - private static final String CA_PRIVATE_KEY - = "-----BEGIN PRIVATE KEY-----\n" - + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOK4DJxxb0XX6MJ1\n" - + "CVjp9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+g\n" - + "dcOAGRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4\n" - + "z1q8LYbxyMVD1XNNNymvPM44OjsBAgMBAAECgYEApmMOlk3FrQtsvjGof4GLp3Xa\n" - + "tmvs54FzxKhagj0C4UHelNyYpAJ9MLjNiGQ7I31yTeaNrUCAi0XSfsKTSrwbLSnJ\n" - + "qsUPKMBrnzcWrOyui2+cupHZXaTlNeYB97teLJYpa6Ql9CZLoTHoim1+//s7diBh\n" - + "03Vls+M6Poi5PMvv59UCQQD+k/BiokmbBgWHfBY5cZSlx3Z4VTwSHJmHDTO3Tjso\n" - + "EVErXUSVvqD/KHX6eM4VPM8lySV5djWV8lDsESCWMtiLAkEA4/xFNsiOLMQpxW/O\n" - + "bt2tukxJkAxldD4lPoFZR+zbXtMtt8OjERtX2wD+nj6h7jfIeSyVuBEcBN8Uj8xe\n" - + "kgfgIwJAPbKG4LCqHAsCjgpRrIxNVTwZByLJEy6hOqzFathn19cSj+rjs1Lm28/n\n" - + "f9OFRnpdTbAJB/3REM0QNZYVCrG57wJBAN0KuTytZJNouaswhPCew5Kt5mDgc/kp\n" - + "S8j3dk2zCto8W8Ygy1iJrzuqEjPxO+UQdrFtlde51vWuKGxnVIW3VwsCQEldqk7r\n" - + "8y7PgquPP+k3L0OXno5wGBrPcW1+U0mhIZGnwSzE4SPX2ddqUSEUA/Av4RjAckL/\n" - + "fpqmCkpTanyYW9U=\n" - + "-----END PRIVATE KEY-----"; - - private final SSLSocketFactory factory; - private final X509ExtendedKeyManager clientKeyManager; - private final X509ExtendedKeyManager serverKeyManager; - private final X509TrustManager clientTrustManager; - private final X509TrustManager serverTrustManager; - - static abstract class Server implements Runnable { - - final CipherTestUtils cipherTest; - - Server(CipherTestUtils cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - @Override - public abstract void run(); - - void handleRequest(InputStream in, OutputStream out) - throws IOException { - boolean newline = false; - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - throw new EOFException(); - } - sb.append((char) ch); - if (ch == '\r') { - // empty - } else if (ch == '\n') { - if (newline) { - // 2nd newline in a row, end of request - break; - } - newline = true; - } else { - newline = false; - } - } - String request = sb.toString(); - if (request.startsWith("GET / HTTP/1.") == false) { - throw new IOException("Invalid request: " + request); - } - out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes()); - out.write("Tested Scenario: ".getBytes()); - TestParameters tp = (TestParameters) CipherTestUtils.TESTS.get(0); - out.write(tp.toString().getBytes()); - out.write(" Test PASSED.".getBytes()); - } - } - - public static class TestParameters { - - String cipherSuite; - String protocol; - String clientAuth; - - TestParameters(String cipherSuite, String protocol, - String clientAuth) { - this.cipherSuite = cipherSuite; - this.protocol = protocol; - this.clientAuth = clientAuth; - } - - boolean isEnabled() { - return true; - } - - @Override - public String toString() { - String s = cipherSuite + " in " + protocol + " mode"; - if (clientAuth != null) { - s += " with " + clientAuth + " client authentication"; - } - return s; - } - } - - private static volatile CipherTestUtils instance = null; - - public static CipherTestUtils getInstance() throws IOException, - FileNotFoundException, KeyStoreException, - NoSuchAlgorithmException, CertificateException, - UnrecoverableKeyException, InvalidKeySpecException { - if (instance == null) { - synchronized (CipherTestUtils.class) { - if (instance == null) { - instance = new CipherTestUtils(); - } - } - } - return instance; - } - - public static void setTestedArguments(String testedProtocol, - String testedCipherSuite) { - - TestParameters testedParams; - - String cipherSuite = testedCipherSuite.trim(); - if (cipherSuite.startsWith("SSL_")) { - testedParams = - new TestParameters(cipherSuite, testedProtocol, null); - TESTS.add(testedParams); - - } else { - System.out.println("Your input Cipher suites is not correct, " - + "please try another one ."); - } - } - - public X509ExtendedKeyManager getClientKeyManager() { - return clientKeyManager; - } - - public X509TrustManager getClientTrustManager() { - return clientTrustManager; - } - - public X509ExtendedKeyManager getServerKeyManager() { - return serverKeyManager; - } - - public X509TrustManager getServerTrustManager() { - return serverTrustManager; - } - - public static void addFailure(Exception e) { - EXCEPTIONS.add(e); - } - - private CipherTestUtils() - throws IOException, FileNotFoundException, KeyStoreException, - NoSuchAlgorithmException, CertificateException, - UnrecoverableKeyException, InvalidKeySpecException { - factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY, - SERVER_PRIVATE_KEY); - KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY, - CA_PRIVATE_KEY); - - if (serverKeyStore != null) { - KeyManagerFactory keyFactory1 - = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - keyFactory1.init(serverKeyStore, PASSWORD); - serverKeyManager = (X509ExtendedKeyManager) keyFactory1. - getKeyManagers()[0]; - } else { - serverKeyManager = null; - } - serverTrustManager = serverTrustStore != null - ? new AlwaysTrustManager(serverTrustStore) : null; - - KeyStore clientKeyStore, clientTrustStore; - clientTrustStore = serverTrustStore; - clientKeyStore = - createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY); - if (clientKeyStore != null) { - KeyManagerFactory keyFactory - = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - keyFactory.init(clientKeyStore, PASSWORD); - clientKeyManager = (X509ExtendedKeyManager) keyFactory. - getKeyManagers()[0]; - } else { - clientKeyManager = null; - } - clientTrustManager = (clientTrustStore != null) - ? new AlwaysTrustManager(clientTrustStore) : null; - } - - void checkResult(String exception) throws Exception { - if (EXCEPTIONS.size() >= 1) { - Exception actualException = EXCEPTIONS.get(0); - if (exception == null) { - throw new RuntimeException("FAILED: got unexpected exception: " - + actualException); - } - if (!exception.equals(actualException.getClass().getName())) { - throw new RuntimeException("FAILED: got unexpected exception: " - + actualException); - } - - System.out.println("PASSED: got expected exception: " - + actualException); - } else { - if (exception != null) { - throw new RuntimeException("FAILED: " + exception - + " was expected"); - } - System.out.println("PASSED"); - } - } - - SSLSocketFactory getFactory() { - return factory; - } - - static abstract class Client implements Runnable { - - final CipherTestUtils cipherTest; - TestParameters testedParams; - - Client(CipherTestUtils cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - Client(CipherTestUtils cipherTest, - String testedCipherSuite) throws Exception { - this.cipherTest = cipherTest; - } - - @Override - public final void run() { - - TESTS.stream().map((params) -> { - if (!params.isEnabled()) { - System.out.println("Skipping disabled test " + params); - } - return params; - }).forEach((params) -> { - try { - runTest(params); - System.out.println("Passed " + params); - } catch (Exception e) { - CipherTestUtils.addFailure(e); - System.out.println("** Failed " + params - + "**, got exception:"); - e.printStackTrace(System.err); - } - }); - } - - abstract void runTest(TestParameters params) throws Exception; - - void sendRequest(InputStream in, OutputStream out) throws IOException { - out.write("GET / HTTP/1.0\r\n\r\n".getBytes()); - out.flush(); - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - break; - } - sb.append((char) ch); - } - String response = sb.toString(); - if (response.startsWith("HTTP/1.0 200 ") == false) { - throw new IOException("Invalid response: " + response); - } else { - System.out.println(); - System.out.println("--- Response --- "); - System.out.println(response); - System.out.println("---------------- "); - } - } - } - - public static void printStringArray(String[] stringArray) { - System.out.print(stringArray.length + " : "); - for (String stringArray1 : stringArray) { - System.out.print(stringArray1); - System.out.print(","); - } - System.out.println(); - } - - public static void printInfo(SSLServerSocket socket) { - System.out.println(); - System.out.println("--- SSL ServerSocket Info ---"); - System.out.print("SupportedProtocols : "); - printStringArray(socket.getSupportedProtocols()); - System.out.print("SupportedCipherSuites : "); - printStringArray(socket.getSupportedCipherSuites()); - System.out.print("EnabledProtocols : "); - printStringArray(socket.getEnabledProtocols()); - System.out.print("EnabledCipherSuites : "); - String[] supportedCipherSuites = socket.getEnabledCipherSuites(); - Arrays.sort(supportedCipherSuites); - printStringArray(supportedCipherSuites); - System.out.println("NeedClientAuth : " - + socket.getNeedClientAuth()); - System.out.println("WantClientAuth : " - + socket.getWantClientAuth()); - System.out.println("-----------------------"); - } - - public static void printInfo(SSLSocket socket) { - System.out.println(); - System.out.println("--- SSL Socket Info ---"); - System.out.print(" SupportedProtocols : "); - printStringArray(socket.getSupportedProtocols()); - System.out.println(" EnabledProtocols : " - + socket.getEnabledProtocols()[0]); - System.out.print(" SupportedCipherSuites : "); - String[] supportedCipherSuites = socket.getEnabledCipherSuites(); - Arrays.sort(supportedCipherSuites); - printStringArray(supportedCipherSuites); - System.out.println(" EnabledCipherSuites : " - + socket.getEnabledCipherSuites()[0]); - System.out.println(" NeedClientAuth : " - + socket.getNeedClientAuth()); - System.out.println(" WantClientAuth : " - + socket.getWantClientAuth()); - System.out.println("-----------------------"); - } - - private static KeyStore createServerKeyStore(String publicKeyStr, - String keySpecStr) throws KeyStoreException, IOException, - NoSuchAlgorithmException, CertificateException, - InvalidKeySpecException { - - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - if (publicKeyStr == null || keySpecStr == null) { - throw new IllegalArgumentException("publicKeyStr or " - + "keySpecStr cannot be null"); - } - String strippedPrivateKey = keySpecStr.substring( - keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n")); - - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(strippedPrivateKey)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey - = (RSAPrivateKey) kf.generatePrivate(priKeySpec); - - // generate certificate chain - try (InputStream is = - new ByteArrayInputStream(publicKeyStr.getBytes())) { - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - Certificate keyCert = cf.generateCertificate(is); - Certificate[] chain = {keyCert}; - ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain); - } - - return ks; - } - - public static void main(PeerFactory peerFactory, String mode, - String expectedException) - throws Exception { - long time = System.currentTimeMillis(); - setTestedArguments(peerFactory.getTestedProtocol(), - peerFactory.getTestedCipher()); - - System.out.print( - " Initializing test '" + peerFactory.getName() + "'..."); - secureRandom.nextInt(); - - CipherTestUtils cipherTest = CipherTestUtils.getInstance(); - if (mode.equalsIgnoreCase("Server")) { // server mode - Thread serverThread = new Thread(peerFactory.newServer(cipherTest), - "Server"); - serverThread.start(); - } else if (mode.equalsIgnoreCase("Client")) { - peerFactory.newClient(cipherTest).run(); - cipherTest.checkResult(expectedException); - JSSEServer.closeServer = true; - } else { - throw new RuntimeException("unsupported mode"); - } - time = System.currentTimeMillis() - time; - System.out.println("Elapsed time " + time); - - } - - public static abstract class PeerFactory { - - abstract String getName(); - - abstract String getTestedProtocol(); - - abstract String getTestedCipher(); - - abstract Client newClient(CipherTestUtils cipherTest) throws Exception; - - abstract Server newServer(CipherTestUtils cipherTest) throws Exception; - - boolean isSupported(String cipherSuite) { - return true; - } - } -} - -class AlwaysTrustManager implements X509TrustManager { - - X509TrustManager trustManager; - - public AlwaysTrustManager(KeyStore keyStore) - throws NoSuchAlgorithmException, KeyStoreException { - - TrustManagerFactory tmf - = TrustManagerFactory.getInstance(TrustManagerFactory. - getDefaultAlgorithm()); - tmf.init(keyStore); - - TrustManager tms[] = tmf.getTrustManagers(); - for (TrustManager tm : tms) { - trustManager = (X509TrustManager) tm; - return; - } - - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - try { - trustManager.checkClientTrusted(chain, authType); - } catch (CertificateException excep) { - System.out.println("ERROR in client trust manager"); - } - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - try { - trustManager.checkServerTrusted(chain, authType); - } catch (CertificateException excep) { - System.out.println("ERROR in server Trust manger"); - } - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return trustManager.getAcceptedIssuers(); - } -} - -class MyX509KeyManager extends X509ExtendedKeyManager { - - private final X509ExtendedKeyManager keyManager; - private String authType; - - MyX509KeyManager(X509ExtendedKeyManager keyManager) { - this.keyManager = keyManager; - } - - void setAuthType(String authType) { - this.authType = "ECDSA".equals(authType) ? "EC" : authType; - } - - @Override - public String[] getClientAliases(String keyType, Principal[] issuers) { - if (authType == null) { - return null; - } - return keyManager.getClientAliases(authType, issuers); - } - - @Override - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - if (authType == null) { - return null; - } - return keyManager.chooseClientAlias(new String[]{authType}, - issuers, socket); - } - - @Override - public String chooseEngineClientAlias(String[] keyType, - Principal[] issuers, SSLEngine engine) { - if (authType == null) { - return null; - } - return keyManager.chooseEngineClientAlias(new String[]{authType}, - issuers, engine); - } - - @Override - public String[] getServerAliases(String keyType, Principal[] issuers) { - throw new UnsupportedOperationException("Servers not supported"); - } - - @Override - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - throw new UnsupportedOperationException("Servers not supported"); - } - - @Override - public String chooseEngineServerAlias(String keyType, Principal[] issuers, - SSLEngine engine) { - throw new UnsupportedOperationException("Servers not supported"); - } - - @Override - public X509Certificate[] getCertificateChain(String alias) { - return keyManager.getCertificateChain(alias); - } - - @Override - public PrivateKey getPrivateKey(String alias) { - return keyManager.getPrivateKey(alias); - } -}
--- a/test/javax/net/ssl/TLS/JSSEClient.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License version 2 only, as published by - * the Free Software Foundation. - * - * This code 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 version 2 for more - * details (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU General Public License version 2 - * along with this work; if not, write to the Free Software Foundation, Inc., 51 - * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or - * visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.InputStream; -import java.io.OutputStream; -import java.security.cert.Certificate; -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; - -class JSSEClient extends CipherTestUtils.Client { - - private static final String DEFAULT = "DEFAULT"; - private static final String TLS = "TLS"; - - private final SSLContext sslContext; - private final MyX509KeyManager keyManager; - private final int serverPort; - private final String serverHost; - private final String testedProtocol; - - JSSEClient(CipherTestUtils cipherTest, String serverHost, int serverPort, - String testedProtocols, String testedCipherSuite) throws Exception { - super(cipherTest, testedCipherSuite); - this.serverHost = serverHost; - this.serverPort = serverPort; - this.testedProtocol = testedProtocols; - this.keyManager = - new MyX509KeyManager(cipherTest.getClientKeyManager()); - sslContext = SSLContext.getInstance(TLS); - } - - @Override - void runTest(CipherTestUtils.TestParameters params) throws Exception { - SSLSocket socket = null; - try { - System.out.println("Connecting to server..."); - keyManager.setAuthType(params.clientAuth); - sslContext.init(new KeyManager[]{keyManager}, - new TrustManager[]{cipherTest.getClientTrustManager()}, - CipherTestUtils.secureRandom); - SSLSocketFactory factory = (SSLSocketFactory) sslContext. - getSocketFactory(); - socket = (SSLSocket) factory.createSocket(serverHost, - serverPort); - socket.setSoTimeout(CipherTestUtils.TIMEOUT); - socket.setEnabledCipherSuites(params.cipherSuite.split(",")); - if (params.protocol != null && !params.protocol.trim().equals("") - && !params.protocol.trim().equals(DEFAULT)) { - socket.setEnabledProtocols(params.protocol.split(",")); - } - CipherTestUtils.printInfo(socket); - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - sendRequest(in, out); - SSLSession session = socket.getSession(); - session.invalidate(); - String cipherSuite = session.getCipherSuite(); - if (params.cipherSuite.equals(cipherSuite) == false) { - throw new RuntimeException("Negotiated ciphersuite mismatch: " - + cipherSuite + " != " + params.cipherSuite); - } - String protocol = session.getProtocol(); - if (!DEFAULT.equals(params.protocol) - && !params.protocol.contains(protocol)) { - throw new RuntimeException("Negotiated protocol mismatch: " - + protocol + " != " + params.protocol); - } - if (!cipherSuite.contains("DH_anon")) { - session.getPeerCertificates(); - } - Certificate[] certificates = session.getLocalCertificates(); - if (params.clientAuth == null) { - if (certificates != null) { - throw new RuntimeException("Local certificates " - + "should be null"); - } - } else { - if ((certificates == null) || (certificates.length == 0)) { - throw new RuntimeException("Certificates missing"); - } - String keyAlg = certificates[0].getPublicKey().getAlgorithm(); - if ("EC".equals(keyAlg)) { - keyAlg = "ECDSA"; - } - if (params.clientAuth == null ? keyAlg != null - : !params.clientAuth.equals(keyAlg)) { - throw new RuntimeException("Certificate type mismatch: " - + keyAlg + " != " + params.clientAuth); - } - } - } finally { - if (socket != null) { - socket.close(); - } - } - } -}
--- a/test/javax/net/ssl/TLS/JSSEServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -/** - * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License version 2 only, as published by - * the Free Software Foundation. - * - * This code 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 version 2 for more - * details (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU General Public License version 2 - * along with this work; if not, write to the Free Software Foundation, Inc., 51 - * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or - * visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; - -public class JSSEServer extends CipherTestUtils.Server { - - private final SSLServerSocket serverSocket; - private final int serverPort; - static volatile boolean closeServer = false; - - JSSEServer(CipherTestUtils cipherTest, int serverPort, - String protocol, String cipherSuite) throws Exception { - super(cipherTest); - this.serverPort = serverPort; - SSLContext serverContext = SSLContext.getInstance("TLS"); - serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()}, - new TrustManager[]{cipherTest.getServerTrustManager()}, - CipherTestUtils.secureRandom); - SSLServerSocketFactory factory = - (SSLServerSocketFactory)serverContext.getServerSocketFactory(); - serverSocket = - (SSLServerSocket) factory.createServerSocket(serverPort); - serverSocket.setEnabledProtocols(protocol.split(",")); - serverSocket.setEnabledCipherSuites(cipherSuite.split(",")); - - CipherTestUtils.printInfo(serverSocket); - } - - @Override - public void run() { - System.out.println("JSSE Server listening on port " + serverPort); - while (!closeServer) { - try (final SSLSocket socket = (SSLSocket) serverSocket.accept()) { - socket.setSoTimeout(CipherTestUtils.TIMEOUT); - - try (InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream()) { - handleRequest(in, out); - out.flush(); - } catch (IOException e) { - CipherTestUtils.addFailure(e); - System.out.println("Got IOException:"); - e.printStackTrace(System.err); - } - } catch (Exception e) { - CipherTestUtils.addFailure(e); - System.out.println("Exception:"); - e.printStackTrace(System.err); - } - } - } -}
--- a/test/javax/net/ssl/TLS/TLSClientPropertyTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.List; -import javax.net.ssl.SSLContext; - -/* - * @test - * @bug 8049432 8069038 - * @summary New tests for TLS property jdk.tls.client.protocols - * @summary javax/net/ssl/TLS/TLSClientPropertyTest.java needs to be - * updated for JDK-8061210 - * @run main/othervm TLSClientPropertyTest NoProperty - * @run main/othervm TLSClientPropertyTest SSLv3 - * @run main/othervm TLSClientPropertyTest TLSv1 - * @run main/othervm TLSClientPropertyTest TLSv11 - * @run main/othervm TLSClientPropertyTest TLSv12 - * @run main/othervm TLSClientPropertyTest WrongProperty - */ - -/** - * Sets the property jdk.tls.client.protocols to one of this protocols: - * SSLv3,TLSv1,TLSv1.1,TLSv1.2 and TLSV(invalid) or removes this - * property (if any),then validates the default, supported and current - * protocols in the SSLContext. - */ -public class TLSClientPropertyTest { - private final String[] expectedSupportedProtos = new String[] { - "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" - }; - - public static void main(String[] args) throws Exception { - - if (args.length < 1) { - throw new RuntimeException( - "Incorrect arguments,expected arguments: testCase"); - } - - String[] expectedDefaultProtos; - String testCase = args[0]; - String contextProtocol; - switch (testCase) { - case "NoProperty": - if (System.getProperty("jdk.tls.client.protocols") != null) { - System.getProperties().remove("jdk.tls.client.protocols"); - } - contextProtocol = null; - expectedDefaultProtos = new String[] { - "TLSv1", "TLSv1.1", "TLSv1.2" - }; - break; - case "SSLv3": - contextProtocol = "SSLv3"; - expectedDefaultProtos = new String[] { - }; - break; - case "TLSv1": - contextProtocol = "TLSv1"; - expectedDefaultProtos = new String[] { - "TLSv1" - }; - break; - case "TLSv11": - contextProtocol = "TLSv1.1"; - expectedDefaultProtos = new String[] { - "TLSv1", "TLSv1.1" - }; - break; - case "TLSv12": - contextProtocol = "TLSv1.2"; - expectedDefaultProtos = new String[] { - "TLSv1", "TLSv1.1", "TLSv1.2" - }; - break; - case "WrongProperty": - expectedDefaultProtos = new String[] {}; - contextProtocol = "TLSV"; - break; - default: - throw new RuntimeException("test case is wrong"); - } - if (contextProtocol != null) { - System.setProperty("jdk.tls.client.protocols", contextProtocol); - } - try { - TLSClientPropertyTest test = new TLSClientPropertyTest(); - test.test(contextProtocol, expectedDefaultProtos); - if (testCase.equals("WrongProperty")) { - throw new RuntimeException( - "Test failed: NoSuchAlgorithmException " + - "is expected when input wrong protocol"); - } else { - System.out.println("Test " + contextProtocol + " passed"); - } - } catch (NoSuchAlgorithmException nsae) { - if (testCase.equals("WrongProperty")) { - System.out.println("NoSuchAlgorithmException is expected," - + contextProtocol + " test passed"); - } else { - throw nsae; - } - } - - } - - /** - * The parameter passed is the user enforced protocol. Does not catch - * NoSuchAlgorithmException, WrongProperty test will use it. - */ - public void test(String expectedContextProto, - String[] expectedDefaultProtos) throws NoSuchAlgorithmException { - - SSLContext context = null; - try { - if (expectedContextProto != null) { - context = SSLContext.getInstance(expectedContextProto); - context.init(null, null, null); - } else { - context = SSLContext.getDefault(); - } - printContextDetails(context); - } catch (KeyManagementException ex) { - error(null, ex); - } - - validateContext(expectedContextProto, expectedDefaultProtos, context); - } - - /** - * Simple print utility for SSLContext's protocol details. - */ - private void printContextDetails(SSLContext context) { - System.out.println("Default Protocols: " - + Arrays.toString(context.getDefaultSSLParameters() - .getProtocols())); - System.out.println("Supported Protocols: " - + Arrays.toString(context.getSupportedSSLParameters() - .getProtocols())); - System.out.println("Current Protocol : " + context.getProtocol()); - - } - - /** - * Error handler. - */ - private void error(String msg, Throwable tble) { - String finalMsg = "FAILED " + (msg != null ? msg : ""); - if (tble != null) { - throw new RuntimeException(finalMsg, tble); - } - throw new RuntimeException(finalMsg); - } - - /** - * Validates the SSLContext's protocols against the user enforced protocol. - */ - private void validateContext(String expectedProto, - String[] expectedDefaultProtos, SSLContext context) { - if (expectedProto == null) { - expectedProto = "Default"; - } - if (!context.getProtocol().equals(expectedProto)) { - error("Invalid current protocol: " + context.getProtocol() - + ", Expected:" + expectedProto, null); - } - List<String> actualDefaultProtos = Arrays.asList(context - .getDefaultSSLParameters().getProtocols()); - for (String p : expectedDefaultProtos) { - if (!actualDefaultProtos.contains(p)) { - error("Default protocol " + p + "missing", null); - } - } - List<String> actualSupportedProtos = Arrays.asList(context - .getSupportedSSLParameters().getProtocols()); - - for (String p : expectedSupportedProtos) { - if (!actualSupportedProtos.contains(p)) { - error("Expected to support protocol:" + p, null); - } - } - } -}
--- a/test/javax/net/ssl/TLS/TestJSSE.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,188 +0,0 @@ -/** - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License version 2 only, as published by - * the Free Software Foundation. - * - * This code 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 version 2 for more - * details (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU General Public License version 2 - * along with this work; if not, write to the Free Software Foundation, Inc., 51 - * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or - * visit www.oracle.com if you need additional information or have any - * questions. - */ - -import static java.lang.System.out; -import java.security.Provider; -import java.security.Security; - -/** - * @test - * @bug 8049429 - * @library ../../../../lib/testlibrary/ - * @build jdk.testlibrary.Utils - * @compile CipherTestUtils.java JSSEClient.java JSSEServer.java - * @summary Test that all cipher suites work in all versions and all client - * authentication types. The way this is setup the server is stateless and - * all checking is done on the client side. - * @run main/othervm -DSERVER_PROTOCOL=SSLv3 - * -DCLIENT_PROTOCOL=SSLv3 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=TLSv1 - * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=TLSv1.1 - * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=TLSv1.2 - * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1 - * -DCLIENT_PROTOCOL=TLSv1 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1,TLSv1.1 - * -DCLIENT_PROTOCOL=TLSv1.1 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv3 - * -DCLIENT_PROTOCOL=TLSv1.1,TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 - * TestJSSE javax.net.ssl.SSLHandshakeException - * @run main/othervm -DSERVER_PROTOCOL=TLSv1 - * -DCLIENT_PROTOCOL=TLSv1.1,TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 - * TestJSSE javax.net.ssl.SSLHandshakeException - * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCLIENT_PROTOCOL=TLSv1.2 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1 - * -DCLIENT_PROTOCOL=DEFAULT -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCLIENT_PROTOCOL=DEFAULT -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1,TLSv1.1,TLSv1.2 - * -DCLIENT_PROTOCOL=DEFAULT -Djdk.tls.client.protocols=TLSv1 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE - * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1 - * -DCLIENT_PROTOCOL=DEFAULT -Djdk.tls.client.protocols=TLSv1.2 - * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 - * TestJSSE javax.net.ssl.SSLHandshakeException - * - */ - -public class TestJSSE { - - private static final String LOCAL_IP = "127.0.0.1"; - - public static void main(String... args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - String serverProtocol = System.getProperty("SERVER_PROTOCOL"); - String clientProtocol = System.getProperty("CLIENT_PROTOCOL"); - int port = jdk.testlibrary.Utils.getFreePort(); - String cipher = System.getProperty("CIPHER"); - if (serverProtocol == null - || clientProtocol == null - || cipher == null) { - throw new IllegalArgumentException("SERVER_PROTOCOL " - + "or CLIENT_PROTOCOL or CIPHER is missing"); - } - out.println("ServerProtocol =" + serverProtocol); - out.println("ClientProtocol =" + clientProtocol); - out.println("Cipher =" + cipher); - server(serverProtocol, cipher, port, args); - client(port, clientProtocol, cipher, args); - - } - - public static void client(int testPort, - String testProtocols, String testCipher, - String... exception) throws Exception { - String expectedException = exception.length >= 1 - ? exception[0] : null; - out.println("========================================="); - out.println(" Testing - https://" + LOCAL_IP + ":" + testPort); - out.println(" Testing - Protocol : " + testProtocols); - out.println(" Testing - Cipher : " + testCipher); - Provider p = new sun.security.ec.SunEC(); - Security.insertProviderAt(p, 1); - try { - CipherTestUtils.main(new JSSEFactory(LOCAL_IP, - testPort, testProtocols, - testCipher, "client JSSE"), - "client", expectedException); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public static void server(String testProtocol, String testCipher, - int testPort, - String... exception) throws Exception { - String expectedException = exception.length >= 1 - ? exception[0] : null; - out.println(" This is Server"); - out.println(" Testing Protocol: " + testProtocol); - out.println(" Testing Cipher: " + testCipher); - out.println(" Testing Port: " + testPort); - Provider p = new sun.security.ec.SunEC(); - Security.insertProviderAt(p, 1); - try { - CipherTestUtils.main(new JSSEFactory(null, testPort, - testProtocol, testCipher, "Server JSSE"), - "Server", expectedException); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static class JSSEFactory extends CipherTestUtils.PeerFactory { - - final String testedCipherSuite, testedProtocol, testHost; - final int testPort; - final String name; - - JSSEFactory(String testHost, int testPort, String testedProtocol, - String testedCipherSuite, String name) { - this.testedCipherSuite = testedCipherSuite; - this.testedProtocol = testedProtocol; - this.testHost = testHost; - this.testPort = testPort; - this.name = name; - } - - @Override - String getName() { - return name; - } - - @Override - String getTestedCipher() { - return testedCipherSuite; - } - - @Override - String getTestedProtocol() { - return testedProtocol; - } - - @Override - CipherTestUtils.Client newClient(CipherTestUtils cipherTest) - throws Exception { - return new JSSEClient(cipherTest, testHost, testPort, - testedProtocol, testedCipherSuite); - } - - @Override - CipherTestUtils.Server newServer(CipherTestUtils cipherTest) - throws Exception { - return new JSSEServer(cipherTest, testPort, - testedProtocol, testedCipherSuite); - } - } -}
--- a/test/javax/net/ssl/TLSv11/ExportableBlockCipher.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,330 +0,0 @@ -/* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4873188 - * @summary Support TLS 1.1 - * @run main/othervm ExportableBlockCipher - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * - * @author Xuelei Fan - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class ExportableBlockCipher { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - boolean interrupted = false; - try { - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - } catch (SSLException ssle) { - // get the expected exception - interrupted = true; - } finally { - sslSocket.close(); - } - - if (!interrupted) { - throw new SSLHandshakeException( - "A weak cipher suite is negotiated, " + - "TLSv1.1 must not negotiate the exportable cipher suites."); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - // enable TLSv1.1 only - sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"}); - - // enable a exportable block cipher - sslSocket.setEnabledCipherSuites( - new String[] {"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - boolean interrupted = false; - try { - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - } catch (SSLException ssle) { - // get the expected exception - interrupted = true; - } finally { - sslSocket.close(); - } - - if (!interrupted) { - throw new SSLHandshakeException( - "A weak cipher suite is negotiated, " + - "TLSv1.1 must not negotiate the exportable cipher suites."); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ExportableBlockCipher(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ExportableBlockCipher() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv11/ExportableStreamCipher.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,330 +0,0 @@ -/* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4873188 - * @summary Support TLS 1.1 - * @run main/othervm ExportableStreamCipher - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * - * @author Xuelei Fan - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class ExportableStreamCipher { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - boolean interrupted = false; - try { - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - } catch (SSLException ssle) { - // get the expected exception - interrupted = true; - } finally { - sslSocket.close(); - } - - if (!interrupted) { - throw new SSLHandshakeException( - "A weak cipher suite is negotiated, " + - "TLSv1.1 must not negotiate the exportable cipher suites."); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - // enable TLSv1.1 only - sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"}); - - // enable a exportable stream cipher - sslSocket.setEnabledCipherSuites( - new String[] {"SSL_RSA_EXPORT_WITH_RC4_40_MD5"}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - boolean interrupted = false; - try { - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - } catch (SSLException ssle) { - // get the expected exception - interrupted = true; - } finally { - sslSocket.close(); - } - - if (!interrupted) { - throw new SSLHandshakeException( - "A weak cipher suite is negotiated, " + - "TLSv1.1 must not negotiate the exportable cipher suites."); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ExportableStreamCipher(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ExportableStreamCipher() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv12/DisabledShortDSAKeys.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,441 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 8139565 - * @summary Restrict certificates with DSA keys less than 1024 bits - * - * @run main/othervm DisabledShortDSAKeys PKIX TLSv1.2 - * @run main/othervm DisabledShortDSAKeys SunX509 TLSv1.2 - * @run main/othervm DisabledShortDSAKeys PKIX TLSv1.1 - * @run main/othervm DisabledShortDSAKeys SunX509 TLSv1.1 - * @run main/othervm DisabledShortDSAKeys PKIX TLSv1 - * @run main/othervm DisabledShortDSAKeys SunX509 TLSv1 - * @run main/othervm DisabledShortDSAKeys PKIX SSLv3 - * @run main/othervm DisabledShortDSAKeys SunX509 SSLv3 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class DisabledShortDSAKeys { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDDjCCAs2gAwIBAgIJAO5/hbm1ByJOMAkGByqGSM44BAMwHzELMAkGA1UEBhMC\n" + - "VVMxEDAOBgNVBAoTB0V4YW1wbGUwHhcNMTYwMjE2MDQzNTQ2WhcNMzcwMTI2MDQz\n" + - "NTQ2WjAfMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXhhbXBsZTCCAbgwggEsBgcq\n" + - "hkjOOAQBMIIBHwKBgQC4aSK8nBYdWJtuBkz6yoDyjZnNuGFSpDmx1ggKpLpcnPuw\n" + - "YKAbUhqdYhZtaIqQ4aO0T1ZS/HuOM0zvddnMUidFNX3RUvDkvdD/JYOnjqzCm+xW\n" + - "U0NFuPHZdapQY5KFk3ugkqZpHLY1StZbu0qugZOZjbBOMwB7cHAbMDuVpEr8DQIV\n" + - "AOi+ig+h3okFbWEE9MztiI2+DqNrAoGBAKh2EZbuWU9NoHglhVzfDUoz8CeyW6W6\n" + - "rUZuIOQsjWaYOeRPWX0UVAGq9ykIOfamEpurKt4H8ge/pHaL9iazJjonMHOXG12A\n" + - "0lALsMDGv22zVaJzXjOBvdPzc87opr0LIVgHASKOcDYjsICKNYPlS2cL3MJoD+bj\n" + - "NAR67b90VBbEA4GFAAKBgQCGrkRp2tdj2mZF7Qz0tO6p3xSysbEfN6QZxOJYPTvM\n" + - "yIYfLV9Yoy7XaRd/mCpJo/dqmsZMzowtyi+u+enuVpOLKiq/lyCktL+xUzZAjLT+\n" + - "9dafHlS1wR3pDSa1spo9xTEi4Ff/DQDHcdGalBxSXX/UdRtSecIYAp5/fkt3QZ5v\n" + - "0aOBkTCBjjAdBgNVHQ4EFgQUX4qbP5PgBx1J8BJ8qEgfoKVLSnQwTwYDVR0jBEgw\n" + - "RoAUX4qbP5PgBx1J8BJ8qEgfoKVLSnShI6QhMB8xCzAJBgNVBAYTAlVTMRAwDgYD\n" + - "VQQKEwdFeGFtcGxlggkA7n+FubUHIk4wDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8E\n" + - "BAMCAgQwCQYHKoZIzjgEAwMwADAtAhUAkr5bINXyy/McAx6qwhb6r0/QJUgCFFUP\n" + - "CZokA4/NqJIgq8ThpTQAE8SB\n" + - "-----END CERTIFICATE-----"; - - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICUjCCAhGgAwIBAgIJAIiDrs/4W8rtMAkGByqGSM44BAMwHzELMAkGA1UEBhMC\n" + - "VVMxEDAOBgNVBAoTB0V4YW1wbGUwHhcNMTYwMjE2MDQzNTQ2WhcNMzUxMTAzMDQz\n" + - "NTQ2WjA5MQswCQYDVQQGEwJVUzEQMA4GA1UECgwHRXhhbXBsZTEYMBYGA1UEAwwP\n" + - "d3d3LmV4YW1wbGUuY29tMIHwMIGoBgcqhkjOOAQBMIGcAkEAs6A0p3TysTtVXGSv\n" + - "ThR/8GHpbL49KyWRJBMIlmLc5jl/wxJgnL1t07p4YTOEa6ecyTFos04Z8n2GARmp\n" + - "zYlUywIVAJLDcf4JXhZbguRFSQdWwWhZkh+LAkBLCzh3Xvpmc/5CDqU+QHqDcuSk\n" + - "5B8+ZHaHRi2KQ00ejilpF2qZpW5JdHe4m3Pggh0MIuaAGX+leM4JKlnObj14A0MA\n" + - "AkAYb+DYlFgStFhF1ip7rFzY8K6i/3ellkXI2umI/XVwxUQTHSlk5nFOep5Dfzm9\n" + - "pADJwuSe1qGHsHB5LpMZPVpto4GEMIGBMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgPo\n" + - "MB0GA1UdDgQWBBT8nsFyccF4q1dtpWE1dkNK5UiXtTAfBgNVHSMEGDAWgBRfips/\n" + - "k+AHHUnwEnyoSB+gpUtKdDAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIG\n" + - "CCsGAQUFBwMDMAkGByqGSM44BAMDMAAwLQIUIcIlxpIwaZXdpMC+U076unR1Mp8C\n" + - "FQCD/NE8O0xwq57nwFfp7tUvUHYMMA==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8, key size is 512 bits. - static String targetPrivateKey = - "MIHGAgEAMIGoBgcqhkjOOAQBMIGcAkEAs6A0p3TysTtVXGSvThR/8GHpbL49KyWR\n" + - "JBMIlmLc5jl/wxJgnL1t07p4YTOEa6ecyTFos04Z8n2GARmpzYlUywIVAJLDcf4J\n" + - "XhZbguRFSQdWwWhZkh+LAkBLCzh3Xvpmc/5CDqU+QHqDcuSk5B8+ZHaHRi2KQ00e\n" + - "jilpF2qZpW5JdHe4m3Pggh0MIuaAGX+leM4JKlnObj14BBYCFHB2Wek2g5hpNj5y\n" + - "RQfCc6CFO0dv"; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(null, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - try (InputStream sslIS = sslSocket.getInputStream()) { - sslIS.read(); - } - - throw new Exception( - "DSA keys shorter than 1024 bits should be disabled"); - } catch (SSLHandshakeException sslhe) { - // the expected exception, ignore - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - try (SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort)) { - - // only enable the target protocol - sslSocket.setEnabledProtocols(new String[] {enabledProtocol}); - - // enable a block cipher - sslSocket.setEnabledCipherSuites( - new String[] {"TLS_DHE_DSS_WITH_AES_128_CBC_SHA"}); - - try (OutputStream sslOS = sslSocket.getOutputStream()) { - sslOS.write('B'); - sslOS.flush(); - } - - throw new Exception( - "DSA keys shorter than 1024 bits should be disabled"); - } catch (SSLHandshakeException sslhe) { - // the expected exception, ignore - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String enabledProtocol; // the target protocol - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - enabledProtocol = args[1]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("DSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("DSA"); - DSAPrivateKey priKey = - (DSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new DisabledShortDSAKeys(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - DisabledShortDSAKeys() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv12/DisabledShortRSAKeys.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,441 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7109274 - * @summary Consider disabling support for X.509 certificates with RSA keys - * less than 1024 bits - * - * @run main/othervm DisabledShortRSAKeys PKIX TLSv1.2 - * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1.2 - * @run main/othervm DisabledShortRSAKeys PKIX TLSv1.1 - * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1.1 - * @run main/othervm DisabledShortRSAKeys PKIX TLSv1 - * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1 - * @run main/othervm DisabledShortRSAKeys PKIX SSLv3 - * @run main/othervm DisabledShortRSAKeys SunX509 SSLv3 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class DisabledShortRSAKeys { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" + - "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" + - "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" + - "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" + - "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" + - "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" + - "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" + - "-----END CERTIFICATE-----"; - - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICNDCCAZ2gAwIBAgIBDDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTA3MTM1NTUyWhcNMzEwNzI1MTM1NTUyWjBPMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3Pb49OSPfOD2G\n" + - "HSXFCFx1GJEZfqG9ZUf7xuIi/ra5dLjPGAaoY5QF2QOa8VnOriQCXDfyXHxsuRnE\n" + - "OomxL7EVAgMBAAGjeDB2MAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUXNCJK3/dtCIc\n" + - "xb+zlA/JINlvs/MwHwYDVR0jBBgwFoAUuXzV2d+nTAOu/Q4nWzGVbMfzdeEwJwYD\n" + - "VR0lBCAwHgYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAzANBgkqhkiG9w0B\n" + - "AQQFAAOBgQB2qIDUxA2caMPpGtUACZAPRUtrGssCINIfItETXJZCx/cRuZ5sP4D9\n" + - "N1acoNDn0hCULe3lhXAeTC9NZ97680yJzregQMV5wATjo1FGsKY30Ma+sc/nfzQW\n" + - "+h/7RhYtoG0OTsiaDCvyhI6swkNJzSzrAccPY4+ZgU8HiDLzZTmM3Q==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8, key size is 512 bits. - static String targetPrivateKey = - "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtz2+PTkj3zg9hh0l\n" + - "xQhcdRiRGX6hvWVH+8biIv62uXS4zxgGqGOUBdkDmvFZzq4kAlw38lx8bLkZxDqJ\n" + - "sS+xFQIDAQABAkByx/5Oo2hQ/w2q4L8z+NTRlJ3vdl8iIDtC/4XPnfYfnGptnpG6\n" + - "ZThQRvbMZiai0xHQPQMszvAHjZVme1eDl3EBAiEA3aKJHynPVCEJhpfCLWuMwX5J\n" + - "1LntwJO7NTOyU5m8rPECIQDTpzn5X44r2rzWBDna/Sx7HW9IWCxNgUD2Eyi2nA7W\n" + - "ZQIgJerEorw4aCAuzQPxiGu57PB6GRamAihEAtoRTBQlH0ECIQDN08FgTtnesgCU\n" + - "DFYLLcw1CiHvc7fZw4neBDHCrC8NtQIgA8TOUkGnpCZlQ0KaI8KfKWI+vxFcgFnH\n" + - "3fnqsTgaUs4="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(null, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - try (InputStream sslIS = sslSocket.getInputStream()) { - sslIS.read(); - } - - throw new Exception( - "RSA keys shorter than 1024 bits should be disabled"); - } catch (SSLHandshakeException sslhe) { - // the expected exception, ignore - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - try (SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort)) { - - // only enable the target protocol - sslSocket.setEnabledProtocols(new String[] {enabledProtocol}); - - // enable a block cipher - sslSocket.setEnabledCipherSuites( - new String[] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"}); - - try (OutputStream sslOS = sslSocket.getOutputStream()) { - sslOS.write('B'); - sslOS.flush(); - } - - throw new Exception( - "RSA keys shorter than 1024 bits should be disabled"); - } catch (SSLHandshakeException sslhe) { - // the expected exception, ignore - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String enabledProtocol; // the target protocol - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - enabledProtocol = args[1]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new DisabledShortRSAKeys(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - DisabledShortRSAKeys() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv12/ShortRSAKey512.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,424 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// This test case relies on updated static security property, no way to re-use -// security property in samevm/agentvm mode. - -/* - * @test - * @bug 7106773 - * @summary 512 bits RSA key cannot work with SHA384 and SHA512 - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @run main/othervm ShortRSAKey512 PKIX - * @run main/othervm ShortRSAKey512 SunX509 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class ShortRSAKey512 { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" + - "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" + - "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" + - "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" + - "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" + - "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" + - "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" + - "-----END CERTIFICATE-----"; - - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICNDCCAZ2gAwIBAgIBDDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTA3MTM1NTUyWhcNMzEwNzI1MTM1NTUyWjBPMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3Pb49OSPfOD2G\n" + - "HSXFCFx1GJEZfqG9ZUf7xuIi/ra5dLjPGAaoY5QF2QOa8VnOriQCXDfyXHxsuRnE\n" + - "OomxL7EVAgMBAAGjeDB2MAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUXNCJK3/dtCIc\n" + - "xb+zlA/JINlvs/MwHwYDVR0jBBgwFoAUuXzV2d+nTAOu/Q4nWzGVbMfzdeEwJwYD\n" + - "VR0lBCAwHgYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAzANBgkqhkiG9w0B\n" + - "AQQFAAOBgQB2qIDUxA2caMPpGtUACZAPRUtrGssCINIfItETXJZCx/cRuZ5sP4D9\n" + - "N1acoNDn0hCULe3lhXAeTC9NZ97680yJzregQMV5wATjo1FGsKY30Ma+sc/nfzQW\n" + - "+h/7RhYtoG0OTsiaDCvyhI6swkNJzSzrAccPY4+ZgU8HiDLzZTmM3Q==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8, key size is 512 bits. - static String targetPrivateKey = - "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtz2+PTkj3zg9hh0l\n" + - "xQhcdRiRGX6hvWVH+8biIv62uXS4zxgGqGOUBdkDmvFZzq4kAlw38lx8bLkZxDqJ\n" + - "sS+xFQIDAQABAkByx/5Oo2hQ/w2q4L8z+NTRlJ3vdl8iIDtC/4XPnfYfnGptnpG6\n" + - "ZThQRvbMZiai0xHQPQMszvAHjZVme1eDl3EBAiEA3aKJHynPVCEJhpfCLWuMwX5J\n" + - "1LntwJO7NTOyU5m8rPECIQDTpzn5X44r2rzWBDna/Sx7HW9IWCxNgUD2Eyi2nA7W\n" + - "ZQIgJerEorw4aCAuzQPxiGu57PB6GRamAihEAtoRTBQlH0ECIQDN08FgTtnesgCU\n" + - "DFYLLcw1CiHvc7fZw4neBDHCrC8NtQIgA8TOUkGnpCZlQ0KaI8KfKWI+vxFcgFnH\n" + - "3fnqsTgaUs4="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(null, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - // enable TLSv1.2 only - sslSocket.setEnabledProtocols(new String[] {"TLSv1.2"}); - - // enable a block cipher - sslSocket.setEnabledCipherSuites( - new String[] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new ShortRSAKey512(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ShortRSAKey512() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv12/ShortRSAKeyGCM.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,447 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7030966 - * @summary Support AEAD CipherSuites - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_RSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_DH_anon_WITH_AES_128_GCM_SHA256 - */ - -/* - * Need additional key materials to run the following cases. - * - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 - * - * Need unlimited JCE Unlimited Strength Jurisdiction Policy to run the - * following cases. - * - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 - * @run main/othervm ShortRSAKeyGCM PKIX TLS_DH_anon_WITH_AES_256_GCM_SHA384 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import sun.misc.BASE64Decoder; - - -public class ShortRSAKeyGCM { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" + - "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" + - "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" + - "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" + - "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" + - "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" + - "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" + - "-----END CERTIFICATE-----"; - - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICNDCCAZ2gAwIBAgIBDDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTA3MTM1NTUyWhcNMzEwNzI1MTM1NTUyWjBPMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3Pb49OSPfOD2G\n" + - "HSXFCFx1GJEZfqG9ZUf7xuIi/ra5dLjPGAaoY5QF2QOa8VnOriQCXDfyXHxsuRnE\n" + - "OomxL7EVAgMBAAGjeDB2MAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUXNCJK3/dtCIc\n" + - "xb+zlA/JINlvs/MwHwYDVR0jBBgwFoAUuXzV2d+nTAOu/Q4nWzGVbMfzdeEwJwYD\n" + - "VR0lBCAwHgYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAzANBgkqhkiG9w0B\n" + - "AQQFAAOBgQB2qIDUxA2caMPpGtUACZAPRUtrGssCINIfItETXJZCx/cRuZ5sP4D9\n" + - "N1acoNDn0hCULe3lhXAeTC9NZ97680yJzregQMV5wATjo1FGsKY30Ma+sc/nfzQW\n" + - "+h/7RhYtoG0OTsiaDCvyhI6swkNJzSzrAccPY4+ZgU8HiDLzZTmM3Q==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8, key size is 512 bits. - static String targetPrivateKey = - "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtz2+PTkj3zg9hh0l\n" + - "xQhcdRiRGX6hvWVH+8biIv62uXS4zxgGqGOUBdkDmvFZzq4kAlw38lx8bLkZxDqJ\n" + - "sS+xFQIDAQABAkByx/5Oo2hQ/w2q4L8z+NTRlJ3vdl8iIDtC/4XPnfYfnGptnpG6\n" + - "ZThQRvbMZiai0xHQPQMszvAHjZVme1eDl3EBAiEA3aKJHynPVCEJhpfCLWuMwX5J\n" + - "1LntwJO7NTOyU5m8rPECIQDTpzn5X44r2rzWBDna/Sx7HW9IWCxNgUD2Eyi2nA7W\n" + - "ZQIgJerEorw4aCAuzQPxiGu57PB6GRamAihEAtoRTBQlH0ECIQDN08FgTtnesgCU\n" + - "DFYLLcw1CiHvc7fZw4neBDHCrC8NtQIgA8TOUkGnpCZlQ0KaI8KfKWI+vxFcgFnH\n" + - "3fnqsTgaUs4="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(null, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites()); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - // enable TLSv1.2 only - sslSocket.setEnabledProtocols(new String[] {"TLSv1.2"}); - - // enable a block cipher - sslSocket.setEnabledCipherSuites(new String[] {cipherSuite}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String cipherSuite; // cipher suite - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - cipherSuite = args[1]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - new BASE64Decoder().decodeBuffer(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new ShortRSAKeyGCM(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ShortRSAKeyGCM() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..." + e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..." + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/TLSv12/SignatureAlgorithms.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,595 +0,0 @@ -/* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 8049321 - * @summary Support SHA256WithDSA in JSSE - * @modules java.base/sun.misc - * @run main/othervm SignatureAlgorithms PKIX "SHA-224,SHA-256" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA - * @run main/othervm SignatureAlgorithms PKIX "SHA-1,SHA-224" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA - * @run main/othervm SignatureAlgorithms PKIX "SHA-1,SHA-256" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA - * @run main/othervm SignatureAlgorithms PKIX "SHA-224,SHA-256" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 - * @run main/othervm SignatureAlgorithms PKIX "SHA-1,SHA-224" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 - * @run main/othervm SignatureAlgorithms PKIX "SHA-1,SHA-256" - * TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import sun.misc.BASE64Decoder; - - -public class SignatureAlgorithms { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificates and key (DSA) used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIIDYTCCAyGgAwIBAgIJAK8/gw6zg/DPMAkGByqGSM44BAMwOzELMAkGA1UEBhMC\n" + - "VVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNl\n" + - "MB4XDTE1MTIwMzEzNTIyNVoXDTM2MTExMjEzNTIyNVowOzELMAkGA1UEBhMCVVMx\n" + - "DTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNlMIIB\n" + - "uDCCASwGByqGSM44BAEwggEfAoGBAPH+b+GSMX6KS7jXDRevzc464DFG4X+uxu5V\n" + - "b3U4yhsU8A8cuH4gwin6L/IDkmZQ7N0zC0jRsiGVSMsFETTq10F39pH2eBfUv/hJ\n" + - "cLfBnIjBEtVqV/dExK88Hul2sZ4mQihQ4issPl7hsroS9EWYicnX0oNAqAB9PO5Y\n" + - "zKbfpL7TAhUA13WW48rln2UP/LaAgtnzKhqcNtMCgYEA3Rv0GirTbAaor8iURd82\n" + - "b5FlDTevOCTuq7ZIpfZVV30neS7cBYNet6m/3/4cfUlbbrqhbqIJ2I+I81drnN0Y\n" + - "lyN4KkuxEcB6OTwfWkIUj6rvPaCQrBH8Q213bDq3HHtYNaP8OoeQUyVXW+SEGADC\n" + - "J1+z8uqP3lIB6ltdgOiV/GQDgYUAAoGBAOXRppuJSGdt6AiZkb81P1DCUgIUlZFI\n" + - "J9GxWrjbbHDmGllMwPNhK6dU7LJKJJuYVPW+95rUGlSJEjRqSlHuyHkNb6e3e7qx\n" + - "tmx1/oIyq+oLult50hBS7uBvLLR0JbIKjBzzkudL8Rjze4G/Wq7KDM2T1JOP49tW\n" + - "eocCvaC8h8uQo4GtMIGqMB0GA1UdDgQWBBT17HcqLllsqnZzP+kElcGcBGmubjBr\n" + - "BgNVHSMEZDBigBT17HcqLllsqnZzP+kElcGcBGmubqE/pD0wOzELMAkGA1UEBhMC\n" + - "VVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNl\n" + - "ggkArz+DDrOD8M8wDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwCQYHKoZI\n" + - "zjgEAwMvADAsAhQ6Y1I6LtIEBMqNo8o6GIe4LLEJuwIUbVQUKi8tvtWyRoxm8AFV\n" + - "0axJYUU=\n" + - "-----END CERTIFICATE-----"; - - static String[] targetCertStr = { - // DSA-SHA1 - "-----BEGIN CERTIFICATE-----\n" + - "MIIDKTCCAumgAwIBAgIJAOy5c0b+8stFMAkGByqGSM44BAMwOzELMAkGA1UEBhMC\n" + - "VVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNl\n" + - "MB4XDTE1MTIwMzEzNTIyNVoXDTM1MDgyMDEzNTIyNVowTzELMAkGA1UEBhMCVVMx\n" + - "DTALBgNVBAoMBEphdmExHTAbBgNVBAsMFFN1bkpTU0UgVGVzdCBTZXJpdmNlMRIw\n" + - "EAYDVQQDDAlsb2NhbGhvc3QwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA8f5v4ZIx\n" + - "fopLuNcNF6/NzjrgMUbhf67G7lVvdTjKGxTwDxy4fiDCKfov8gOSZlDs3TMLSNGy\n" + - "IZVIywURNOrXQXf2kfZ4F9S/+Elwt8GciMES1WpX90TErzwe6XaxniZCKFDiKyw+\n" + - "XuGyuhL0RZiJydfSg0CoAH087ljMpt+kvtMCFQDXdZbjyuWfZQ/8toCC2fMqGpw2\n" + - "0wKBgQDdG/QaKtNsBqivyJRF3zZvkWUNN684JO6rtkil9lVXfSd5LtwFg163qb/f\n" + - "/hx9SVtuuqFuognYj4jzV2uc3RiXI3gqS7ERwHo5PB9aQhSPqu89oJCsEfxDbXds\n" + - "Orcce1g1o/w6h5BTJVdb5IQYAMInX7Py6o/eUgHqW12A6JX8ZAOBhAACgYB+zYqn\n" + - "jJwG4GZpBIN/6qhzbp0flChsV+Trlu0SL0agAQzb6XdI/4JnO87Pgbxaxh3VNAj3\n" + - "3+Ghr1NLBuBfTKzJ4j9msWT3EpLupkMyNtXvBYM0iyMrll67lSjMdv++wLEw35Af\n" + - "/bzVcjGyA5Q0i0cuEzDmHTVfi0OydynbwSLxtKNjMGEwCwYDVR0PBAQDAgPoMB0G\n" + - "A1UdDgQWBBQXJI8AxM0qsYCbbkIMuI5zJ+nMEDAfBgNVHSMEGDAWgBT17HcqLlls\n" + - "qnZzP+kElcGcBGmubjASBgNVHREBAf8ECDAGhwR/AAABMAkGByqGSM44BAMDLwAw\n" + - "LAIUXgyJ0xll4FrZAKXi8bj7Kiz+SA4CFH9WCSZIBYA9lmJkiTgRS7iM/6IC\n" + - "-----END CERTIFICATE-----", - - // DSA-SHA224 - "-----BEGIN CERTIFICATE-----\n" + - "MIIDLzCCAuugAwIBAgIJAOy5c0b+8stGMAsGCWCGSAFlAwQDATA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2UwHhcNMTUxMjAzMTU0NDM5WhcNMzUwODIwMTU0NDM5WjBPMQswCQYDVQQGEwJV\n" + - "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Ux\n" + - "EjAQBgNVBAMMCWxvY2FsaG9zdDCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQDx/m/h\n" + - "kjF+iku41w0Xr83OOuAxRuF/rsbuVW91OMobFPAPHLh+IMIp+i/yA5JmUOzdMwtI\n" + - "0bIhlUjLBRE06tdBd/aR9ngX1L/4SXC3wZyIwRLValf3RMSvPB7pdrGeJkIoUOIr\n" + - "LD5e4bK6EvRFmInJ19KDQKgAfTzuWMym36S+0wIVANd1luPK5Z9lD/y2gILZ8yoa\n" + - "nDbTAoGBAN0b9Boq02wGqK/IlEXfNm+RZQ03rzgk7qu2SKX2VVd9J3ku3AWDXrep\n" + - "v9/+HH1JW266oW6iCdiPiPNXa5zdGJcjeCpLsRHAejk8H1pCFI+q7z2gkKwR/ENt\n" + - "d2w6txx7WDWj/DqHkFMlV1vkhBgAwidfs/Lqj95SAepbXYDolfxkA4GEAAKBgA81\n" + - "CJKEv+pwiqYgxtw/9rkQ9748WP3mKrEC06kjUG+94/Z9dQloNFFfj6LiO1bymc5l\n" + - "6QIR8XCi4Po3N80K3+WxhBGFhY+RkVWTh43JV8epb41aH2qiWErarBwBGEh8LyGT\n" + - "i30db+Nkz2gfvyz9H/9T0jmYgfLEOlMCusali1qHo2MwYTALBgNVHQ8EBAMCA+gw\n" + - "HQYDVR0OBBYEFBqSP0S4+X+zOCTEnlp2hbAjV/W5MB8GA1UdIwQYMBaAFPXsdyou\n" + - "WWyqdnM/6QSVwZwEaa5uMBIGA1UdEQEB/wQIMAaHBH8AAAEwCwYJYIZIAWUDBAMB\n" + - "AzEAMC4CFQChiRaOnAnsCSJFwdpK22jSxU/mhQIVALgLbj/G39+1Ej8UuSWnEQyU\n" + - "4DA+\n" + - "-----END CERTIFICATE-----", - - // DSA-SHA256 - "-----BEGIN CERTIFICATE-----\n" + - "MIIDLTCCAuugAwIBAgIJAOy5c0b+8stHMAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2UwHhcNMTUxMjAzMTU0NjUxWhcNMzUwODIwMTU0NjUxWjBPMQswCQYDVQQGEwJV\n" + - "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Ux\n" + - "EjAQBgNVBAMMCWxvY2FsaG9zdDCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQDx/m/h\n" + - "kjF+iku41w0Xr83OOuAxRuF/rsbuVW91OMobFPAPHLh+IMIp+i/yA5JmUOzdMwtI\n" + - "0bIhlUjLBRE06tdBd/aR9ngX1L/4SXC3wZyIwRLValf3RMSvPB7pdrGeJkIoUOIr\n" + - "LD5e4bK6EvRFmInJ19KDQKgAfTzuWMym36S+0wIVANd1luPK5Z9lD/y2gILZ8yoa\n" + - "nDbTAoGBAN0b9Boq02wGqK/IlEXfNm+RZQ03rzgk7qu2SKX2VVd9J3ku3AWDXrep\n" + - "v9/+HH1JW266oW6iCdiPiPNXa5zdGJcjeCpLsRHAejk8H1pCFI+q7z2gkKwR/ENt\n" + - "d2w6txx7WDWj/DqHkFMlV1vkhBgAwidfs/Lqj95SAepbXYDolfxkA4GEAAKBgEF7\n" + - "2qiYxGrjX4KCOy0k5nK/RYlgLy4gYDChihQpiaa+fbA5JOBOxPWsh7rdtmJuDrEJ\n" + - "keacU223+DIhOKC49fa+EvhLNqo6U1oPn8n/yvBsvvnWkcynw5KfNzaLlaPmzugh\n" + - "v9xl/GhyZNAXc1QUcW3C+ceHVNrKnkfbTKZz5eRSo2MwYTALBgNVHQ8EBAMCA+gw\n" + - "HQYDVR0OBBYEFNMkPrt40oO9Dpy+bcbQdEvOlNlyMB8GA1UdIwQYMBaAFPXsdyou\n" + - "WWyqdnM/6QSVwZwEaa5uMBIGA1UdEQEB/wQIMAaHBH8AAAEwCwYJYIZIAWUDBAMC\n" + - "Ay8AMCwCFCvA2QiKSe/n+6GqSYQwgQ/zL5M9AhQfSiuWdMJKWpgPJKakvzhBUbMb\n" + - "vA==\n" + - "-----END CERTIFICATE-----"}; - - // Private key in the format of PKCS#8, key size is 1024 bits. - static String[] targetPrivateKey = { - // For cert DSA-SHA1 - "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAPH+b+GSMX6KS7jXDRevzc464DFG\n" + - "4X+uxu5Vb3U4yhsU8A8cuH4gwin6L/IDkmZQ7N0zC0jRsiGVSMsFETTq10F39pH2\n" + - "eBfUv/hJcLfBnIjBEtVqV/dExK88Hul2sZ4mQihQ4issPl7hsroS9EWYicnX0oNA\n" + - "qAB9PO5YzKbfpL7TAhUA13WW48rln2UP/LaAgtnzKhqcNtMCgYEA3Rv0GirTbAao\n" + - "r8iURd82b5FlDTevOCTuq7ZIpfZVV30neS7cBYNet6m/3/4cfUlbbrqhbqIJ2I+I\n" + - "81drnN0YlyN4KkuxEcB6OTwfWkIUj6rvPaCQrBH8Q213bDq3HHtYNaP8OoeQUyVX\n" + - "W+SEGADCJ1+z8uqP3lIB6ltdgOiV/GQEFgIUOiB7J/lrFrNduQ8nDNTe8VspoAI=", - - // For cert DSA-SHA224 - "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAPH+b+GSMX6KS7jXDRevzc464DFG\n" + - "4X+uxu5Vb3U4yhsU8A8cuH4gwin6L/IDkmZQ7N0zC0jRsiGVSMsFETTq10F39pH2\n" + - "eBfUv/hJcLfBnIjBEtVqV/dExK88Hul2sZ4mQihQ4issPl7hsroS9EWYicnX0oNA\n" + - "qAB9PO5YzKbfpL7TAhUA13WW48rln2UP/LaAgtnzKhqcNtMCgYEA3Rv0GirTbAao\n" + - "r8iURd82b5FlDTevOCTuq7ZIpfZVV30neS7cBYNet6m/3/4cfUlbbrqhbqIJ2I+I\n" + - "81drnN0YlyN4KkuxEcB6OTwfWkIUj6rvPaCQrBH8Q213bDq3HHtYNaP8OoeQUyVX\n" + - "W+SEGADCJ1+z8uqP3lIB6ltdgOiV/GQEFgIUOj9F5mxWd9W1tiLSdsOAt8BUBzE=", - - // For cert DSA-SHA256 - "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAPH+b+GSMX6KS7jXDRevzc464DFG\n" + - "4X+uxu5Vb3U4yhsU8A8cuH4gwin6L/IDkmZQ7N0zC0jRsiGVSMsFETTq10F39pH2\n" + - "eBfUv/hJcLfBnIjBEtVqV/dExK88Hul2sZ4mQihQ4issPl7hsroS9EWYicnX0oNA\n" + - "qAB9PO5YzKbfpL7TAhUA13WW48rln2UP/LaAgtnzKhqcNtMCgYEA3Rv0GirTbAao\n" + - "r8iURd82b5FlDTevOCTuq7ZIpfZVV30neS7cBYNet6m/3/4cfUlbbrqhbqIJ2I+I\n" + - "81drnN0YlyN4KkuxEcB6OTwfWkIUj6rvPaCQrBH8Q213bDq3HHtYNaP8OoeQUyVX\n" + - "W+SEGADCJ1+z8uqP3lIB6ltdgOiV/GQEFgIUQ2WGgg+OO39Aujj0e4lM4pP4/9g="}; - - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Is the server ready to serve? - */ - volatile boolean serverReady = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - - SSLContext context = generateSSLContext( - null, targetCertStr, targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - try (SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort)) { - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - sslSocket.setEnabledCipherSuites( - sslSocket.getSupportedCipherSuites()); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - dumpSignatureAlgorithms(sslSocket); - } - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - try (SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort)) { - - // enable TLSv1.2 only - sslSocket.setEnabledProtocols(new String[] {"TLSv1.2"}); - - // enable a block cipher - sslSocket.setEnabledCipherSuites(new String[] {cipherSuite}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - dumpSignatureAlgorithms(sslSocket); - } - } - - static void dumpSignatureAlgorithms(SSLSocket sslSocket) throws Exception { - - boolean isClient = sslSocket.getUseClientMode(); - String mode = "[" + (isClient ? "Client" : "Server") + "]"; - ExtendedSSLSession session = - (ExtendedSSLSession)sslSocket.getSession(); - String[] signAlgs = session.getLocalSupportedSignatureAlgorithms(); - System.out.println( - mode + " local supported signature algorithms: " + - Arrays.asList(signAlgs)); - - if (!isClient) { - signAlgs = session.getPeerSupportedSignatureAlgorithms(); - System.out.println( - mode + " peer supported signature algorithms: " + - Arrays.asList(signAlgs)); - } else { - Certificate[] serverCerts = session.getPeerCertificates(); - - // server should always send the authentication cert. - String sigAlg = ((X509Certificate)serverCerts[0]).getSigAlgName(); - System.out.println( - mode + " the signature algorithm of server certificate: " + - sigAlg); - if (sigAlg.contains("SHA1")) { - if (disabledAlgorithms.contains("SHA-1")) { - throw new Exception( - "Not the expected server certificate. " + - "SHA-1 should be disabled"); - } - } else if (sigAlg.contains("SHA224")) { - if (disabledAlgorithms.contains("SHA-224")) { - throw new Exception( - "Not the expected server certificate. " + - "SHA-224 should be disabled"); - } - } else { // SHA-256 - if (disabledAlgorithms.contains("SHA-256")) { - throw new Exception( - "Not the expected server certificate. " + - "SHA-256 should be disabled"); - } - } - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String disabledAlgorithms; // disabled algorithms - private static String cipherSuite; // cipher suite - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - disabledAlgorithms = args[1]; - cipherSuite = args[2]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String[] keyCertStrs, String[] keySpecStrs) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("DSA Signer", trusedCert); - } - - if (keyCertStrs != null && keyCertStrs.length != 0) { - for (int i = 0; i < keyCertStrs.length; i++) { - String keyCertStr = keyCertStrs[i]; - String keySpecStr = keySpecStrs[i]; - - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - new BASE64Decoder().decodeBuffer(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("DSA"); - DSAPrivateKey priKey = - (DSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("DSA Entry " + i, priKey, passphrase, chain); - } - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStrs != null && keyCertStrs.length != 0) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - /* - * debug option - */ - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Get the customized arguments. - */ - parseArguments(args); - - - /* - * Ignore testing on Windows if only SHA-224 is available. - */ - if ((Security.getProvider("SunMSCAPI") != null) && - (disabledAlgorithms.contains("SHA-1")) && - (disabledAlgorithms.contains("SHA-256"))) { - - System.out.println( - "Windows system does not support SHA-224 algorithms yet. " + - "Ignore the testing"); - - return; - } - - /* - * Expose the target algorithms by diabling unexpected algorithms. - */ - Security.setProperty( - "jdk.certpath.disabledAlgorithms", disabledAlgorithms); - - /* - * Reset the security property to make sure that the algorithms - * and keys used in this test are not disabled by default. - */ - Security.setProperty( "jdk.tls.disabledAlgorithms", ""); - - /* - * Start the tests. - */ - new SignatureAlgorithms(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SignatureAlgorithms() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..." + e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..." + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/ciphersuites/DisabledAlgorithms.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,398 +0,0 @@ -/* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.NoSuchAlgorithmException; -import java.security.Security; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -/** - * @test - * @bug 8076221 8157035 8211883 - * @summary Check if weak cipher suites are disabled - * @run main/othervm DisabledAlgorithms default - * @run main/othervm DisabledAlgorithms empty - */ -public class DisabledAlgorithms { - - private static final String pathToStores = - "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - - private static final String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - // supported RC4, NULL, and anon cipher suites - // it does not contain KRB5 cipher suites because they need a KDC - private static final String[] rc4_null_anon_ciphersuites = new String[] { - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDHE_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_SHA", - "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDH_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_MD5", - "TLS_ECDH_anon_WITH_RC4_128_SHA", - "SSL_DH_anon_WITH_RC4_128_MD5", - "SSL_RSA_WITH_NULL_MD5", - "SSL_RSA_WITH_NULL_SHA", - "TLS_RSA_WITH_NULL_SHA256", - "TLS_ECDH_ECDSA_WITH_NULL_SHA", - "TLS_ECDHE_ECDSA_WITH_NULL_SHA", - "TLS_ECDH_RSA_WITH_NULL_SHA", - "TLS_ECDHE_RSA_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", - "SSL_DH_anon_WITH_DES_CBC_SHA", - "SSL_DH_anon_WITH_RC4_128_MD5", - "TLS_DH_anon_WITH_AES_128_CBC_SHA", - "TLS_DH_anon_WITH_AES_128_CBC_SHA256", - "TLS_DH_anon_WITH_AES_128_GCM_SHA256", - "TLS_DH_anon_WITH_AES_256_CBC_SHA", - "TLS_DH_anon_WITH_AES_256_CBC_SHA256", - "TLS_DH_anon_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_RC4_128_SHA" - }; - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - throw new RuntimeException("No parameters specified"); - } - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - switch (args[0]) { - case "default": - // use default jdk.tls.disabledAlgorithms - System.out.println("jdk.tls.disabledAlgorithms = " - + Security.getProperty("jdk.tls.disabledAlgorithms")); - - // check if RC4, NULL, and anon cipher suites - // can't be used by default - checkFailure(rc4_null_anon_ciphersuites); - break; - case "empty": - // reset jdk.tls.disabledAlgorithms - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - System.out.println("jdk.tls.disabledAlgorithms = " - + Security.getProperty("jdk.tls.disabledAlgorithms")); - - // check if RC4, NULL, and anon cipher suites can be used - // if jdk.tls.disabledAlgorithms is empty - checkSuccess(rc4_null_anon_ciphersuites); - break; - default: - throw new RuntimeException("Wrong parameter: " + args[0]); - } - - System.out.println("Test passed"); - } - - /* - * Checks if that specified cipher suites cannot be used. - */ - private static void checkFailure(String[] ciphersuites) throws Exception { - try (SSLServer server = SSLServer.init(ciphersuites)) { - startNewThread(server); - while (!server.isRunning()) { - sleep(); - } - - int port = server.getPort(); - for (String ciphersuite : ciphersuites) { - try (SSLClient client = SSLClient.init(port, ciphersuite)) { - client.connect(); - throw new RuntimeException("Expected SSLHandshakeException " - + "not thrown"); - } catch (SSLHandshakeException e) { - System.out.println("Expected exception on client side: " - + e); - } - } - - while (server.isRunning()) { - sleep(); - } - - if (!server.sslError()) { - throw new RuntimeException("Expected SSL exception " - + "not thrown on server side"); - } - } - - } - - /* - * Checks if specified cipher suites can be used. - */ - private static void checkSuccess(String[] ciphersuites) throws Exception { - try (SSLServer server = SSLServer.init(ciphersuites)) { - startNewThread(server); - while (!server.isRunning()) { - sleep(); - } - - int port = server.getPort(); - for (String ciphersuite : ciphersuites) { - try (SSLClient client = SSLClient.init(port, ciphersuite)) { - client.connect(); - String negotiated = client.getNegotiatedCipherSuite(); - System.out.println("Negotiated cipher suite: " - + negotiated); - if (!negotiated.equals(ciphersuite)) { - throw new RuntimeException("Unexpected cipher suite: " - + negotiated); - } - } - } - - server.stop(); - while (server.isRunning()) { - sleep(); - } - - if (server.error()) { - throw new RuntimeException("Unexpected error on server side"); - } - } - - } - - private static Thread startNewThread(SSLServer server) { - Thread serverThread = new Thread(server, "SSL server thread"); - serverThread.setDaemon(true); - serverThread.start(); - return serverThread; - } - - private static void sleep() { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - // do nothing - } - } - - static class SSLServer implements Runnable, AutoCloseable { - - private final SSLServerSocket ssocket; - private volatile boolean stopped = false; - private volatile boolean running = false; - private volatile boolean sslError = false; - private volatile boolean otherError = false; - - private SSLServer(SSLServerSocket ssocket) { - this.ssocket = ssocket; - } - - @Override - public void run() { - System.out.println("Server: started"); - running = true; - while (!stopped) { - try (SSLSocket socket = (SSLSocket) ssocket.accept()) { - System.out.println("Server: accepted client connection"); - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - int b = in.read(); - if (b < 0) { - throw new IOException("Unexpected EOF"); - } - System.out.println("Server: send data: " + b); - out.write(b); - out.flush(); - socket.getSession().invalidate(); - } catch (SSLHandshakeException e) { - System.out.println("Server: run: " + e); - e.printStackTrace(); - sslError = true; - stopped = true; - } catch (IOException e) { - if (!stopped) { - System.out.println("Server: run: unexpected exception: " - + e); - e.printStackTrace(); - otherError = true; - stopped = true; - } else { - System.out.println("Server: run: " + e); - System.out.println("The exception above occurred " - + "because socket was closed, " - + "please ignore it"); - } - } - } - - System.out.println("Server: finished"); - running = false; - } - - int getPort() { - return ssocket.getLocalPort(); - } - - String[] getEnabledCiperSuites() { - return ssocket.getEnabledCipherSuites(); - } - - boolean isRunning() { - return running; - } - - boolean sslError() { - return sslError; - } - - boolean error() { - return sslError || otherError; - } - - void stop() { - stopped = true; - if (!ssocket.isClosed()) { - try { - System.out.println("Server: close socket"); - ssocket.close(); - } catch (IOException e) { - System.out.println("Server: close: " + e); - } - } - } - - @Override - public void close() { - stop(); - } - - static SSLServer init(String[] ciphersuites) - throws IOException { - SSLServerSocketFactory ssf = (SSLServerSocketFactory) - SSLServerSocketFactory.getDefault(); - SSLServerSocket ssocket = (SSLServerSocket) - ssf.createServerSocket(0); - - if (ciphersuites != null) { - System.out.println("Server: enable cipher suites: " - + java.util.Arrays.toString(ciphersuites)); - ssocket.setEnabledCipherSuites(ciphersuites); - } - - return new SSLServer(ssocket); - } - } - - static class SSLClient implements AutoCloseable { - - private final SSLSocket socket; - - private SSLClient(SSLSocket socket) { - this.socket = socket; - } - - void connect() throws IOException { - System.out.println("Client: connect to server"); - try ( - BufferedInputStream bis = new BufferedInputStream( - socket.getInputStream()); - BufferedOutputStream bos = new BufferedOutputStream( - socket.getOutputStream())) { - bos.write('x'); - bos.flush(); - - int read = bis.read(); - if (read < 0) { - throw new IOException("Client: couldn't read a response"); - } - socket.getSession().invalidate(); - } - } - - String[] getEnabledCiperSuites() { - return socket.getEnabledCipherSuites(); - } - - String getNegotiatedCipherSuite() { - return socket.getSession().getCipherSuite(); - } - - @Override - public void close() throws Exception { - if (!socket.isClosed()) { - try { - socket.close(); - } catch (IOException e) { - System.out.println("Client: close: " + e); - } - } - } - - static SSLClient init(int port) - throws NoSuchAlgorithmException, IOException { - return init(port, null); - } - - static SSLClient init(int port, String ciphersuite) - throws NoSuchAlgorithmException, IOException { - SSLContext context = SSLContext.getDefault(); - SSLSocketFactory ssf = (SSLSocketFactory) - context.getSocketFactory(); - SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port); - - if (ciphersuite != null) { - System.out.println("Client: enable cipher suite: " - + ciphersuite); - socket.setEnabledCipherSuites(new String[] { ciphersuite }); - } - - return new SSLClient(socket); - } - - } - - -}
--- a/test/javax/net/ssl/ciphersuites/ECCurvesconstraints.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,408 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 8148516 - * @summary Improve the default strength of EC in JDK - * @run main/othervm ECCurvesconstraints PKIX - * @run main/othervm ECCurvesconstraints SunX509 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class ECCurvesconstraints { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - // - // EC curve: secp224k1 - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIIBCzCBugIEVz2lcjAKBggqhkjOPQQDAjAaMRgwFgYDVQQDDA93d3cuZXhhbXBs\n" + - "ZS5vcmcwHhcNMTYwNTE5MTEzNzM5WhcNMTcwNTE5MTEzNzM5WjAaMRgwFgYDVQQD\n" + - "DA93d3cuZXhhbXBsZS5vcmcwTjAQBgcqhkjOPQIBBgUrgQQAIAM6AAT68uovMZ8f\n" + - "KARn5NOjvieJaq6h8zHYkM9w5DuN0kkOo4KBhke06EkQj0nvQQcSvppTV6RoDLY4\n" + - "djAKBggqhkjOPQQDAgNAADA9AhwMNIujM0R0llpPH6d89d1S3VRGH/78ovc+zw51\n" + - "Ah0AuZ1YlQkUbrJIzkuPSICxz5UfCWPe+7w4as+wiA==\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8 - static String targetPrivateKey = - "MIGCAgEAMBAGByqGSM49AgEGBSuBBAAgBGswaQIBAQQdAPbckc86mgW/zexB1Ajq\n" + - "38HntWOjdxL6XSoiAsWgBwYFK4EEACChPAM6AAT68uovMZ8fKARn5NOjvieJaq6h\n" + - "8zHYkM9w5DuN0kkOo4KBhke06EkQj0nvQQcSvppTV6RoDLY4dg=="; - - static String[] serverCerts = {trustedCertStr}; - static String[] serverKeys = {targetPrivateKey}; - static String[] clientCerts = {trustedCertStr}; - static String[] clientKeys = {targetPrivateKey}; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(false); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - try { - sslSocket.setSoTimeout(5000); - sslSocket.setSoLinger(true, 5); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - throw new Exception("EC curve secp224k1 should be disabled"); - } catch (SSLHandshakeException she) { - // expected exception: no cipher suites in common - System.out.println("Expected exception: " + she); - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(true); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - try { - sslSocket.setSoTimeout(5000); - sslSocket.setSoLinger(true, 5); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - throw new Exception("EC curve secp224k1 should be disabled"); - } catch (SSLHandshakeException she) { - // expected exception: Received fatal alert - System.out.println("Expected exception: " + she); - } finally { - sslSocket.close(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - } - - private static SSLContext generateSSLContext(boolean isClient) - throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - ByteArrayInputStream is = - new ByteArrayInputStream(trustedCertStr.getBytes()); - Certificate trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("Export Signer", trusedCert); - - String[] certStrs = null; - String[] keyStrs = null; - if (isClient) { - certStrs = clientCerts; - keyStrs = clientKeys; - } else { - certStrs = serverCerts; - keyStrs = serverKeys; - } - - for (int i = 0; i < certStrs.length; i++) { - // generate the private key. - String keySpecStr = keyStrs[i]; - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("EC"); - ECPrivateKey priKey = - (ECPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - String keyCertStr = certStrs[i]; - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - - // import the key entry. - ks.setKeyEntry("key-entry-" + i, priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - - return ctx; - } - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new ECCurvesconstraints(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ECCurvesconstraints() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died, because of " + e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died, because of " + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/javax/net/ssl/etc/README Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -Keystores used for the JSSE regression test suite. - -keystore -truststore -========== - -These are the primary two keystores and contain entries for testing most -of the JSSE regression test files. There are three entries, one RSA-based, -one DSA-based and one EC-based. If they expire, simply recreate them -using keytool and most of the test cases should work. - -The password on both files is: - - passphrase - -There are no individual key entry passwords at this time. - - -keystore entries -================ - -Alias name: dummy ------------------ -Creation date: May 16, 2016 -Entry type: PrivateKeyEntry -Certificate chain length: 1 -Certificate[1]: -Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Serial number: 57399b87 -Valid from: Mon May 16 10:06:38 UTC 2016 until: Sat May 16 10:06:38 UTC 2026 -Signature algorithm name: SHA256withRSA -Version: 1 - -This can be generated using hacked (update the keytool source code so that -it can be used for version 1 X.509 certificate) keytool command: -% keytool -genkeypair -alias dummy -keyalg RSA -keysize 2048 \ - -sigalg SHA256withRSA \ - -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \ - -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase - - -Alias name: dummyecdsa ----------------------- -Creation date: May 16, 2016 -Entry type: PrivateKeyEntry -Certificate chain length: 1 -Certificate[1]: -Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Serial number: 57399c1d -Valid from: Mon May 16 10:09:01 UTC 2016 until: Sat May 16 10:09:01 UTC 2026 -Signature algorithm name: SHA256withECDSA -Version: 1 - -This can be generated using hacked (update the keytool source code so that -it can be used for version 1 X.509 certificate) keytool command: -% keytool -genkeypair -alias dummy -keyalg EC -keysize 256 \ - -sigalg SHA256withECDSA \ - -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \ - -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase - -Alias name: dummydsa --------------------- -Creation date: Mar 11, 2007 -Entry type: PrivateKeyEntry -Certificate chain length: 1 -Certificate[1]: -Owner: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Issuer: CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US -Serial number: 45f3a314 -Valid from: Sun Mar 11 06:35:00 UTC 2007 until: Wed Mar 08 06:35:00 UTC 2017 -Certificate fingerprints: -Signature algorithm name: SHA1withDSA -Version: 1 - -This can be generated using hacked (update the keytool source code so that -it can be used for version 1 X.509 certificate) keytool command: -% keytool -genkeypair -alias dummy -keyalg DSA -keysize 1024 \ - -sigalg SHA1withDSA \ - -dname "CN=dummy.example.com, OU=Dummy, O=Dummy, L=Cupertino, ST=CA, C=US" \ - -validity 3652 -keypass passphrase -keystore keystore -storepass passphrase - - -truststore entries -================== -This key store contains only trusted certificate entries. The same -certificates are used in both keystore and truststore. - - -unknown_keystore -================ -A keystore you can use when you don't want things to be verified. -Use this with keystore/truststore, and you'll never get a match.
--- a/test/javax/net/ssl/sanity/ciphersuites/CheckCipherSuites.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,247 +0,0 @@ -/* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4750141 4895631 8217579 - * @summary Check enabled and supported ciphersuites are correct - * @run main CheckCipherSuites default - * @run main/othervm CheckCipherSuites limited - */ - -import java.util.*; -import java.security.Security; -import javax.net.ssl.*; - -public class CheckCipherSuites { - - // List of enabled cipher suites when the "crypto.policy" security - // property is set to "unlimited" (the default value). - private final static String[] ENABLED_DEFAULT = { - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" - }; - - // List of enabled cipher suites when the "crypto.policy" security - // property is set to "limited". - private final static String[] ENABLED_LIMITED = { - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" - }; - - // List of supported cipher suites when the "crypto.policy" security - // property is set to "unlimited" (the default value). - private final static String[] SUPPORTED_DEFAULT = { - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" - }; - - // List of supported cipher suites when the "crypto.policy" security - // property is set to "limited". - private final static String[] SUPPORTED_LIMITED = { - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" - }; - - private static void showSuites(String[] suites) { - if ((suites == null) || (suites.length == 0)) { - System.out.println("<none>"); - } - for (int i = 0; i < suites.length; i++) { - System.out.println(" " + suites[i]); - } - } - - public static void main(String[] args) throws Exception { - long start = System.currentTimeMillis(); - - if (args.length != 1) { - throw new Exception("One arg required"); - } - - String[] ENABLED; - String[] SUPPORTED; - if (args[0].equals("default")) { - ENABLED = ENABLED_DEFAULT; - SUPPORTED = SUPPORTED_DEFAULT; - } else if (args[0].equals("limited")) { - Security.setProperty("crypto.policy", "limited"); - ENABLED = ENABLED_LIMITED; - SUPPORTED = SUPPORTED_LIMITED; - } else { - throw new Exception("Illegal argument"); - } - - SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); - SSLSocket socket = (SSLSocket)factory.createSocket(); - String[] enabled = socket.getEnabledCipherSuites(); - - System.out.println("Default enabled ciphersuites:"); - showSuites(enabled); - - if (Arrays.equals(ENABLED, enabled) == false) { - System.out.println("*** MISMATCH, should be ***"); - showSuites(ENABLED); - throw new Exception("Enabled ciphersuite mismatch"); - } - System.out.println("OK"); - System.out.println(); - - String[] supported = socket.getSupportedCipherSuites(); - System.out.println("Supported ciphersuites:"); - showSuites(supported); - - if (Arrays.equals(SUPPORTED, supported) == false) { - System.out.println("*** MISMATCH, should be ***"); - showSuites(SUPPORTED); - throw new Exception("Supported ciphersuite mismatch"); - } - System.out.println("OK"); - - long end = System.currentTimeMillis(); - System.out.println("Done (" + (end - start) + " ms)."); - } - -}
--- a/test/javax/net/ssl/sanity/ciphersuites/CipherSuitesInOrder.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7174244 - * @summary NPE in Krb5ProxyImpl.getServerKeys() - * @run main/othervm CipherSuitesInOrder - */ - -import java.util.*; -import javax.net.ssl.*; - -public class CipherSuitesInOrder { - - // supported ciphersuites - private final static List<String> supportedCipherSuites = - Arrays.<String>asList( - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", - "TLS_RSA_WITH_AES_256_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", - - "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", - - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV", - - "TLS_DH_anon_WITH_AES_256_GCM_SHA384", - "TLS_DH_anon_WITH_AES_128_GCM_SHA256", - - "TLS_DH_anon_WITH_AES_256_CBC_SHA256", - "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", - "TLS_DH_anon_WITH_AES_256_CBC_SHA", - "TLS_DH_anon_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", - "TLS_DH_anon_WITH_AES_128_CBC_SHA", - "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", - - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDHE_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_SHA", - "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDH_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_MD5", - "TLS_ECDH_anon_WITH_RC4_128_SHA", - "SSL_DH_anon_WITH_RC4_128_MD5", - - "SSL_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_DSS_WITH_DES_CBC_SHA", - "SSL_DH_anon_WITH_DES_CBC_SHA", - "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "SSL_RSA_EXPORT_WITH_RC4_40_MD5", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", - "TLS_RSA_WITH_NULL_SHA256", - "TLS_ECDHE_ECDSA_WITH_NULL_SHA", - "TLS_ECDHE_RSA_WITH_NULL_SHA", - "SSL_RSA_WITH_NULL_SHA", - "TLS_ECDH_ECDSA_WITH_NULL_SHA", - "TLS_ECDH_RSA_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "SSL_RSA_WITH_NULL_MD5", - "TLS_KRB5_WITH_3DES_EDE_CBC_SHA", - "TLS_KRB5_WITH_3DES_EDE_CBC_MD5", - "TLS_KRB5_WITH_RC4_128_SHA", - "TLS_KRB5_WITH_RC4_128_MD5", - "TLS_KRB5_WITH_DES_CBC_SHA", - "TLS_KRB5_WITH_DES_CBC_MD5", - "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", - "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", - "TLS_KRB5_EXPORT_WITH_RC4_40_SHA", - "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" - ); - - private final static String[] protocols = { - "", "SSL", "TLS", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" - }; - - - public static void main(String[] args) throws Exception { - // show all of the supported cipher suites - showSuites(supportedCipherSuites.toArray(new String[0]), - "All supported cipher suites"); - - for (String protocol : protocols) { - System.out.println("//"); - System.out.println("// " + - "Testing for SSLContext of " + protocol); - System.out.println("//"); - checkForProtocols(protocol); - } - } - - public static void checkForProtocols(String protocol) throws Exception { - SSLContext context; - if (protocol.isEmpty()) { - context = SSLContext.getDefault(); - } else { - context = SSLContext.getInstance(protocol); - context.init(null, null, null); - } - - // check the order of default cipher suites of SSLContext - SSLParameters parameters = context.getDefaultSSLParameters(); - checkSuites(parameters.getCipherSuites(), - "Default cipher suites in SSLContext"); - - // check the order of supported cipher suites of SSLContext - parameters = context.getSupportedSSLParameters(); - checkSuites(parameters.getCipherSuites(), - "Supported cipher suites in SSLContext"); - - - // - // Check the cipher suites order of SSLEngine - // - SSLEngine engine = context.createSSLEngine(); - - // check the order of endabled cipher suites - String[] ciphers = engine.getEnabledCipherSuites(); - checkSuites(ciphers, - "Enabled cipher suites in SSLEngine"); - - // check the order of supported cipher suites - ciphers = engine.getSupportedCipherSuites(); - checkSuites(ciphers, - "Supported cipher suites in SSLEngine"); - - // - // Check the cipher suites order of SSLSocket - // - SSLSocketFactory factory = context.getSocketFactory(); - try (SSLSocket socket = (SSLSocket)factory.createSocket()) { - - // check the order of endabled cipher suites - ciphers = socket.getEnabledCipherSuites(); - checkSuites(ciphers, - "Enabled cipher suites in SSLSocket"); - - // check the order of supported cipher suites - ciphers = socket.getSupportedCipherSuites(); - checkSuites(ciphers, - "Supported cipher suites in SSLSocket"); - } - - // - // Check the cipher suites order of SSLServerSocket - // - SSLServerSocketFactory serverFactory = context.getServerSocketFactory(); - try (SSLServerSocket serverSocket = - (SSLServerSocket)serverFactory.createServerSocket()) { - // check the order of endabled cipher suites - ciphers = serverSocket.getEnabledCipherSuites(); - checkSuites(ciphers, - "Enabled cipher suites in SSLServerSocket"); - - // check the order of supported cipher suites - ciphers = serverSocket.getSupportedCipherSuites(); - checkSuites(ciphers, - "Supported cipher suites in SSLServerSocket"); - } - } - - private static void checkSuites(String[] suites, String title) { - showSuites(suites, title); - - int loc = -1; - int index = 0; - for (String suite : suites) { - index = supportedCipherSuites.indexOf(suite); - if (index <= loc) { - throw new RuntimeException(suite + " is not in order"); - } - - loc = index; - } - } - - private static void showSuites(String[] suites, String title) { - System.out.println(title + "[" + suites.length + "]:"); - for (String suite : suites) { - System.out.println(" " + suite); - } - } -}
--- a/test/javax/net/ssl/sanity/interop/CipherTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,591 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.concurrent.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -/** - * Test that all ciphersuites work in all versions and all client - * authentication types. The way this is setup the server is stateless and - * all checking is done on the client side. - * - * The test is multithreaded to speed it up, especially on multiprocessor - * machines. To simplify debugging, run with -DnumThreads=1. - * - * @author Andreas Sterbenz - */ -public class CipherTest { - - // use any available port for the server socket - static int serverPort = 0; - - final int THREADS; - - // assume that if we do not read anything for 20 seconds, something - // has gone wrong - final static int TIMEOUT = 20 * 1000; - - static KeyStore trustStore, keyStore; - static X509ExtendedKeyManager keyManager; - static X509TrustManager trustManager; - static SecureRandom secureRandom; - - private static PeerFactory peerFactory; - - static abstract class Server implements Runnable { - - final CipherTest cipherTest; - - Server(CipherTest cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - public abstract void run(); - - void handleRequest(InputStream in, OutputStream out) throws IOException { - boolean newline = false; - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - throw new EOFException(); - } - sb.append((char)ch); - if (ch == '\r') { - // empty - } else if (ch == '\n') { - if (newline) { - // 2nd newline in a row, end of request - break; - } - newline = true; - } else { - newline = false; - } - } - String request = sb.toString(); - if (request.startsWith("GET / HTTP/1.") == false) { - throw new IOException("Invalid request: " + request); - } - out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes()); - } - - } - - public static class TestParameters { - - String cipherSuite; - String protocol; - String clientAuth; - - TestParameters(String cipherSuite, String protocol, - String clientAuth) { - this.cipherSuite = cipherSuite; - this.protocol = protocol; - this.clientAuth = clientAuth; - } - - boolean isEnabled() { - return TLSCipherStatus.isEnabled(cipherSuite, protocol); - } - - public String toString() { - String s = cipherSuite + " in " + protocol + " mode"; - if (clientAuth != null) { - s += " with " + clientAuth + " client authentication"; - } - return s; - } - - static enum TLSCipherStatus { - // cipher suites supported since TLS 1.2 - CS_01("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_02("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_03("TLS_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_04("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_05("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_06("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_07("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - - CS_08("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_09("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_10("TLS_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_11("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_12("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_13("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_14("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - - CS_15("TLS_DH_anon_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_16("TLS_DH_anon_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_17("TLS_RSA_WITH_NULL_SHA256", 0x0303, 0xFFFF), - - CS_20("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_21("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_22("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_23("TLS_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_24("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_25("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_26("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_27("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - - CS_28("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_29("TLS_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_30("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_31("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_32("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_33("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - - CS_34("TLS_DH_anon_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_35("TLS_DH_anon_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - - // cipher suites obsoleted since TLS 1.2 - CS_50("SSL_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_51("SSL_DHE_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_52("SSL_DHE_DSS_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_53("SSL_DH_anon_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_54("TLS_KRB5_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_55("TLS_KRB5_WITH_DES_CBC_MD5", 0x0000, 0x0303), - - // cipher suites obsoleted since TLS 1.1 - CS_60("SSL_RSA_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_61("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_62("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_63("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_64("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_65("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_66("TLS_KRB5_EXPORT_WITH_RC4_40_SHA", 0x0000, 0x0302), - CS_67("TLS_KRB5_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_68("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", 0x0000, 0x0302), - CS_69("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", 0x0000, 0x0302), - - // ignore TLS_EMPTY_RENEGOTIATION_INFO_SCSV always - CS_99("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", 0xFFFF, 0x0000); - - // the cipher suite name - final String cipherSuite; - - // supported since protocol version - final int supportedSince; - - // obsoleted since protocol version - final int obsoletedSince; - - TLSCipherStatus(String cipherSuite, - int supportedSince, int obsoletedSince) { - this.cipherSuite = cipherSuite; - this.supportedSince = supportedSince; - this.obsoletedSince = obsoletedSince; - } - - static boolean isEnabled(String cipherSuite, String protocol) { - int versionNumber = toVersionNumber(protocol); - - if (versionNumber < 0) { - return true; // unlikely to happen - } - - for (TLSCipherStatus status : TLSCipherStatus.values()) { - if (cipherSuite.equals(status.cipherSuite)) { - if ((versionNumber < status.supportedSince) || - (versionNumber >= status.obsoletedSince)) { - return false; - } - - return true; - } - } - - return true; - } - - private static int toVersionNumber(String protocol) { - int versionNumber = -1; - - switch (protocol) { - case "SSLv2Hello": - versionNumber = 0x0002; - break; - case "SSLv3": - versionNumber = 0x0300; - break; - case "TLSv1": - versionNumber = 0x0301; - break; - case "TLSv1.1": - versionNumber = 0x0302; - break; - case "TLSv1.2": - versionNumber = 0x0303; - break; - default: - // unlikely to happen - } - - return versionNumber; - } - } - } - - private List<TestParameters> tests; - private Iterator<TestParameters> testIterator; - private SSLSocketFactory factory; - private boolean failed; - - private CipherTest(PeerFactory peerFactory) throws IOException { - THREADS = Integer.parseInt(System.getProperty("numThreads", "4")); - factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); - SSLSocket socket = (SSLSocket)factory.createSocket(); - String[] cipherSuites = socket.getSupportedCipherSuites(); - String[] protocols = socket.getSupportedProtocols(); - String[] clientAuths = {null, "RSA", "DSA"}; - tests = new ArrayList<TestParameters>( - cipherSuites.length * protocols.length * clientAuths.length); - for (int i = 0; i < cipherSuites.length; i++) { - String cipherSuite = cipherSuites[i]; - - for (int j = 0; j < protocols.length; j++) { - String protocol = protocols[j]; - - if (!peerFactory.isSupported(cipherSuite, protocol)) { - continue; - } - - for (int k = 0; k < clientAuths.length; k++) { - String clientAuth = clientAuths[k]; - if ((clientAuth != null) && - (cipherSuite.indexOf("DH_anon") != -1)) { - // no client with anonymous ciphersuites - continue; - } - tests.add(new TestParameters(cipherSuite, protocol, - clientAuth)); - } - } - } - testIterator = tests.iterator(); - } - - synchronized void setFailed() { - failed = true; - } - - public void run() throws Exception { - Thread[] threads = new Thread[THREADS]; - for (int i = 0; i < THREADS; i++) { - try { - threads[i] = new Thread(peerFactory.newClient(this), - "Client " + i); - } catch (Exception e) { - e.printStackTrace(); - return; - } - threads[i].start(); - } - try { - for (int i = 0; i < THREADS; i++) { - threads[i].join(); - } - } catch (InterruptedException e) { - setFailed(); - e.printStackTrace(); - } - if (failed) { - throw new Exception("*** Test '" + peerFactory.getName() + - "' failed ***"); - } else { - System.out.println("Test '" + peerFactory.getName() + - "' completed successfully"); - } - } - - synchronized TestParameters getTest() { - if (failed) { - return null; - } - if (testIterator.hasNext()) { - return (TestParameters)testIterator.next(); - } - return null; - } - - SSLSocketFactory getFactory() { - return factory; - } - - static abstract class Client implements Runnable { - - final CipherTest cipherTest; - - Client(CipherTest cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - public final void run() { - while (true) { - TestParameters params = cipherTest.getTest(); - if (params == null) { - // no more tests - break; - } - if (params.isEnabled() == false) { - System.out.println("Skipping disabled test " + params); - continue; - } - try { - runTest(params); - System.out.println("Passed " + params); - } catch (Exception e) { - cipherTest.setFailed(); - System.out.println("** Failed " + params + "**"); - e.printStackTrace(); - } - } - } - - abstract void runTest(TestParameters params) throws Exception; - - void sendRequest(InputStream in, OutputStream out) throws IOException { - out.write("GET / HTTP/1.0\r\n\r\n".getBytes()); - out.flush(); - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - break; - } - sb.append((char)ch); - } - String response = sb.toString(); - if (response.startsWith("HTTP/1.0 200 ") == false) { - throw new IOException("Invalid response: " + response); - } - } - - } - - // for some reason, ${test.src} has a different value when the - // test is called from the script and when it is called directly... - static String pathToStores = "../../etc"; - static String pathToStoresSH = "."; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static char[] passwd = "passphrase".toCharArray(); - - static File PATH; - - private static KeyStore readKeyStore(String name) throws Exception { - File file = new File(PATH, name); - InputStream in = new FileInputStream(file); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(in, passwd); - in.close(); - return ks; - } - - public static void main(PeerFactory peerFactory, String[] args) - throws Exception { - long time = System.currentTimeMillis(); - String relPath; - if ((args != null) && (args.length > 0) && args[0].equals("sh")) { - relPath = pathToStoresSH; - } else { - relPath = pathToStores; - } - PATH = new File(System.getProperty("test.src", "."), relPath); - CipherTest.peerFactory = peerFactory; - System.out.print( - "Initializing test '" + peerFactory.getName() + "'..."); - secureRandom = new SecureRandom(); - secureRandom.nextInt(); - trustStore = readKeyStore(trustStoreFile); - keyStore = readKeyStore(keyStoreFile); - KeyManagerFactory keyFactory = - KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - keyFactory.init(keyStore, passwd); - keyManager = (X509ExtendedKeyManager)keyFactory.getKeyManagers()[0]; - trustManager = new AlwaysTrustManager(); - - CipherTest cipherTest = new CipherTest(peerFactory); - Thread serverThread = new Thread(peerFactory.newServer(cipherTest), - "Server"); - serverThread.setDaemon(true); - serverThread.start(); - System.out.println("Done"); - cipherTest.run(); - time = System.currentTimeMillis() - time; - System.out.println("Done. (" + time + " ms)"); - } - - static abstract class PeerFactory { - - abstract String getName(); - - abstract Client newClient(CipherTest cipherTest) throws Exception; - - abstract Server newServer(CipherTest cipherTest) throws Exception; - - boolean isSupported(String cipherSuite, String protocol) { - // skip kerberos cipher suites - if (cipherSuite.startsWith("TLS_KRB5")) { - System.out.println("Skipping unsupported test for " + - cipherSuite + " of " + protocol); - return false; - } - - // skip SSLv2Hello protocol - if (protocol.equals("SSLv2Hello")) { - System.out.println("Skipping unsupported test for " + - cipherSuite + " of " + protocol); - return false; - } - - // ignore exportable cipher suite for TLSv1.1 - if (protocol.equals("TLSv1.1")) { - if (cipherSuite.indexOf("_EXPORT_WITH") != -1) { - System.out.println("Skipping obsoleted test for " + - cipherSuite + " of " + protocol); - return false; - } - } - - // ignore obsoleted cipher suite for the specified protocol - // TODO - - // ignore unsupported cipher suite for the specified protocol - // TODO - - return true; - } - } - -} - -// we currently don't do any chain verification. we assume that works ok -// and we can speed up the test. we could also just add a plain certificate -// chain comparision with our trusted certificates. -class AlwaysTrustManager implements X509TrustManager { - - public AlwaysTrustManager() { - - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - // empty - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - // empty - } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} - -class MyX509KeyManager extends X509ExtendedKeyManager { - - private final X509ExtendedKeyManager keyManager; - private String authType; - - MyX509KeyManager(X509ExtendedKeyManager keyManager) { - this.keyManager = keyManager; - } - - void setAuthType(String authType) { - this.authType = authType; - } - - public String[] getClientAliases(String keyType, Principal[] issuers) { - if (authType == null) { - return null; - } - return keyManager.getClientAliases(authType, issuers); - } - - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - if (authType == null) { - return null; - } - return keyManager.chooseClientAlias(new String[] {authType}, - issuers, socket); - } - - public String chooseEngineClientAlias(String[] keyType, - Principal[] issuers, SSLEngine engine) { - if (authType == null) { - return null; - } - return keyManager.chooseEngineClientAlias(new String[] {authType}, - issuers, engine); - } - - public String[] getServerAliases(String keyType, Principal[] issuers) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public String chooseEngineServerAlias(String keyType, Principal[] issuers, - SSLEngine engine) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public X509Certificate[] getCertificateChain(String alias) { - return keyManager.getCertificateChain(alias); - } - - public PrivateKey getPrivateKey(String alias) { - return keyManager.getPrivateKey(alias); - } - -} - -class DaemonThreadFactory implements ThreadFactory { - - final static ThreadFactory INSTANCE = new DaemonThreadFactory(); - - private final static ThreadFactory DEFAULT = Executors.defaultThreadFactory(); - - public Thread newThread(Runnable r) { - Thread t = DEFAULT.newThread(r); - t.setDaemon(true); - return t; - } - -}
--- a/test/javax/net/ssl/sanity/interop/ClientJSSEServerJSSE.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4496785 - * @summary Verify that all ciphersuites work in all configurations - * @author Andreas Sterbenz - * @run main/othervm/timeout=300 ClientJSSEServerJSSE - */ - -import java.security.Security; - -public class ClientJSSEServerJSSE { - - public static void main(String[] args) throws Exception { - // reset security properties to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - Security.setProperty("jdk.certpath.disabledAlgorithms", ""); - - CipherTest.main(new JSSEFactory(), args); - } - - private static class JSSEFactory extends CipherTest.PeerFactory { - - String getName() { - return "Client JSSE - Server JSSE"; - } - - CipherTest.Client newClient(CipherTest cipherTest) throws Exception { - return new JSSEClient(cipherTest); - } - - CipherTest.Server newServer(CipherTest cipherTest) throws Exception { - return new JSSEServer(cipherTest); - } - } -}
--- a/test/javax/net/ssl/sanity/interop/JSSEClient.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.io.*; -import java.net.*; -import java.util.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -class JSSEClient extends CipherTest.Client { - - private final SSLContext sslContext; - private final MyX509KeyManager keyManager; - - JSSEClient(CipherTest cipherTest) throws Exception { - super(cipherTest); - this.keyManager = new MyX509KeyManager(CipherTest.keyManager); - sslContext = SSLContext.getInstance("TLS"); - } - - void runTest(CipherTest.TestParameters params) throws Exception { - SSLSocket socket = null; - try { - keyManager.setAuthType(params.clientAuth); - sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom); - SSLSocketFactory factory = (SSLSocketFactory)sslContext.getSocketFactory(); - socket = (SSLSocket)factory.createSocket("127.0.0.1", cipherTest.serverPort); - socket.setSoTimeout(cipherTest.TIMEOUT); - socket.setEnabledCipherSuites(new String[] {params.cipherSuite}); - socket.setEnabledProtocols(new String[] {params.protocol}); - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - sendRequest(in, out); - socket.close(); - SSLSession session = socket.getSession(); - session.invalidate(); - String cipherSuite = session.getCipherSuite(); - if (params.cipherSuite.equals(cipherSuite) == false) { - throw new Exception("Negotiated ciphersuite mismatch: " + cipherSuite + " != " + params.cipherSuite); - } - String protocol = session.getProtocol(); - if (params.protocol.equals(protocol) == false) { - throw new Exception("Negotiated protocol mismatch: " + protocol + " != " + params.protocol); - } - if (cipherSuite.indexOf("DH_anon") == -1) { - session.getPeerCertificates(); - } - Certificate[] certificates = session.getLocalCertificates(); - if (params.clientAuth == null) { - if (certificates != null) { - throw new Exception("Local certificates should be null"); - } - } else { - if ((certificates == null) || (certificates.length == 0)) { - throw new Exception("Certificates missing"); - } - String keyAlg = certificates[0].getPublicKey().getAlgorithm(); - if (params.clientAuth != keyAlg) { - throw new Exception("Certificate type mismatch: " + keyAlg + " != " + params.clientAuth); - } - } - } finally { - if (socket != null) { - socket.close(); - } - } - } - -}
--- a/test/javax/net/ssl/sanity/interop/JSSEServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.concurrent.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -class JSSEServer extends CipherTest.Server { - - SSLServerSocket serverSocket; - - JSSEServer(CipherTest cipherTest) throws Exception { - super(cipherTest); - SSLContext serverContext = SSLContext.getInstance("TLS"); - serverContext.init(new KeyManager[] {cipherTest.keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom); - - SSLServerSocketFactory factory = (SSLServerSocketFactory)serverContext.getServerSocketFactory(); - serverSocket = (SSLServerSocket)factory.createServerSocket(cipherTest.serverPort); - cipherTest.serverPort = serverSocket.getLocalPort(); - serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites()); - serverSocket.setWantClientAuth(true); - } - - public void run() { - System.out.println("JSSE Server listening on port " + cipherTest.serverPort); - Executor exec = Executors.newFixedThreadPool - (cipherTest.THREADS, DaemonThreadFactory.INSTANCE); - try { - while (true) { - final SSLSocket socket = (SSLSocket)serverSocket.accept(); - socket.setSoTimeout(cipherTest.TIMEOUT); - Runnable r = new Runnable() { - public void run() { - try { - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - handleRequest(in, out); - out.flush(); - socket.close(); - socket.getSession().invalidate(); - } catch (IOException e) { - cipherTest.setFailed(); - e.printStackTrace(); - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - cipherTest.setFailed(); - System.out.println("Exception closing socket on server side:"); - e.printStackTrace(); - } - } - } - } - }; - exec.execute(r); - } - } catch (IOException e) { - cipherTest.setFailed(); - e.printStackTrace(); - // - } - } - -}
--- a/test/javax/net/ssl/templates/SSLEngineTemplate.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,380 +0,0 @@ -/* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 1234567 - * @summary SSLEngine has not yet caused Solaris kernel to panic - * @run main/othervm SSLEngineTemplate - */ - -/** - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class SSLEngineTemplate { - - /* - * Enables logging of the SSLEngine operations. - */ - private static final boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static final boolean debug = false; - - private final SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static final String pathToStores = "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static final String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - SSLEngineTemplate test = new SSLEngineTemplate(); - test.runTest(); - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public SSLEngineTemplate() throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult clientResult; // results from client's last operation - SSLEngineResult serverResult; // results from server's last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - while (!isEngineClosed(clientEngine) || - !isEngineClosed(serverEngine)) { - - log("================"); - - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - cTOs.flip(); - sTOc.flip(); - - log("----"); - - clientResult = clientEngine.unwrap(sTOc, clientIn); - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - cTOs.compact(); - sTOc.compact(); - - /* - * After we've transfered all application data between the client - * and server, we close the clientEngine's outbound stream. - * This generates a close_notify handshake message, which the - * server engine receives and responds by closing itself. - */ - if (!dataDone && (clientOut.limit() == serverIn.position()) && - (serverOut.limit() == clientIn.position())) { - - /* - * A sanity check to ensure we got what was sent. - */ - checkTransfer(serverOut, clientIn); - checkTransfer(clientOut, serverIn); - - log("\tClosing clientEngine's *OUTBOUND*..."); - clientEngine.closeOutbound(); - dataDone = true; - } - } - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" + - "\t\"getStatus() / getHandshakeStatus()\" +\n" + - "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str + - result.getStatus() + "/" + hsStatus + ", " + - result.bytesConsumed() + "/" + result.bytesProduced() + - " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/templates/SSLSocketSSLEngineTemplate.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,491 +0,0 @@ -/* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7105780 - * @summary Add SSLSocket client/SSLEngine server to templates directory. - * @run main/othervm SSLSocketSSLEngineTemplate - */ - -/** - * A SSLSocket/SSLEngine interop test case. This is not the way to - * code SSLEngine-based servers, but works for what we need to do here, - * which is to make sure that SSLEngine/SSLSockets can talk to each other. - * SSLEngines can use direct or indirect buffers, and different code - * is used to get at the buffer contents internally, so we test that here. - * - * The test creates one SSLSocket (client) and one SSLEngine (server). - * The SSLSocket talks to a raw ServerSocket, and the server code - * does the translation between byte [] and ByteBuffers that the SSLEngine - * can use. The "transport" layer consists of a Socket Input/OutputStream - * and two byte buffers for the SSLEngines: think of them - * as directly connected pipes. - * - * Again, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * write() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * read() ... ServerHello/Certificate - * write() ... ClientKeyExchange - * write() ... ChangeCipherSpec - * write() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * read() ... ChangeCipherSpec - * read() ... Finished - */ -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.net.*; -import java.security.*; -import java.nio.*; - -public class SSLSocketSSLEngineTemplate { - - /* - * Enables logging of the SSL/TLS operations. - */ - private static final boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static final boolean debug = false; - private final SSLContext sslc; - private SSLEngine serverEngine; // server-side SSLEngine - private SSLSocket sslSocket; // client-side socket - private ServerSocket serverSocket; // server-side Socket, generates the... - private Socket socket; // server-side socket that will read - - private final byte[] serverMsg = - "Hi there Client, I'm a Server.".getBytes(); - private final byte[] clientMsg = - "Hello Server, I'm a Client! Pleased to meet you!".getBytes(); - - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - private volatile Exception clientException; - private volatile Exception serverException; - - /* - * For data transport, this example uses local ByteBuffers. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores/trust material. - */ - private static final String pathToStores = "../etc/"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - private static final String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + keyStoreFile; - private static final String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - String [] protocols = new String [] { - "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }; - - for (String protocol : protocols) { - log("Testing " + protocol); - /* - * Run the tests with direct and indirect buffers. - */ - SSLSocketSSLEngineTemplate test = - new SSLSocketSSLEngineTemplate(protocol); - test.runTest(true); - test.runTest(false); - } - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public SSLSocketSSLEngineTemplate(String protocol) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance(protocol); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Run the test. - * - * Sit in a tight loop, with the server engine calling wrap/unwrap - * regardless of whether data is available or not. We do this until - * we get the application data. Then we shutdown and go to the next one. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest(boolean direct) throws Exception { - boolean serverClose = direct; - - serverSocket = new ServerSocket(); - serverSocket.setReuseAddress(false); - serverSocket.bind(null); - int port = serverSocket.getLocalPort(); - Thread thread = createClientThread(port, serverClose); - - socket = serverSocket.accept(); - socket.setSoTimeout(500); - serverSocket.close(); - - createSSLEngine(); - createBuffers(direct); - - try { - boolean closed = false; - - InputStream is = socket.getInputStream(); - OutputStream os = socket.getOutputStream(); - - SSLEngineResult serverResult; // results from last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - byte[] inbound = new byte[8192]; - byte[] outbound = new byte[8192]; - - while (!isEngineClosed(serverEngine)) { - int len; - - // Inbound data - log("================"); - - // Read from the Client side. - try { - len = is.read(inbound); - if (len == -1) { - throw new Exception("Unexpected EOF"); - } - cTOs.put(inbound, 0, len); - } catch (SocketTimeoutException ste) { - // swallow. Nothing yet, probably waiting on us. - } - - cTOs.flip(); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - cTOs.compact(); - - // Outbound data - log("----"); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - sTOc.flip(); - - if ((len = sTOc.remaining()) != 0) { - sTOc.get(outbound, 0, len); - os.write(outbound, 0, len); - // Give the other side a chance to process - } - - sTOc.compact(); - - if (!closed && (serverOut.remaining() == 0)) { - closed = true; - - /* - * We'll alternate initiatating the shutdown. - * When the server initiates, it will take one more - * loop, but tests the orderly shutdown. - */ - if (serverClose) { - serverEngine.closeOutbound(); - } - serverIn.flip(); - - /* - * A sanity check to ensure we got what was sent. - */ - if (serverIn.remaining() != clientMsg.length) { - throw new Exception("Client: Data length error"); - } - - for (int i = 0; i < clientMsg.length; i++) { - if (clientMsg[i] != serverIn.get()) { - throw new Exception("Client: Data content error"); - } - } - serverIn.compact(); - } - } - } catch (Exception e) { - serverException = e; - } finally { - if (socket != null) { - socket.close(); - } - - // Wait for the client to join up with us. - if (thread != null) { - thread.join(); - } - - if (serverException != null) { - if (clientException != null) { - serverException.initCause(clientException); - } - throw serverException; - } - if (clientException != null) { - if (serverException != null) { - clientException.initCause(serverException); - } - throw clientException; - } - } - } - - /* - * Create a client thread which does simple SSLSocket operations. - * We'll write and read one data packet. - */ - private Thread createClientThread(final int port, - final boolean serverClose) throws Exception { - - Thread t = new Thread("ClientThread") { - - @Override - public void run() { - try { - Thread.sleep(1000); // Give server time to finish setup. - - sslSocket = (SSLSocket) sslc.getSocketFactory(). - createSocket("localhost", port); - OutputStream os = sslSocket.getOutputStream(); - InputStream is = sslSocket.getInputStream(); - - // write(byte[]) goes in one shot. - os.write(clientMsg); - - byte[] inbound = new byte[2048]; - int pos = 0; - - int len; - while ((len = is.read(inbound, pos, 2048 - pos)) != -1) { - pos += len; - // Let the client do the closing. - if ((pos == serverMsg.length) && !serverClose) { - sslSocket.close(); - break; - } - } - - if (pos != serverMsg.length) { - throw new Exception("Client: Data length error"); - } - - for (int i = 0; i < serverMsg.length; i++) { - if (inbound[i] != serverMsg[i]) { - throw new Exception("Client: Data content error"); - } - } - } catch (Exception e) { - clientException = e; - } - } - }; - t.start(); - return t; - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngine() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.getNeedClientAuth(); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers(boolean direct) { - - SSLSession session = serverEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - if (direct) { - serverIn = ByteBuffer.allocateDirect(appBufferMax + 50); - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - } else { - serverIn = ByteBuffer.allocate(appBufferMax + 50); - cTOs = ByteBuffer.allocate(netBufferMax); - sTOc = ByteBuffer.allocate(netBufferMax); - } - - serverOut = ByteBuffer.wrap(serverMsg); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" - + "\t\"getStatus() / getHandshakeStatus()\" +\n" - + "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str - + result.getStatus() + "/" + hsStatus + ", " - + result.bytesConsumed() + "/" + result.bytesProduced() - + " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/javax/net/ssl/templates/SSLSocketTemplate.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,844 +0,0 @@ -/* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// Please run in othervm mode. SunJSSE does not support dynamic system -// properties, no way to re-use system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 8161106 8170329 - * @modules jdk.crypto.ec - * @summary Improve SSLSocket test template - * @run main/othervm SSLSocketTemplate - */ - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManagerFactory; -import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.Base64; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Template to help speed your client/server tests. - * - * Two examples that use this template: - * test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java - * test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java - */ -public class SSLSocketTemplate { - - /* - * ================== - * Run the test case. - */ - public static void main(String[] args) throws Exception { - (new SSLSocketTemplate()).run(); - } - - /* - * Run the test case. - */ - public void run() throws Exception { - bootup(); - } - - /* - * Define the server side application of the test for the specified socket. - */ - protected void runServerApplication(SSLSocket socket) throws Exception { - // here comes the test logic - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - /* - * Define the client side application of the test for the specified socket. - * This method is used if the returned value of - * isCustomizedClientConnection() is false. - * - * @param socket may be null is no client socket is generated. - * - * @see #isCustomizedClientConnection() - */ - protected void runClientApplication(SSLSocket socket) throws Exception { - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - /* - * Define the client side application of the test for the specified - * server port. This method is used if the returned value of - * isCustomizedClientConnection() is true. - * - * Note that the client need to connect to the server port by itself - * for the actual message exchange. - * - * @see #isCustomizedClientConnection() - */ - protected void runClientApplication(int serverPort) throws Exception { - // blank - } - - /* - * Create an instance of SSLContext for client use. - */ - protected SSLContext createClientSSLContext() throws Exception { - return createSSLContext(trustedCertStrs, - endEntityCertStrs, endEntityPrivateKeys, - endEntityPrivateKeyNames, - getClientContextParameters()); - } - - /* - * Create an instance of SSLContext for server use. - */ - protected SSLContext createServerSSLContext() throws Exception { - return createSSLContext(trustedCertStrs, - endEntityCertStrs, endEntityPrivateKeys, - endEntityPrivateKeyNames, - getServerContextParameters()); - } - - /* - * The parameters used to configure SSLContext. - */ - protected static final class ContextParameters { - final String contextProtocol; - final String tmAlgorithm; - final String kmAlgorithm; - - ContextParameters(String contextProtocol, - String tmAlgorithm, String kmAlgorithm) { - - this.contextProtocol = contextProtocol; - this.tmAlgorithm = tmAlgorithm; - this.kmAlgorithm = kmAlgorithm; - } - } - - /* - * Get the client side parameters of SSLContext. - */ - protected ContextParameters getClientContextParameters() { - return new ContextParameters("TLS", "PKIX", "NewSunX509"); - } - - /* - * Get the server side parameters of SSLContext. - */ - protected ContextParameters getServerContextParameters() { - return new ContextParameters("TLS", "PKIX", "NewSunX509"); - } - - /* - * Does the client side use customized connection other than - * explicit Socket.connect(), for example, URL.openConnection()? - */ - protected boolean isCustomizedClientConnection() { - return false; - } - - /* - * Configure the server side socket. - */ - protected void configureServerSocket(SSLServerSocket socket) { - - } - - /* - * ============================================= - * Define the client and server side operations. - * - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Is the server ready to serve? - */ - private final CountDownLatch serverCondition = new CountDownLatch(1); - - /* - * Is the client ready to handshake? - */ - private final CountDownLatch clientCondition = new CountDownLatch(1); - - /* - * What's the server port? Use any free port by default - */ - private volatile int serverPort = 0; - - /* - * Define the server side of the test. - */ - private void doServerSide() throws Exception { - // kick start the server side service - SSLContext context = createServerSSLContext(); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - configureServerSocket(sslServerSocket); - serverPort = sslServerSocket.getLocalPort(); - - // Signal the client, the server is ready to accept connection. - serverCondition.countDown(); - - // Try to accept a connection in 30 seconds. - SSLSocket sslSocket; - try { - sslServerSocket.setSoTimeout(30000); - sslSocket = (SSLSocket)sslServerSocket.accept(); - } catch (SocketTimeoutException ste) { - // Ignore the test case if no connection within 30 seconds. - System.out.println( - "No incoming client connection in 30 seconds. " + - "Ignore in server side."); - return; - } finally { - sslServerSocket.close(); - } - - // handle the connection - try { - // Is it the expected client connection? - // - // Naughty test cases or third party routines may try to - // connection to this server port unintentionally. In - // order to mitigate the impact of unexpected client - // connections and avoid intermittent failure, it should - // be checked that the accepted connection is really linked - // to the expected client. - boolean clientIsReady = - clientCondition.await(30L, TimeUnit.SECONDS); - - if (clientIsReady) { - // Run the application in server side. - runServerApplication(sslSocket); - } else { // Otherwise, ignore - // We don't actually care about plain socket connections - // for TLS communication testing generally. Just ignore - // the test if the accepted connection is not linked to - // the expected client or the client connection timeout - // in 30 seconds. - System.out.println( - "The client is not the expected one or timeout. " + - "Ignore in server side."); - } - } finally { - sslSocket.close(); - } - } - - /* - * Define the client side of the test. - */ - private void doClientSide() throws Exception { - - // Wait for server to get started. - // - // The server side takes care of the issue if the server cannot - // get started in 90 seconds. The client side would just ignore - // the test case if the serer is not ready. - boolean serverIsReady = - serverCondition.await(90L, TimeUnit.SECONDS); - if (!serverIsReady) { - System.out.println( - "The server is not ready yet in 90 seconds. " + - "Ignore in client side."); - return; - } - - if (isCustomizedClientConnection()) { - // Signal the server, the client is ready to communicate. - clientCondition.countDown(); - - // Run the application in client side. - runClientApplication(serverPort); - - return; - } - - SSLContext context = createClientSSLContext(); - SSLSocketFactory sslsf = context.getSocketFactory(); - - try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) { - try { - sslSocket.connect( - new InetSocketAddress("localhost", serverPort), 15000); - } catch (IOException ioe) { - // The server side may be impacted by naughty test cases or - // third party routines, and cannot accept connections. - // - // Just ignore the test if the connection cannot be - // established. - System.out.println( - "Cannot make a connection in 15 seconds. " + - "Ignore in client side."); - return; - } - - // OK, here the client and server get connected. - - // Signal the server, the client is ready to communicate. - clientCondition.countDown(); - - // There is still a chance in theory that the server thread may - // wait client-ready timeout and then quit. The chance should - // be really rare so we don't consider it until it becomes a - // real problem. - - // Run the application in client side. - runClientApplication(sslSocket); - } - } - - /* - * ============================================= - * Stuffs to customize the SSLContext instances. - */ - - /* - * ======================================= - * Certificates and keys used in the test. - */ - // Trusted certificates. - private final static String[] trustedCertStrs = { - // SHA256withECDSA, curve prime256v1 - // Validity - // Not Before: Nov 25 04:19:51 2016 GMT - // Not After : Nov 5 04:19:51 2037 GMT - // Subject Key Identifier: - // CA:48:E8:00:C1:42:BD:59:9B:79:D9:B4:B4:CE:3F:68:0C:C8:C4:0C - "-----BEGIN CERTIFICATE-----\n" + - "MIICHDCCAcGgAwIBAgIJAJtKs6ZEcVjxMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + - "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + - "ZTAeFw0xNjExMjUwNDE5NTFaFw0zNzExMDUwNDE5NTFaMDsxCzAJBgNVBAYTAlVT\n" + - "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZTBZ\n" + - "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABKMO/AFDHZia65RaqMIBX7WBdtzFj8fz\n" + - "ggqMADLJhoszS6qfTUDYskETw3uHfB3KAOENsoKX446qFFPuVjxS1aejga0wgaow\n" + - "HQYDVR0OBBYEFMpI6ADBQr1Zm3nZtLTOP2gMyMQMMGsGA1UdIwRkMGKAFMpI6ADB\n" + - "Qr1Zm3nZtLTOP2gMyMQMoT+kPTA7MQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2\n" + - "YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2WCCQCbSrOmRHFY8TAPBgNV\n" + - "HRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjAKBggqhkjOPQQDAgNJADBGAiEA5cJ/\n" + - "jirBbXxzpZ6kdp/Zb/yrIBnr4jiPGJTLgRTb8s4CIQChUDfP1Zqg0qJVfqFNaL4V\n" + - "a0EAeJHXGZnvCGGqHzoxkg==\n" + - "-----END CERTIFICATE-----", - - // SHA256withRSA, 2048 bits - // Validity - // Not Before: Nov 25 04:20:02 2016 GMT - // Not After : Nov 5 04:20:02 2037 GMT - // Subject Key Identifier: - // A2:DC:55:38:E4:47:7C:8B:D3:E0:CA:FA:AD:3A:C8:4A:DD:12:A0:8E - "-----BEGIN CERTIFICATE-----\n" + - "MIIDpzCCAo+gAwIBAgIJAO586A+hYNXaMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + - "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" + - "aXZjZTAeFw0xNjExMjUwNDIwMDJaFw0zNzExMDUwNDIwMDJaMDsxCzAJBgNVBAYT\n" + - "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + - "ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMm3veDSU4zKXO0aAHos\n" + - "cFRXGLBTe+MUJXAtlkNyx7VKaMZNt5wrUuqzyi/r0LFUdRfNCzZf3X8s8HPHQVii\n" + - "29tK0y/yeTn4sJTATSmGaAysMJQpKQcfAQ79ItcEGQ721TFQZ3kOBdgp3t/yUYAP\n" + - "K2tFze/QbIw72LE52SBnPPPTzyimNw7Ai2MLl4eQlyMkTs7JS07zIiAO5QYbS8s+\n" + - "1NW0A3Y+d0B0q8wYEoHGq7QVjOKlSAksfO0tzi4l0Zu6Uf+J5kMAyZ4ZFgEJvGvw\n" + - "y/OKJ+soRFH/5cy1SL8B6AWD1y7WXugeeHTHRW1eOjTxqfG1rZqTVd2lfOMER8y1\n" + - "bXcCAwEAAaOBrTCBqjAdBgNVHQ4EFgQUotxVOORHfIvT4Mr6rTrISt0SoI4wawYD\n" + - "VR0jBGQwYoAUotxVOORHfIvT4Mr6rTrISt0SoI6hP6Q9MDsxCzAJBgNVBAYTAlVT\n" + - "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZYIJ\n" + - "AO586A+hYNXaMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3\n" + - "DQEBCwUAA4IBAQAtNZJSFeFU6Yid0WSCs2qLAVaTyHsUNSUPUFIIhFAKxdP4DFS0\n" + - "+aeOFwdqizAU3kReAYULsfwEBgO51lPBSpB+9coUNQwu7cc8Q5Xqw/llRB0PrINS\n" + - "pZl7PW6Ur2ExTBocnUT9A/nhm8iO4PFD/Ly11sf5OdZihhX69NJ2h3a3gcrLjIpO\n" + - "L/ewTOgSi5xs+AGGQa+huN3YVL7dh+/rCUvMZVSBX5PloxWS5MMJi0Ui6YjwCFGO\n" + - "J4G9m7pI+gJs/x1UG0AgplMF2UCFfiY1SAeE2nKAeOOXAXEwEjFy0ToVTmqXx7fg\n" + - "m9YjhuePxlBrd2DF/YW0pc8gmLnrtm4rKPLz\n" + - "-----END CERTIFICATE-----", - - // SHA256withDSA, 2048 bits - // Validity - // Not Before: Nov 25 04:19:56 2016 GMT - // Not After : Nov 5 04:19:56 2037 GMT - // Subject Key Identifier: - // 19:46:10:43:24:6A:A5:14:BE:E2:92:01:79:F0:4C:5F:E1:AE:81:B5 - "-----BEGIN CERTIFICATE-----\n" + - "MIIFCzCCBLGgAwIBAgIJAOnEn6YZD/sAMAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2UwHhcNMTYxMTI1MDQxOTU2WhcNMzcxMTA1MDQxOTU2WjA7MQswCQYDVQQGEwJV\n" + - "UzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2Uw\n" + - "ggNGMIICOQYHKoZIzjgEATCCAiwCggEBAJa17ZYdIChv5yeYuPK3zXxgUEGGsdUD\n" + - "AzfQUxtMryCtc3aNgWLxsN1/QYvp9v+hh4twnG20VemCEH9Qlx06Pxg74DwSOA83\n" + - "SecO2y7cdgmrHpep9drxKbXVZafwBhbTSwhV+IDO7EO6+LaRvZuya/YOqNIE9ENx\n" + - "FVk0NrNsDB6pfDEXZsCZALMN2mcl8KGn1q7vdzJQUEV7F6uLGP33znVfmQyWJH3Y\n" + - "W09WVCFXHvDzZHGXDO2O2QwIU1B5AsXnOGeLnKgXzErCoNKwUbVFP0W0OVeJo4pc\n" + - "ZfL/8TVELGG90AuuH1V3Gsq6PdzCDPw4Uv/v5m7/6kwXqBQxAJA7jhMCIQCORIGV\n" + - "mHy5nBLRhIP4vC7vsTxb4CTApPVmZeL5gTIwtQKCAQB2VZLY22k2+IQM6deRGK3L\n" + - "l7tPChGrKnGmTbtUThIza70Sp9DmTBiLzMEY+IgG8kYuT5STVxWjs0cxXCKZGMQW\n" + - "tioMtiXPA2M3HA0/8E0mDLSmzb0RAd2xxnDyGsuqo1eVmx7PLjN3bn3EjhD/+j3d\n" + - "Jx3ZVScMGyq7sVWppUvpudEXi+2etf6GUHjrcX27juo7u4zQ1ezC/HYG1H+jEFqG\n" + - "hdQ6b7H+LBHZH9LegOyIZTMrzAY/TwIr77sXrNJWRoxmDErKB+8bRDybYhNJswlZ\n" + - "m0N5YYUlPmepgbl6XzwCv0y0d81h3bayqIPLXEUtRAl9GuM0hNAlA1Y+qSn9xLFY\n" + - "A4IBBQACggEAZgWC0uflwqQQP1GRU1tolmFZwyVtKre7SjYgCeQBrOa0Xnj/SLaD\n" + - "g1HZ1oH0hccaR/45YouJiCretbbsQ77KouldGSGqTHJgRL75Y2z5uvxa60+YxZ0Z\n" + - "v8xvZnj4seyOjgJLxSSYSPl5n/F70RaNiCLVz/kGe6OQ8KoAeQjdDTOHXCegO9KX\n" + - "tvhM7EaYc8CII9OIR7S7PXJW0hgLKynZcu/Unh02aM0ABh/uLmw1+tvo8e8KTp98\n" + - "NKYSVf6kV3/ya58n4h64UbIYL08JoKUM/5SFETcKAZTU0YKZbpWTM79oJMr8oYVk\n" + - "P9jKitNsXq0Xkzt5dSO0kfu/kM7zpnaFsqOBrTCBqjAdBgNVHQ4EFgQUGUYQQyRq\n" + - "pRS+4pIBefBMX+GugbUwawYDVR0jBGQwYoAUGUYQQyRqpRS+4pIBefBMX+GugbWh\n" + - "P6Q9MDsxCzAJBgNVBAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5K\n" + - "U1NFIFRlc3QgU2VyaXZjZYIJAOnEn6YZD/sAMA8GA1UdEwEB/wQFMAMBAf8wCwYD\n" + - "VR0PBAQDAgEGMAsGCWCGSAFlAwQDAgNHADBEAiAwBafz5RRR9nc4cCYoYuBlT/D9\n" + - "9eayhkjhBY/zYunypwIgNp/JnFR88/T4hh36QfSKBGXId9RBCM6uaOkOKnEGkps=\n" + - "-----END CERTIFICATE-----" - }; - - // End entity certificate. - private final static String[] endEntityCertStrs = { - // SHA256withECDSA, curve prime256v1 - // Validity - // Not Before: Nov 25 04:19:51 2016 GMT - // Not After : Aug 12 04:19:51 2036 GMT - // Authority Key Identifier: - // CA:48:E8:00:C1:42:BD:59:9B:79:D9:B4:B4:CE:3F:68:0C:C8:C4:0C - "-----BEGIN CERTIFICATE-----\n" + - "MIIB1zCCAXygAwIBAgIJAPFq2QL/nUNZMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + - "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + - "ZTAeFw0xNjExMjUwNDE5NTFaFw0zNjA4MTIwNDE5NTFaMFUxCzAJBgNVBAYTAlVT\n" + - "MQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZjZTEY\n" + - "MBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD\n" + - "QgAE4yvRGVvy9iVATyuHPJVdX6+lh/GLm/sRJ5qLT/3PVFOoNIvlEVNiARo7xhyj\n" + - "2p6bnf32gNg5Ye+QCw20VUv9E6NPME0wCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBSO\n" + - "hHlHZQp9hyBfSGTSQWeszqMXejAfBgNVHSMEGDAWgBTKSOgAwUK9WZt52bS0zj9o\n" + - "DMjEDDAKBggqhkjOPQQDAgNJADBGAiEAu3t6cvFglBAZfkhZlEwB04ZjUFqyfiRj\n" + - "4Hr275E4ZoQCIQDUEonJHlmA19J6oobfR5lYsmoqPm1r0DPm/IiNNKGKKA==\n" + - "-----END CERTIFICATE-----", - - // SHA256withRSA, 2048 bits - // Validity - // Not Before: Nov 25 04:20:02 2016 GMT - // Not After : Aug 12 04:20:02 2036 GMT - // Authority Key Identifier: - // A2:DC:55:38:E4:47:7C:8B:D3:E0:CA:FA:AD:3A:C8:4A:DD:12:A0:8E - "-----BEGIN CERTIFICATE-----\n" + - "MIIDdjCCAl6gAwIBAgIJAJDcIGOlAmBmMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + - "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" + - "aXZjZTAeFw0xNjExMjUwNDIwMDJaFw0zNjA4MTIwNDIwMDJaMFUxCzAJBgNVBAYT\n" + - "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + - "ZTEYMBYGA1UEAwwPUmVncmVzc2lvbiBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOC\n" + - "AQ8AMIIBCgKCAQEAp0dHrifTg2aY0sH03f2JjK2fW4DL6gLDKq0YirsNE07z54LF\n" + - "IeeDio49XwPjB7OpbUTC1hf/YKZ7XiRWyPa1rYozZ88emhZt+cpkyKz+nmW4avlA\n" + - "WnrV+gx4+bU9T+WuBWdAraBcq27Y1I26yfCEtC8k3+O0sdlHbhasF+BUDmX/n4+n\n" + - "ifJdbNm5eSDx8eFYHFTdjhAud3An2X6QD9WWSoJpPdDi4utHhFAlxW6osjJxsAPv\n" + - "zo8YsqmpCMjZcEks4ZsqiZKKiWUWUAjCcbMerDPDX29fyeo348uztvJsmNRzfcwl\n" + - "FtwxpYdxuZqwHi2QoNaQTGXjjbZFmjn7qEkjXwIDAQABo2MwYTALBgNVHQ8EBAMC\n" + - "A+gwHQYDVR0OBBYEFP+henfufE6Znr60lRkmayadVdxnMB8GA1UdIwQYMBaAFKLc\n" + - "VTjkR3yL0+DK+q06yErdEqCOMBIGA1UdEQEB/wQIMAaHBH8AAAEwDQYJKoZIhvcN\n" + - "AQELBQADggEBAK56pV2XoAIkrHFTCkWtYX518nuvkzN6a6BqPKALQlmlbJnq/lhV\n" + - "tPQx79b0j7tow28l2ze/3M0hRb5Ft/d/7mITZNMR+0owk4U51AU2NacRt7fpoxu5\n" + - "wX3hTa4VgX2+BAXeoWF+Yzy6Jj5gAVmSLzBnkTUH0d+EyL1pp+DFE3QdvZqf3+nP\n" + - "zkxz15h3iW8FwI+7/19MX2j2XB/sG8mJpqoszWw8lM4qCa2eWyCbqSHhPi+/+rGg\n" + - "dDG5uzZeOC845GEH2T3tHDA+F3WwcZG/W+4RR6ZaaHlqPKKMcwFL73YbsqdCiKBv\n" + - "p6sXrhIiP0oXImRBRLDlidj5TIOLfAtNM9A=\n" + - "-----END CERTIFICATE-----", - - // SHA256withDSA, 2048 bits - // Validity - // Not Before: Nov 25 04:19:56 2016 GMT - // Not After : Aug 12 04:19:56 2036 GMT - // Authority Key Identifier: - // 19:46:10:43:24:6A:A5:14:BE:E2:92:01:79:F0:4C:5F:E1:AE:81:B5 - "-----BEGIN CERTIFICATE-----\n" + - "MIIE2jCCBICgAwIBAgIJAONcI1oba9V9MAsGCWCGSAFlAwQDAjA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2UwHhcNMTYxMTI1MDQxOTU2WhcNMzYwODEyMDQxOTU2WjBVMQswCQYDVQQGEwJV\n" + - "UzENMAsGA1UECgwESmF2YTEdMBsGA1UECwwUU3VuSlNTRSBUZXN0IFNlcml2Y2Ux\n" + - "GDAWBgNVBAMMD1JlZ3Jlc3Npb24gVGVzdDCCA0YwggI5BgcqhkjOOAQBMIICLAKC\n" + - "AQEAlrXtlh0gKG/nJ5i48rfNfGBQQYax1QMDN9BTG0yvIK1zdo2BYvGw3X9Bi+n2\n" + - "/6GHi3CcbbRV6YIQf1CXHTo/GDvgPBI4DzdJ5w7bLtx2Casel6n12vEptdVlp/AG\n" + - "FtNLCFX4gM7sQ7r4tpG9m7Jr9g6o0gT0Q3EVWTQ2s2wMHql8MRdmwJkAsw3aZyXw\n" + - "oafWru93MlBQRXsXq4sY/ffOdV+ZDJYkfdhbT1ZUIVce8PNkcZcM7Y7ZDAhTUHkC\n" + - "xec4Z4ucqBfMSsKg0rBRtUU/RbQ5V4mjilxl8v/xNUQsYb3QC64fVXcayro93MIM\n" + - "/DhS/+/mbv/qTBeoFDEAkDuOEwIhAI5EgZWYfLmcEtGEg/i8Lu+xPFvgJMCk9WZl\n" + - "4vmBMjC1AoIBAHZVktjbaTb4hAzp15EYrcuXu08KEasqcaZNu1ROEjNrvRKn0OZM\n" + - "GIvMwRj4iAbyRi5PlJNXFaOzRzFcIpkYxBa2Kgy2Jc8DYzccDT/wTSYMtKbNvREB\n" + - "3bHGcPIay6qjV5WbHs8uM3dufcSOEP/6Pd0nHdlVJwwbKruxVamlS+m50ReL7Z61\n" + - "/oZQeOtxfbuO6ju7jNDV7ML8dgbUf6MQWoaF1Dpvsf4sEdkf0t6A7IhlMyvMBj9P\n" + - "Aivvuxes0lZGjGYMSsoH7xtEPJtiE0mzCVmbQ3lhhSU+Z6mBuXpfPAK/TLR3zWHd\n" + - "trKog8tcRS1ECX0a4zSE0CUDVj6pKf3EsVgDggEFAAKCAQBEGmdP55PyE3M+Q3fU\n" + - "dCGq0sbKw/04xPVhaNYRnRKNR82n+wb8bMCI1vvFqXy1BB6svti4mTHbQZ8+bQXm\n" + - "gyce67uYMwIa5BIk6omNGCeW/kd4ruPgyFxeb6O/Y/7w6AWyRmQttlxRA5M5OhSC\n" + - "tVS4oVC1KK1EfHAUh7mu8S8GrWJoJAWA3PM97Oy/HSGCEUl6HGEu1m7FHPhOKeYG\n" + - "cLkSaov5cbCYO76smHchI+tdUciVqeL3YKQdS+KAzsQoeAZIu/WpbaI1V+5/rSG1\n" + - "I94uBITLCjlJfJZ1aredCDrRXOFH7qgSBhM8/WzwFpFCnnpbSKMgrcrKubsFmW9E\n" + - "jQhXo2MwYTALBgNVHQ8EBAMCA+gwHQYDVR0OBBYEFNA9PhQOjB+05fxxXPNqe0OT\n" + - "doCjMB8GA1UdIwQYMBaAFBlGEEMkaqUUvuKSAXnwTF/hroG1MBIGA1UdEQEB/wQI\n" + - "MAaHBH8AAAEwCwYJYIZIAWUDBAMCA0cAMEQCIE0LM2sZi+L8tjH9sgjLEwJmYZvO\n" + - "yqNfQnXrkTCb+MLMAiBZLaRTVJrOW3edQjum+SonKKuiN22bRclO6pGuNRCtng==\n" + - "-----END CERTIFICATE-----" - }; - - // Private key in the format of PKCS#8. - private final static String[] endEntityPrivateKeys = { - // - // EC private key related to cert endEntityCertStrs[0]. - // - "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGAy4Pxrd2keM7AdP\n" + - "VNUMEO5iO681v4/tstVGfdXkCTuhRANCAATjK9EZW/L2JUBPK4c8lV1fr6WH8Yub\n" + - "+xEnmotP/c9UU6g0i+URU2IBGjvGHKPanpud/faA2Dlh75ALDbRVS/0T", - - // - // RSA private key related to cert endEntityCertStrs[1]. - // - "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCnR0euJ9ODZpjS\n" + - "wfTd/YmMrZ9bgMvqAsMqrRiKuw0TTvPngsUh54OKjj1fA+MHs6ltRMLWF/9gpnte\n" + - "JFbI9rWtijNnzx6aFm35ymTIrP6eZbhq+UBaetX6DHj5tT1P5a4FZ0CtoFyrbtjU\n" + - "jbrJ8IS0LyTf47Sx2UduFqwX4FQOZf+fj6eJ8l1s2bl5IPHx4VgcVN2OEC53cCfZ\n" + - "fpAP1ZZKgmk90OLi60eEUCXFbqiyMnGwA+/OjxiyqakIyNlwSSzhmyqJkoqJZRZQ\n" + - "CMJxsx6sM8Nfb1/J6jfjy7O28myY1HN9zCUW3DGlh3G5mrAeLZCg1pBMZeONtkWa\n" + - "OfuoSSNfAgMBAAECggEAWnAHKPkPObN2XDvQj1RL0WrtBSOVG2dy7Ne4tQh8ATxm\n" + - "UXw56CKq03YjaANJ8xgHObQ7QlSnFTHs8PDkmrIHd1OIh09LVDNcMfhilLwyzKBi\n" + - "HDO1vzU6Cn5DyX1bMJ8UfodcSIKyl1zOjdwyaItIs8HpRcJuJtk57SME18PIrh9H\n" + - "EWchWSxTvPvKDY2bhb4vBMgVPfTQO3yc8gY/1J5vKPqDpyEuCGjV13zd/AoL/u5A\n" + - "sG10hQ2veJ9KAn1xwPwEoAkCdNLL8vPB1rCbeMZNamqHZRihfoOgDnnJIf3FtUFF\n" + - "8bS2FM2kGQR+05SZdhBmJl0obPrbBWil/2vxqeFrgQKBgQDZl1yQsFss2BKK2VAh\n" + - "9PKc8tU1v6RpHQZhJEDSct2slHQS5DF6bWl5kJiPevXSvcnjgoPamZf7Joii+Rds\n" + - "3xtPQmRw2vQmXBQzQS1YoRuh4hUlkdFWCjUNNg1kvipue6FO4PVg3ViP7llN8PXK\n" + - "rSpVxn0a36UiN9jN2zMOUs6tJwKBgQDEzlqa7DghMli7TUdL44uvD2/ceiHqHMMw\n" + - "5eLsEHeRVn/EVU99beKw/dAOGwRssTpCd9h7fwzQ2503/Qb/Goe0nKE7+xvt3/sE\n" + - "n2Y8Qfv1W1+hGb2qU2jhQaR5bZrLZp0+BgRuQ4ttpYvzopYe4FLZWhDBA0zsGyu0\n" + - "nCi7lUSrCQKBgGeGYW8hyS9r2l6fiEWvsiLEUnbRKFsuiRN82S6HojpzI0q9sWDL\n" + - "X6yMBFn3qa/LxpttRGikPTAsJERN+Tw+ZlLuhrU/J3x8wMumDfomJOx/kYofd5bV\n" + - "ImqXtgWhiLSqM5RA6d5dUb6hK3Iu2/LDMuo+ltVLZNkD8y32RbNh6J1vAoGAbLqQ\n" + - "pgyhSf3Vtc0Q+aVB87p0k3tKJ1wynl4zSzYhyMLgHakAHIzL8/qVqmVUwXP8euJZ\n" + - "UIk1nGHobxk0d1XB6Y+rKEcn+/iFZt1ljx7pQ3ly0L824NXqGKC6bHeYUI1li/Gp\n" + - "Gv3oFvCh7D1D8NUAEKLIpMndAohUUhkAC/qAkHkCgYEAzSIarDNquayV+umC1SXm\n" + - "Zo6XLuzWjudLxPd2lyCfwR2aRKlrb+5OFYErX+RSLyCJmaqVZMyXP09PBIvNXu2Z\n" + - "+gbx5WUC+kA+6zdKEPXowei6i6EHMXYT2AL7395ZbPajZjsCduE3WuUztuHrhtMm\n" + - "JI+k1o4rCnSLlX4gWdN1oTs=", - - // - // DSA private key related to cert endEntityCertStrs[2]. - // - "MIICZAIBADCCAjkGByqGSM44BAEwggIsAoIBAQCWte2WHSAob+cnmLjyt818YFBB\n" + - "hrHVAwM30FMbTK8grXN2jYFi8bDdf0GL6fb/oYeLcJxttFXpghB/UJcdOj8YO+A8\n" + - "EjgPN0nnDtsu3HYJqx6XqfXa8Sm11WWn8AYW00sIVfiAzuxDuvi2kb2bsmv2DqjS\n" + - "BPRDcRVZNDazbAweqXwxF2bAmQCzDdpnJfChp9au73cyUFBFexerixj99851X5kM\n" + - "liR92FtPVlQhVx7w82RxlwztjtkMCFNQeQLF5zhni5yoF8xKwqDSsFG1RT9FtDlX\n" + - "iaOKXGXy//E1RCxhvdALrh9VdxrKuj3cwgz8OFL/7+Zu/+pMF6gUMQCQO44TAiEA\n" + - "jkSBlZh8uZwS0YSD+Lwu77E8W+AkwKT1ZmXi+YEyMLUCggEAdlWS2NtpNviEDOnX\n" + - "kRity5e7TwoRqypxpk27VE4SM2u9EqfQ5kwYi8zBGPiIBvJGLk+Uk1cVo7NHMVwi\n" + - "mRjEFrYqDLYlzwNjNxwNP/BNJgy0ps29EQHdscZw8hrLqqNXlZsezy4zd259xI4Q\n" + - "//o93Scd2VUnDBsqu7FVqaVL6bnRF4vtnrX+hlB463F9u47qO7uM0NXswvx2BtR/\n" + - "oxBahoXUOm+x/iwR2R/S3oDsiGUzK8wGP08CK++7F6zSVkaMZgxKygfvG0Q8m2IT\n" + - "SbMJWZtDeWGFJT5nqYG5el88Ar9MtHfNYd22sqiDy1xFLUQJfRrjNITQJQNWPqkp\n" + - "/cSxWAQiAiAKHYbYwEy0XS9J0MeKQmqPswn0nCJKvH+esfMKkZvV3w==" - }; - - // Private key names of endEntityPrivateKeys. - private final static String[] endEntityPrivateKeyNames = { - "EC", - "RSA", - "DSA", - }; - - /* - * Create an instance of SSLContext with the specified trust/key materials. - */ - private SSLContext createSSLContext( - String[] trustedMaterials, - String[] keyMaterialCerts, - String[] keyMaterialKeys, - String[] keyMaterialKeyAlgs, - ContextParameters params) throws Exception { - - KeyStore ts = null; // trust store - KeyStore ks = null; // key store - char passphrase[] = "passphrase".toCharArray(); - - // Generate certificate from cert string. - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // Import the trused certs. - ByteArrayInputStream is; - if (trustedMaterials != null && trustedMaterials.length != 0) { - ts = KeyStore.getInstance("JKS"); - ts.load(null, null); - - Certificate[] trustedCert = - new Certificate[trustedMaterials.length]; - for (int i = 0; i < trustedMaterials.length; i++) { - String trustedCertStr = trustedMaterials[i]; - - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - try { - trustedCert[i] = cf.generateCertificate(is); - } finally { - is.close(); - } - - ts.setCertificateEntry("trusted-cert-" + i, trustedCert[i]); - } - } - - // Import the key materials. - // - // Note that certification pathes bigger than one are not supported yet. - boolean hasKeyMaterials = - (keyMaterialCerts != null) && (keyMaterialCerts.length != 0) && - (keyMaterialKeys != null) && (keyMaterialKeys.length != 0) && - (keyMaterialKeyAlgs != null) && (keyMaterialKeyAlgs.length != 0) && - (keyMaterialCerts.length == keyMaterialKeys.length) && - (keyMaterialCerts.length == keyMaterialKeyAlgs.length); - if (hasKeyMaterials) { - ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - for (int i = 0; i < keyMaterialCerts.length; i++) { - String keyCertStr = keyMaterialCerts[i]; - - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keyMaterialKeys[i])); - KeyFactory kf = - KeyFactory.getInstance(keyMaterialKeyAlgs[i]); - PrivateKey priKey = kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = null; - try { - keyCert = cf.generateCertificate(is); - } finally { - is.close(); - } - - Certificate[] chain = new Certificate[] { keyCert }; - - // import the key entry. - ks.setKeyEntry("cert-" + keyMaterialKeyAlgs[i], - priKey, passphrase, chain); - } - } - - // Create an SSLContext object. - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(params.tmAlgorithm); - tmf.init(ts); - - SSLContext context = SSLContext.getInstance(params.contextProtocol); - if (hasKeyMaterials && ks != null) { - KeyManagerFactory kmf = - KeyManagerFactory.getInstance(params.kmAlgorithm); - kmf.init(ks, passphrase); - - context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - } else { - context.init(null, tmf.getTrustManagers(), null); - } - - return context; - } - - /* - * ================================================= - * Stuffs to boot up the client-server mode testing. - */ - private Thread clientThread = null; - private Thread serverThread = null; - private volatile Exception serverException = null; - private volatile Exception clientException = null; - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private static final boolean separateServerThread = false; - - /* - * Boot up the testing, used to drive remainder of the test. - */ - private void bootup() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - private void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - logException("Server died", e); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - logException("Server failed", e); - serverException = e; - } - } - } - - private void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - logException("Client died", e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - logException("Client failed", e); - clientException = e; - } - } - } - - private synchronized void logException(String prefix, Throwable cause) { - System.out.println(prefix + ": " + cause); - cause.printStackTrace(System.out); - } -}
--- a/test/sun/net/www/protocol/https/HttpsClient/OriginServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * - * This is a HTTP test server used by the regression test - * for the bug fixes: 4323990, 4413069 - */ - -import java.io.*; -import java.net.*; -import javax.net.*; - -/* - * OriginServer.java -- a simple server that can serve - * Http get request in both clear and secure channel - */ - -public abstract class OriginServer implements Runnable, Closeable { - - private ServerSocket server = null; - Exception serverException = null; - private volatile boolean closed; - - /** - * Constructs a OriginServer based on ss and - * obtains a response data's bytecodes using the method - * getBytes. - */ - protected OriginServer(ServerSocket ss) throws Exception - { - server = ss; - newListener(); - if (serverException != null) - throw serverException; - } - - @Override - public void close() throws IOException { - if (closed) - return; - closed = true; - server.close(); - } - - /** - * Returns an array of bytes containing the bytes for - * the data sent in the response. - * - * @return the bytes for the information that is being sent - */ - public abstract byte[] getBytes(); - - /** - * The "listen" thread that accepts a connection to the - * server, parses the header and sends back the response - */ - public void run() - { - Socket socket; - - // accept a connection - try { - socket = server.accept(); - } catch (IOException e) { - System.out.println("Class Server died: " + e.getMessage()); - serverException = e; - return; - } - try { - DataOutputStream out = - new DataOutputStream(socket.getOutputStream()); - try { - BufferedReader in = - new BufferedReader(new InputStreamReader( - socket.getInputStream())); - // read the request - readRequest(in); - // retrieve bytecodes - byte[] bytecodes = getBytes(); - // send bytecodes in response (assumes HTTP/1.0 or later) - try { - out.writeBytes("HTTP/1.0 200 OK\r\n"); - out.writeBytes("Content-Length: " + bytecodes.length + - "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.write(bytecodes); - out.flush(); - } catch (IOException ie) { - serverException = ie; - return; - } - - } catch (Exception e) { - // write out error response - out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.flush(); - } - - } catch (IOException ex) { - System.out.println("error writing response: " + ex.getMessage()); - serverException = ex; - - } finally { - try { - socket.close(); - } catch (IOException e) { - serverException = e; - } - } - } - - /** - * Create a new thread to listen. - */ - private void newListener() - { - (new Thread(this)).start(); - } - - /** - * read the response, don't care for the syntax of the request-line - * for this testing - */ - private static void readRequest(BufferedReader in) - throws IOException - { - String line = null; - System.out.println("Server received: "); - do { - if (line != null) - System.out.println(line); - line = in.readLine(); - } while ((line.length() != 0) && - (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); - } -}
--- a/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4323990 4413069 8160838 - * @summary HttpsURLConnection doesn't send Proxy-Authorization on CONNECT - * Incorrect checking of proxy server response - * @run main/othervm ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=Basic ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=Basic, ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=BAsIc ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=Basic,Digest ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=Unknown,bAsIc ProxyAuthTest fail - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes= ProxyAuthTest succeed - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=Digest,NTLM,Negotiate ProxyAuthTest succeed - * @run main/othervm -Djdk.http.auth.tunneling.disabledSchemes=UNKNOWN,notKnown ProxyAuthTest succeed - */ - -// No way to reserve and restore java.lang.Authenticator, as well as read-once -// system properties, so this tests needs to run in othervm mode. - -import java.io.*; -import java.net.*; -import java.security.KeyStore; -import javax.net.*; -import javax.net.ssl.*; -import java.security.cert.*; -import static java.nio.charset.StandardCharsets.US_ASCII; - -/* - * ProxyAuthTest.java -- includes a simple server that can serve - * Http get request in both clear and secure channel, and a client - * that makes https requests behind the firewall through an - * authentication proxy - */ - -public class ProxyAuthTest { - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - volatile private static int serverPort = 0; - - /* - * The TestServer implements a OriginServer that - * processes HTTP requests and responses. - */ - static class TestServer extends OriginServer { - public TestServer(ServerSocket ss) throws Exception { - super(ss); - } - - /* - * Returns an array of bytes containing the bytes for - * the data sent in the response. - * - * @return bytes for the data in the response - */ - public byte[] getBytes() { - return "Proxy authentication for tunneling succeeded ..". - getBytes(US_ASCII); - } - } - - /* - * Main method to create the server and the client - */ - public static void main(String args[]) throws Exception { - boolean expectSuccess; - if (args[0].equals("succeed")) { - expectSuccess = true; - } else { - expectSuccess = false; - } - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - boolean useSSL = true; - /* - * setup the server - */ - Closeable server; - try { - ServerSocketFactory ssf = - ProxyAuthTest.getServerSocketFactory(useSSL); - ServerSocket ss = ssf.createServerSocket(serverPort); - serverPort = ss.getLocalPort(); - server = new TestServer(ss); - } catch (Exception e) { - System.out.println("Server side failed:" + - e.getMessage()); - throw e; - } - // trigger the client - try { - doClientSide(); - if (!expectSuccess) { - throw new RuntimeException( - "Expected exception/failure to connect, but succeeded."); - } - } catch (IOException e) { - if (expectSuccess) { - System.out.println("Client side failed: " + e.getMessage()); - throw e; - } - - if (! (e.getMessage().contains("Unable to tunnel through proxy") && - e.getMessage().contains("407")) ) { - throw new RuntimeException( - "Expected exception about cannot tunnel, 407, etc, but got", e); - } else { - // Informative - System.out.println("Caught expected exception: " + e.getMessage()); - } - } finally { - if (server != null) - server.close(); - } - } - - private static ServerSocketFactory getServerSocketFactory - (boolean useSSL) throws Exception { - if (useSSL) { - SSLServerSocketFactory ssf = null; - // set up key manager to do server authentication - SSLContext ctx; - KeyManagerFactory kmf; - KeyStore ks; - char[] passphrase = passwd.toCharArray(); - - ctx = SSLContext.getInstance("TLS"); - kmf = KeyManagerFactory.getInstance("SunX509"); - ks = KeyStore.getInstance("JKS"); - - ks.load(new FileInputStream(System.getProperty( - "javax.net.ssl.keyStore")), passphrase); - kmf.init(ks, passphrase); - ctx.init(kmf.getKeyManagers(), null, null); - - ssf = ctx.getServerSocketFactory(); - return ssf; - } else { - return ServerSocketFactory.getDefault(); - } - } - - static void doClientSide() throws IOException { - /* - * setup up a proxy with authentication information - */ - ProxyTunnelServer ps = setupProxy(); - - /* - * we want to avoid URLspoofCheck failures in cases where the cert - * DN name does not match the hostname in the URL. - */ - HttpsURLConnection.setDefaultHostnameVerifier( - new NameVerifier()); - - InetSocketAddress paddr = new InetSocketAddress("localhost", ps.getPort()); - Proxy proxy = new Proxy(Proxy.Type.HTTP, paddr); - - URL url = new URL("https://" + "localhost:" + serverPort - + "/index.html"); - BufferedReader in = null; - HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(proxy); - try { - in = new BufferedReader(new InputStreamReader(uc.getInputStream())); - String inputLine; - System.out.print("Client recieved from the server: "); - while ((inputLine = in.readLine()) != null) - System.out.println(inputLine); - in.close(); - } catch (IOException e) { - // Assert that the error stream is not accessible from the failed - // tunnel setup. - if (uc.getErrorStream() != null) { - throw new RuntimeException("Unexpected error stream."); - } - - if (in != null) - in.close(); - throw e; - } - } - - static class NameVerifier implements HostnameVerifier { - public boolean verify(String hostname, SSLSession session) { - return true; - } - } - - static ProxyTunnelServer setupProxy() throws IOException { - ProxyTunnelServer pserver = new ProxyTunnelServer(); - /* - * register a system wide authenticator and setup the proxy for - * authentication - */ - Authenticator.setDefault(new TestAuthenticator()); - - // register with the username and password - pserver.needUserAuth(true); - pserver.setUserAuth("Test", "test123"); - - pserver.start(); - return pserver; - } - - public static class TestAuthenticator extends Authenticator { - - public PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("Test", - "test123".toCharArray()); - } - } -} -
--- a/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4328195 - * @summary Need to include the alternate subject DN for certs, - * https should check for this - * @run main/othervm ServerIdentityTest - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * - * @author Yingxian Wang - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.security.KeyStore; - -public class ServerIdentityTest { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "./"; - static String[] keyStoreFiles = {"dnsstore", "ipstore"}; - static String[] trustStoreFiles = {"dnsstore", "ipstore"}; - static String passwd = "changeit"; - - /* - * Is the server ready to serve? - */ - boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - OutputStream sslOS = sslSocket.getOutputStream(); - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sslOS)); - bw.write("HTTP/1.1 200 OK\r\n\r\n\r\n"); - bw.flush(); - Thread.sleep(2000); - sslSocket.getSession().invalidate(); - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - String host = iphost? "127.0.0.1": "localhost"; - URL url = new URL("https://"+host+":"+serverPort+"/index.html"); - - HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); - InputStream is = urlc.getInputStream(); - is.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - SSLSocketFactory reservedSFactory = - HttpsURLConnection.getDefaultSSLSocketFactory(); - try { - for (int i = 0; i < keyStoreFiles.length; i++) { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFiles[i]; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFiles[i]; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - SSLContext context = SSLContext.getInstance("SSL"); - - KeyManager[] kms = new KeyManager[1]; - KeyStore ks = KeyStore.getInstance("JKS"); - FileInputStream fis = new FileInputStream(keyFilename); - ks.load(fis, passwd.toCharArray()); - fis.close(); - KeyManager km = new MyKeyManager(ks, passwd.toCharArray()); - kms[0] = km; - context.init(kms, null, null); - HttpsURLConnection.setDefaultSSLSocketFactory( - context.getSocketFactory()); - - /* - * Start the tests. - */ - System.out.println("Testing " + keyFilename); - new ServerIdentityTest(context, keyStoreFiles[i]); - } - } finally { - HttpsURLConnection.setDefaultSSLSocketFactory(reservedSFactory); - } - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLContext context; - boolean iphost = false; - ServerIdentityTest(SSLContext context, String keystore) - throws Exception { - this.context = context; - iphost = keystore.equals("ipstore"); - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - e.printStackTrace(); - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/B6216082.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 6216082 - * @library ../ - * @build HttpCallback TestHttpsServer ClosedChannelList HttpTransaction TunnelProxy - * @summary Redirect problem with HttpsURLConnection using a proxy - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @run main/othervm B6216082 - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.util.*; - -public class B6216082 { - static SimpleHttpTransaction httpTrans; - static TestHttpsServer server; - static TunnelProxy proxy; - - // it seems there's no proxy ever if a url points to 'localhost', - // even if proxy related properties are set. so we need to bind - // our simple http proxy and http server to a non-loopback address - static InetAddress firstNonLoAddress = null; - - public static void main(String[] args) throws Exception { - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - // XXX workaround for CNFE - Class.forName("java.nio.channels.ClosedByInterruptException"); - if (!setupEnv()) { - return; - } - - startHttpServer(); - - // https.proxyPort can only be set after the TunnelProxy has been - // created as it will use an ephemeral port. - System.setProperty("https.proxyPort", - (new Integer(proxy.getLocalPort())).toString() ); - - makeHttpCall(); - - if (httpTrans.hasBadRequest) { - throw new RuntimeException("Test failed : bad http request"); - } - } finally { - if (proxy != null) { - proxy.terminate(); - } - if (server != null) { - server.terminate(); - } - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } - - /* - * Where do we find the keystores for ssl? - */ - static String pathToStores = "../../../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - public static boolean setupEnv() throws Exception { - firstNonLoAddress = getNonLoAddress(); - if (firstNonLoAddress == null) { - System.err.println("The test needs at least one non-loopback address to run. Quit now."); - return false; - } - System.out.println(firstNonLoAddress.getHostAddress()); - // will use proxy - System.setProperty( "https.proxyHost", firstNonLoAddress.getHostAddress()); - - // setup properties to do ssl - String keyFilename = System.getProperty("test.src", "./") + "/" + - pathToStores + "/" + keyStoreFile; - String trustFilename = System.getProperty("test.src", "./") + "/" + - pathToStores + "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier()); - return true; - } - - public static InetAddress getNonLoAddress() throws Exception { - NetworkInterface loNIC = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost")); - Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); - while (nics.hasMoreElements()) { - NetworkInterface nic = nics.nextElement(); - if (!nic.getName().equalsIgnoreCase(loNIC.getName())) { - Enumeration<InetAddress> addrs = nic.getInetAddresses(); - while (addrs.hasMoreElements()) { - InetAddress addr = addrs.nextElement(); - if (!addr.isLoopbackAddress()) - return addr; - } - } - } - - return null; - } - - public static void startHttpServer() throws IOException { - // Both the https server and the proxy let the - // system pick up an ephemeral port. - httpTrans = new SimpleHttpTransaction(); - server = new TestHttpsServer(httpTrans, 1, 10, 0); - proxy = new TunnelProxy(1, 10, 0); - } - - public static void makeHttpCall() throws Exception { - System.out.println("https server listen on: " + server.getLocalPort()); - System.out.println("https proxy listen on: " + proxy.getLocalPort()); - URL url = new URL("https" , firstNonLoAddress.getHostAddress(), - server.getLocalPort(), "/"); - HttpURLConnection uc = (HttpURLConnection)url.openConnection(); - System.out.println(uc.getResponseCode()); - uc.disconnect(); - } - - static class NameVerifier implements HostnameVerifier { - public boolean verify(String hostname, SSLSession session) { - return true; - } - } -} - -class SimpleHttpTransaction implements HttpCallback { - public boolean hasBadRequest = false; - - /* - * Our http server which simply redirect first call - */ - public void request(HttpTransaction trans) { - try { - String path = trans.getRequestURI().getPath(); - if (path.equals("/")) { - // the first call, redirect it - String location = "/redirect"; - trans.addResponseHeader("Location", location); - trans.sendResponse(302, "Moved Temporarily"); - } else { - // if the bug exsits, it'll send 2 GET commands - // check 2nd GET here - String duplicatedGet = trans.getRequestHeader(null); - if (duplicatedGet != null && - duplicatedGet.toUpperCase().indexOf("GET") >= 0) { - trans.sendResponse(400, "Bad Request"); - hasBadRequest = true; - } else { - trans.sendResponse(200, "OK"); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } -}
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/DNSIdentities.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/net/www/protocol/https/HttpsURLConnection/DNSIdentities.java Tue Aug 25 18:03:27 2020 +0300 @@ -46,8 +46,6 @@ import java.security.interfaces.*; import java.math.BigInteger; -import sun.security.ssl.SSLSocketImpl; - /* * Certificates and key used in the test. *
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressDNSIdentities.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressDNSIdentities.java Tue Aug 25 18:03:27 2020 +0300 @@ -43,8 +43,6 @@ import java.security.interfaces.*; import java.math.BigInteger; -import sun.security.ssl.SSLSocketImpl; - /* * Certificates and key used in the test. *
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressIPIdentities.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/net/www/protocol/https/HttpsURLConnection/IPAddressIPIdentities.java Tue Aug 25 18:03:27 2020 +0300 @@ -46,8 +46,6 @@ import java.security.interfaces.*; import java.math.BigInteger; -import sun.security.ssl.SSLSocketImpl; - /* * Certificates and key used in the test. *
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/IPIdentities.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/net/www/protocol/https/HttpsURLConnection/IPIdentities.java Tue Aug 25 18:03:27 2020 +0300 @@ -46,8 +46,6 @@ import java.security.interfaces.*; import java.math.BigInteger; -import sun.security.ssl.SSLSocketImpl; - /* * Certificates and key used in the test. *
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/Identities.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/net/www/protocol/https/HttpsURLConnection/Identities.java Tue Aug 25 18:03:27 2020 +0300 @@ -46,8 +46,6 @@ import java.security.interfaces.*; import java.math.BigInteger; -import sun.security.ssl.SSLSocketImpl; - /* * Certificates and key used in the test. *
--- a/test/sun/net/www/protocol/https/HttpsURLConnection/ReadTimeout.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,318 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4811482 4700777 4905410 - * @summary sun.net.client.defaultConnectTimeout should work with - * HttpsURLConnection; HTTP client: Connect and read timeouts; - * Https needs to support new tiger features that went into http - * @run main/othervm ReadTimeout - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class ReadTimeout { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Message posted - */ - static String postMsg = "Testing HTTP post on a https server"; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - SSLSocket sslSocket = null; - try { - sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(sslIS)); - br.readLine(); - while (!finished()) { - Thread.sleep (2000); - } - sslSocket.close(); - - reset(); - // doing second test - sslSocket = (SSLSocket) sslServerSocket.accept(); - sslIS = sslSocket.getInputStream(); - br = new BufferedReader(new InputStreamReader(sslIS)); - br.readLine(); - while (!finished()) { - Thread.sleep (2000); - } - sslSocket.close(); - } catch (Exception e) { - } finally { - if (sslServerSocket != null) - sslServerSocket.close(); - } - } - - boolean isFinished = false; - - synchronized boolean finished () { - return (isFinished); - } - synchronized void done () { - isFinished = true; - } - - synchronized void reset() { - isFinished = false; - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - HttpsURLConnection http = null; - try { - URL url = new URL("https://localhost:"+serverPort); - - // set read timeout through system property - System.setProperty("sun.net.client.defaultReadTimeout", "2000"); - HttpsURLConnection.setDefaultHostnameVerifier( - new NameVerifier()); - http = (HttpsURLConnection)url.openConnection(); - - InputStream is = http.getInputStream (); - } catch (SocketTimeoutException stex) { - done(); - http.disconnect(); - } - - try { - URL url = new URL("https://localhost:"+serverPort); - - HttpsURLConnection.setDefaultHostnameVerifier( - new NameVerifier()); - http = (HttpsURLConnection)url.openConnection(); - // set read timeout through API - http.setReadTimeout(2000); - - InputStream is = http.getInputStream (); - } catch (SocketTimeoutException stex) { - done(); - http.disconnect(); - } - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } - - static class NameVerifier implements HostnameVerifier { - public boolean verify(String hostname, SSLSession session) { - return true; - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ReadTimeout(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ReadTimeout() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,381 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4474255 - * @summary Can no longer obtain a com.sun.net.ssl.HttpsURLConnection - * @run main/othervm ComHTTPSConnection - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import javax.security.cert.*; -import com.sun.net.ssl.HostnameVerifier; -import com.sun.net.ssl.HttpsURLConnection; - -/** - * See if we can obtain a com.sun.net.ssl.HttpsURLConnection, - * and then play with it a bit. - */ -public class ComHTTPSConnection { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /** - * Returns the path to the file obtained from - * parsing the HTML header. - */ - private static String getPath(DataInputStream in) - throws IOException - { - String line = in.readLine(); - String path = ""; - // extract class from GET line - if (line.startsWith("GET /")) { - line = line.substring(5, line.length()-1).trim(); - int index = line.indexOf(' '); - if (index != -1) { - path = line.substring(0, index); - } - } - - // eat the rest of header - do { - line = in.readLine(); - } while ((line.length() != 0) && - (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); - - if (path.length() != 0) { - return path; - } else { - throw new IOException("Malformed Header"); - } - } - - /** - * Returns an array of bytes containing the bytes for - * the file represented by the argument <b>path</b>. - * - * In our case, we just pretend to send something back. - * - * @return the bytes for the file - * @exception FileNotFoundException if the file corresponding - * to <b>path</b> could not be loaded. - */ - private byte[] getBytes(String path) - throws IOException - { - return "Hello world, I am here".getBytes(); - } - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - DataOutputStream out = - new DataOutputStream(sslSocket.getOutputStream()); - - try { - // get path to class file from header - DataInputStream in = - new DataInputStream(sslSocket.getInputStream()); - String path = getPath(in); - // retrieve bytecodes - byte[] bytecodes = getBytes(path); - // send bytecodes in response (assumes HTTP/1.0 or later) - try { - out.writeBytes("HTTP/1.0 200 OK\r\n"); - out.writeBytes("Content-Length: " + bytecodes.length + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.write(bytecodes); - out.flush(); - } catch (IOException ie) { - ie.printStackTrace(); - return; - } - - } catch (Exception e) { - e.printStackTrace(); - // write out error response - out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.flush(); - } finally { - // close the socket - System.out.println("Server closing socket"); - sslSocket.close(); - serverReady = false; - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - HostnameVerifier reservedHV = - HttpsURLConnection.getDefaultHostnameVerifier(); - try { - System.setProperty("java.protocol.handler.pkgs", - "com.sun.net.ssl.internal.www.protocol"); - HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier()); - - URL url = new URL("https://" + "localhost:" + serverPort + - "/etc/hosts"); - URLConnection urlc = url.openConnection(); - - if (!(urlc instanceof com.sun.net.ssl.HttpsURLConnection)) { - throw new Exception( - "URLConnection ! instanceof " + - "com.sun.net.ssl.HttpsURLConnection"); - } - - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - urlc.getInputStream())); - String inputLine; - System.out.print("Client reading... "); - while ((inputLine = in.readLine()) != null) - System.out.println(inputLine); - - System.out.println("Cipher Suite: " + - ((HttpsURLConnection)urlc).getCipherSuite()); - X509Certificate[] certs = - ((HttpsURLConnection)urlc).getServerCertificateChain(); - for (int i = 0; i < certs.length; i++) { - System.out.println(certs[0]); - } - - in.close(); - } catch (SSLException e) { - if (in != null) - in.close(); - throw e; - } - System.out.println("Client reports: SUCCESS"); - } finally { - HttpsURLConnection.setDefaultHostnameVerifier(reservedHV); - } - } - - static class NameVerifier implements HostnameVerifier { - public boolean verify(String urlHostname, - String certHostname) { - System.out.println( - "CertificateHostnameVerifier: " + urlHostname + " == " - + certHostname + " returning true"); - return true; - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ComHTTPSConnection(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ComHTTPSConnection() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/net/www/protocol/https/NewImpl/ComHostnameVerifier.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,350 +0,0 @@ -/* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 4474255 4484246 - * @summary When an application enables anonymous SSL cipher suite, - * Hostname verification is not required - * @run main/othervm ComHostnameVerifier - */ - -import java.io.*; -import java.net.*; -import java.security.Security; -import javax.net.ssl.*; -import javax.security.cert.*; -import com.sun.net.ssl.HostnameVerifier; -import com.sun.net.ssl.HttpsURLConnection; - -/** - * Use com.net.net.ssl.HostnameVerifier - */ -public class ComHostnameVerifier { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /** - * Returns the path to the file obtained from - * parsing the HTML header. - */ - private static String getPath(DataInputStream in) - throws IOException - { - String line = in.readLine(); - if (line == null) - return null; - String path = ""; - // extract class from GET line - if (line.startsWith("GET /")) { - line = line.substring(5, line.length()-1).trim(); - int index = line.indexOf(' '); - if (index != -1) { - path = line.substring(0, index); - } - } - - // eat the rest of header - do { - line = in.readLine(); - } while ((line.length() != 0) && - (line.charAt(0) != '\r') && (line.charAt(0) != '\n')); - - if (path.length() != 0) { - return path; - } else { - throw new IOException("Malformed Header"); - } - } - - /** - * Returns an array of bytes containing the bytes for - * the file represented by the argument <b>path</b>. - * - * In our case, we just pretend to send something back. - * - * @return the bytes for the file - * @exception FileNotFoundException if the file corresponding - * to <b>path</b> could not be loaded. - */ - private byte[] getBytes(String path) - throws IOException - { - return "Hello world, I am here".getBytes(); - } - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - String ciphers[]= { "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" }; - sslServerSocket.setEnabledCipherSuites(ciphers); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - DataOutputStream out = - new DataOutputStream(sslSocket.getOutputStream()); - - try { - // get path to class file from header - DataInputStream in = - new DataInputStream(sslSocket.getInputStream()); - String path = getPath(in); - // retrieve bytecodes - byte[] bytecodes = getBytes(path); - // send bytecodes in response (assumes HTTP/1.0 or later) - try { - out.writeBytes("HTTP/1.0 200 OK\r\n"); - out.writeBytes("Content-Length: " + bytecodes.length + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.write(bytecodes); - out.flush(); - } catch (IOException ie) { - ie.printStackTrace(); - return; - } - - } catch (Exception e) { - e.printStackTrace(); - // write out error response - out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n"); - out.writeBytes("Content-Type: text/html\r\n\r\n"); - out.flush(); - } finally { - // close the socket - System.out.println("Server closing socket"); - sslSocket.close(); - serverReady = false; - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - System.setProperty("java.protocol.handler.pkgs", - "com.sun.net.ssl.internal.www.protocol"); - - System.setProperty("https.cipherSuites", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"); - - // use the default hostname verifier - - URL url = new URL("https://" + "localhost:" + serverPort + - "/etc/hosts"); - URLConnection urlc = url.openConnection(); - - if (!(urlc instanceof com.sun.net.ssl.HttpsURLConnection)) { - throw new Exception( - "URLConnection ! instanceof " + - "com.sun.net.ssl.HttpsURLConnection"); - } - - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - urlc.getInputStream())); - String inputLine; - System.out.print("Client reading... "); - while ((inputLine = in.readLine()) != null) - System.out.println(inputLine); - System.out.println("Cipher Suite: " + - ((HttpsURLConnection)urlc).getCipherSuite()); - in.close(); - } catch (SSLException e) { - if (in != null) - in.close(); - throw e; - } - System.out.println("Client reports: SUCCESS"); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // re-enable 3DES - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ComHostnameVerifier(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ComHostnameVerifier() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/pkcs11/sslecc/CipherTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,586 +0,0 @@ -/* - * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.concurrent.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -/** - * Test that all ciphersuites work in all versions and all client - * authentication types. The way this is setup the server is stateless and - * all checking is done on the client side. - * - * The test is multithreaded to speed it up, especially on multiprocessor - * machines. To simplify debugging, run with -DnumThreads=1. - * - * @author Andreas Sterbenz - */ -public class CipherTest { - - // use any available port for the server socket - static volatile int serverPort = 0; - - final int THREADS; - - // assume that if we do not read anything for 20 seconds, something - // has gone wrong - final static int TIMEOUT = 20 * 1000; - - static KeyStore trustStore, keyStore; - static X509ExtendedKeyManager keyManager; - static X509TrustManager trustManager; - static SecureRandom secureRandom; - - private static PeerFactory peerFactory; - - static abstract class Server implements Runnable { - - final CipherTest cipherTest; - - Server(CipherTest cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - public abstract void run(); - - void handleRequest(InputStream in, OutputStream out) throws IOException { - boolean newline = false; - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - throw new EOFException(); - } - sb.append((char)ch); - if (ch == '\r') { - // empty - } else if (ch == '\n') { - if (newline) { - // 2nd newline in a row, end of request - break; - } - newline = true; - } else { - newline = false; - } - } - String request = sb.toString(); - if (request.startsWith("GET / HTTP/1.") == false) { - throw new IOException("Invalid request: " + request); - } - out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes()); - } - - } - - public static class TestParameters { - - String cipherSuite; - String protocol; - String clientAuth; - - TestParameters(String cipherSuite, String protocol, - String clientAuth) { - this.cipherSuite = cipherSuite; - this.protocol = protocol; - this.clientAuth = clientAuth; - } - - boolean isEnabled() { - return TLSCipherStatus.isEnabled(cipherSuite, protocol); - } - - public String toString() { - String s = cipherSuite + " in " + protocol + " mode"; - if (clientAuth != null) { - s += " with " + clientAuth + " client authentication"; - } - return s; - } - - static enum TLSCipherStatus { - // cipher suites supported since TLS 1.2 - CS_01("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_02("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_03("TLS_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_04("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_05("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF), - CS_06("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_07("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - - CS_08("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_09("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_10("TLS_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_11("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_12("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_13("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_14("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - - CS_15("TLS_DH_anon_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF), - CS_16("TLS_DH_anon_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF), - CS_17("TLS_RSA_WITH_NULL_SHA256", 0x0303, 0xFFFF), - - CS_20("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_21("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_22("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_23("TLS_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_24("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_25("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_26("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_27("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - - CS_28("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_29("TLS_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_30("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_31("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_32("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - CS_33("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - - CS_34("TLS_DH_anon_WITH_AES_256_GCM_SHA384", 0x0303, 0xFFFF), - CS_35("TLS_DH_anon_WITH_AES_128_GCM_SHA256", 0x0303, 0xFFFF), - - // cipher suites obsoleted since TLS 1.2 - CS_50("SSL_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_51("SSL_DHE_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_52("SSL_DHE_DSS_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_53("SSL_DH_anon_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_54("TLS_KRB5_WITH_DES_CBC_SHA", 0x0000, 0x0303), - CS_55("TLS_KRB5_WITH_DES_CBC_MD5", 0x0000, 0x0303), - - // cipher suites obsoleted since TLS 1.1 - CS_60("SSL_RSA_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_61("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_62("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_63("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_64("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_65("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302), - CS_66("TLS_KRB5_EXPORT_WITH_RC4_40_SHA", 0x0000, 0x0302), - CS_67("TLS_KRB5_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302), - CS_68("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", 0x0000, 0x0302), - CS_69("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", 0x0000, 0x0302), - - // ignore TLS_EMPTY_RENEGOTIATION_INFO_SCSV always - CS_99("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", 0xFFFF, 0x0000); - - // the cipher suite name - final String cipherSuite; - - // supported since protocol version - final int supportedSince; - - // obsoleted since protocol version - final int obsoletedSince; - - TLSCipherStatus(String cipherSuite, - int supportedSince, int obsoletedSince) { - this.cipherSuite = cipherSuite; - this.supportedSince = supportedSince; - this.obsoletedSince = obsoletedSince; - } - - static boolean isEnabled(String cipherSuite, String protocol) { - int versionNumber = toVersionNumber(protocol); - - if (versionNumber < 0) { - return true; // unlikely to happen - } - - for (TLSCipherStatus status : TLSCipherStatus.values()) { - if (cipherSuite.equals(status.cipherSuite)) { - if ((versionNumber < status.supportedSince) || - (versionNumber >= status.obsoletedSince)) { - return false; - } - - return true; - } - } - - return true; - } - - private static int toVersionNumber(String protocol) { - int versionNumber = -1; - - switch (protocol) { - case "SSLv2Hello": - versionNumber = 0x0002; - break; - case "SSLv3": - versionNumber = 0x0300; - break; - case "TLSv1": - versionNumber = 0x0301; - break; - case "TLSv1.1": - versionNumber = 0x0302; - break; - case "TLSv1.2": - versionNumber = 0x0303; - break; - default: - // unlikely to happen - } - - return versionNumber; - } - } - } - - private List<TestParameters> tests; - private Iterator<TestParameters> testIterator; - private SSLSocketFactory factory; - private boolean failed; - - private CipherTest(PeerFactory peerFactory) throws IOException { - THREADS = Integer.parseInt(System.getProperty("numThreads", "4")); - factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); - SSLSocket socket = (SSLSocket)factory.createSocket(); - String[] cipherSuites = socket.getSupportedCipherSuites(); - String[] protocols = socket.getSupportedProtocols(); - String[] clientAuths = {null, "RSA", "DSA", "ECDSA"}; - tests = new ArrayList<TestParameters>( - cipherSuites.length * protocols.length * clientAuths.length); - for (int i = 0; i < cipherSuites.length; i++) { - String cipherSuite = cipherSuites[i]; - - for (int j = 0; j < protocols.length; j++) { - String protocol = protocols[j]; - - if (!peerFactory.isSupported(cipherSuite, protocol)) { - continue; - } - - for (int k = 0; k < clientAuths.length; k++) { - String clientAuth = clientAuths[k]; - if ((clientAuth != null) && - (cipherSuite.indexOf("DH_anon") != -1)) { - // no client with anonymous ciphersuites - continue; - } - - tests.add(new TestParameters(cipherSuite, protocol, - clientAuth)); - } - } - } - - testIterator = tests.iterator(); - } - - synchronized void setFailed() { - failed = true; - } - - public void run() throws Exception { - Thread[] threads = new Thread[THREADS]; - for (int i = 0; i < THREADS; i++) { - try { - threads[i] = new Thread(peerFactory.newClient(this), - "Client " + i); - } catch (Exception e) { - e.printStackTrace(); - return; - } - threads[i].start(); - } - try { - for (int i = 0; i < THREADS; i++) { - threads[i].join(); - } - } catch (InterruptedException e) { - setFailed(); - e.printStackTrace(); - } - if (failed) { - throw new Exception("*** Test '" + peerFactory.getName() + - "' failed ***"); - } else { - System.out.println("Test '" + peerFactory.getName() + - "' completed successfully"); - } - } - - synchronized TestParameters getTest() { - if (failed) { - return null; - } - if (testIterator.hasNext()) { - return (TestParameters)testIterator.next(); - } - return null; - } - - SSLSocketFactory getFactory() { - return factory; - } - - static abstract class Client implements Runnable { - - final CipherTest cipherTest; - - Client(CipherTest cipherTest) throws Exception { - this.cipherTest = cipherTest; - } - - public final void run() { - while (true) { - TestParameters params = cipherTest.getTest(); - if (params == null) { - // no more tests - break; - } - if (params.isEnabled() == false) { - System.out.println("Skipping disabled test " + params); - continue; - } - try { - runTest(params); - System.out.println("Passed " + params); - } catch (Exception e) { - cipherTest.setFailed(); - System.out.println("** Failed " + params + "**"); - e.printStackTrace(); - } - } - } - - abstract void runTest(TestParameters params) throws Exception; - - void sendRequest(InputStream in, OutputStream out) throws IOException { - out.write("GET / HTTP/1.0\r\n\r\n".getBytes()); - out.flush(); - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = in.read(); - if (ch < 0) { - break; - } - sb.append((char)ch); - } - String response = sb.toString(); - if (response.startsWith("HTTP/1.0 200 ") == false) { - throw new IOException("Invalid response: " + response); - } - } - - } - - // for some reason, ${test.src} has a different value when the - // test is called from the script and when it is called directly... - static String pathToStores = "."; - static String pathToStoresSH = "."; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static char[] passwd = "passphrase".toCharArray(); - - static File PATH; - - private static KeyStore readKeyStore(String name) throws Exception { - File file = new File(PATH, name); - InputStream in = new FileInputStream(file); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(in, passwd); - in.close(); - return ks; - } - - public static void main(PeerFactory peerFactory, String[] args) - throws Exception { - long time = System.currentTimeMillis(); - String relPath; - if ((args != null) && (args.length > 0) && args[0].equals("sh")) { - relPath = pathToStoresSH; - } else { - relPath = pathToStores; - } - PATH = new File(System.getProperty("test.src", "."), relPath); - CipherTest.peerFactory = peerFactory; - System.out.print( - "Initializing test '" + peerFactory.getName() + "'..."); - secureRandom = new SecureRandom(); - secureRandom.nextInt(); - trustStore = readKeyStore(trustStoreFile); - keyStore = readKeyStore(keyStoreFile); - KeyManagerFactory keyFactory = - KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - keyFactory.init(keyStore, passwd); - keyManager = (X509ExtendedKeyManager)keyFactory.getKeyManagers()[0]; - trustManager = new AlwaysTrustManager(); - - CipherTest cipherTest = new CipherTest(peerFactory); - Thread serverThread = new Thread(peerFactory.newServer(cipherTest), - "Server"); - serverThread.setDaemon(true); - serverThread.start(); - System.out.println("Done"); - cipherTest.run(); - time = System.currentTimeMillis() - time; - System.out.println("Done. (" + time + " ms)"); - } - - static abstract class PeerFactory { - - abstract String getName(); - - abstract Client newClient(CipherTest cipherTest) throws Exception; - - abstract Server newServer(CipherTest cipherTest) throws Exception; - - boolean isSupported(String cipherSuite, String protocol) { - // skip kerberos cipher suites - if (cipherSuite.startsWith("TLS_KRB5")) { - System.out.println("Skipping unsupported test for " + - cipherSuite + " of " + protocol); - return false; - } - - // skip SSLv2Hello protocol - if (protocol.equals("SSLv2Hello")) { - System.out.println("Skipping unsupported test for " + - cipherSuite + " of " + protocol); - return false; - } - - // ignore exportable cipher suite for TLSv1.1 - if (protocol.equals("TLSv1.1")) { - if (cipherSuite.indexOf("_EXPORT_WITH") != -1) { - System.out.println("Skipping obsoleted test for " + - cipherSuite + " of " + protocol); - return false; - } - } - - return true; - } - } - -} - -// we currently don't do any chain verification. we assume that works ok -// and we can speed up the test. we could also just add a plain certificate -// chain comparision with our trusted certificates. -class AlwaysTrustManager implements X509TrustManager { - - public AlwaysTrustManager() { - - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - // empty - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - // empty - } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} - -class MyX509KeyManager extends X509ExtendedKeyManager { - - private final X509ExtendedKeyManager keyManager; - private String authType; - - MyX509KeyManager(X509ExtendedKeyManager keyManager) { - this.keyManager = keyManager; - } - - void setAuthType(String authType) { - this.authType = "ECDSA".equals(authType) ? "EC" : authType; - } - - public String[] getClientAliases(String keyType, Principal[] issuers) { - if (authType == null) { - return null; - } - return keyManager.getClientAliases(authType, issuers); - } - - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - if (authType == null) { - return null; - } - return keyManager.chooseClientAlias(new String[] {authType}, - issuers, socket); - } - - public String chooseEngineClientAlias(String[] keyType, - Principal[] issuers, SSLEngine engine) { - if (authType == null) { - return null; - } - return keyManager.chooseEngineClientAlias(new String[] {authType}, - issuers, engine); - } - - public String[] getServerAliases(String keyType, Principal[] issuers) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public String chooseEngineServerAlias(String keyType, Principal[] issuers, - SSLEngine engine) { - throw new UnsupportedOperationException("Servers not supported"); - } - - public X509Certificate[] getCertificateChain(String alias) { - return keyManager.getCertificateChain(alias); - } - - public PrivateKey getPrivateKey(String alias) { - return keyManager.getPrivateKey(alias); - } - -} - -class DaemonThreadFactory implements ThreadFactory { - - final static ThreadFactory INSTANCE = new DaemonThreadFactory(); - - private final static ThreadFactory DEFAULT = Executors.defaultThreadFactory(); - - public Thread newThread(Runnable r) { - Thread t = DEFAULT.newThread(r); - t.setDaemon(true); - return t; - } - -}
--- a/test/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 6405536 8080102 - * @summary Verify that all ciphersuites work (incl. ECC using NSS crypto) - * @author Andreas Sterbenz - * @library .. - * @library ../../../../java/security/testlibrary - * @run main/othervm -Djdk.tls.namedGroups="secp256r1,sect193r1" - * ClientJSSEServerJSSE - */ - -import java.security.*; - -public class ClientJSSEServerJSSE extends PKCS11Test { - - private static String[] cmdArgs; - - public static void main(String[] args) throws Exception { - // reset security properties to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - Security.setProperty("jdk.certpath.disabledAlgorithms", ""); - - cmdArgs = args; - main(new ClientJSSEServerJSSE()); - // now test without SunEC Provider - System.setProperty("testWithoutSunEC", "true"); - main(new ClientJSSEServerJSSE()); - - } - - public void main(Provider p) throws Exception { - String testWithoutSunEC = System.getProperty("testWithoutSunEC"); - - if (p.getService("KeyFactory", "EC") == null) { - System.out.println("Provider does not support EC, skipping"); - return; - } - - if (testWithoutSunEC != null) { - Provider sunec = Security.getProvider("SunEC"); - if (sunec == null) { - System.out.println("SunEC provider not present. Skipping test"); - return; - } - Security.removeProvider(sunec.getName()); - } - - Providers.setAt(p, 1); - CipherTest.main(new JSSEFactory(), cmdArgs); - Security.removeProvider(p.getName()); - } - - private static class JSSEFactory extends CipherTest.PeerFactory { - - String getName() { - return "Client JSSE - Server JSSE"; - } - - CipherTest.Client newClient(CipherTest cipherTest) throws Exception { - return new JSSEClient(cipherTest); - } - - CipherTest.Server newServer(CipherTest cipherTest) throws Exception { - return new JSSEServer(cipherTest); - } - } -}
--- a/test/sun/security/pkcs11/sslecc/JSSEClient.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.net.*; -import java.util.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -class JSSEClient extends CipherTest.Client { - - private final SSLContext sslContext; - private final MyX509KeyManager keyManager; - - JSSEClient(CipherTest cipherTest) throws Exception { - super(cipherTest); - this.keyManager = new MyX509KeyManager(CipherTest.keyManager); - sslContext = SSLContext.getInstance("TLS"); - } - - void runTest(CipherTest.TestParameters params) throws Exception { - SSLSocket socket = null; - try { - keyManager.setAuthType(params.clientAuth); - sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom); - SSLSocketFactory factory = (SSLSocketFactory)sslContext.getSocketFactory(); - socket = (SSLSocket)factory.createSocket("127.0.0.1", cipherTest.serverPort); - socket.setSoTimeout(cipherTest.TIMEOUT); - socket.setEnabledCipherSuites(new String[] {params.cipherSuite}); - socket.setEnabledProtocols(new String[] {params.protocol}); - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - sendRequest(in, out); - socket.close(); - SSLSession session = socket.getSession(); - session.invalidate(); - String cipherSuite = session.getCipherSuite(); - if (params.cipherSuite.equals(cipherSuite) == false) { - throw new Exception("Negotiated ciphersuite mismatch: " + cipherSuite + " != " + params.cipherSuite); - } - String protocol = session.getProtocol(); - if (params.protocol.equals(protocol) == false) { - throw new Exception("Negotiated protocol mismatch: " + protocol + " != " + params.protocol); - } - if (cipherSuite.indexOf("DH_anon") == -1) { - session.getPeerCertificates(); - } - Certificate[] certificates = session.getLocalCertificates(); - if (params.clientAuth == null) { - if (certificates != null) { - throw new Exception("Local certificates should be null"); - } - } else { - if ((certificates == null) || (certificates.length == 0)) { - throw new Exception("Certificates missing"); - } - String keyAlg = certificates[0].getPublicKey().getAlgorithm(); - if (keyAlg.equals("EC")) { - keyAlg = "ECDSA"; - } - if (params.clientAuth != keyAlg) { - throw new Exception("Certificate type mismatch: " + keyAlg + " != " + params.clientAuth); - } - } - } finally { - if (socket != null) { - socket.close(); - } - } - } - -}
--- a/test/sun/security/pkcs11/sslecc/JSSEServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.concurrent.*; - -import java.security.*; -import java.security.cert.*; -import java.security.cert.Certificate; - -import javax.net.ssl.*; - -class JSSEServer extends CipherTest.Server { - - SSLServerSocket serverSocket; - - JSSEServer(CipherTest cipherTest) throws Exception { - super(cipherTest); - SSLContext serverContext = SSLContext.getInstance("TLS"); - serverContext.init(new KeyManager[] {cipherTest.keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom); - - SSLServerSocketFactory factory = (SSLServerSocketFactory)serverContext.getServerSocketFactory(); - serverSocket = (SSLServerSocket)factory.createServerSocket(0); - cipherTest.serverPort = serverSocket.getLocalPort(); - serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites()); - serverSocket.setWantClientAuth(true); - } - - public void run() { - System.out.println("JSSE Server listening on port " + cipherTest.serverPort); - Executor exec = Executors.newFixedThreadPool - (cipherTest.THREADS, DaemonThreadFactory.INSTANCE); - try { - while (true) { - final SSLSocket socket = (SSLSocket)serverSocket.accept(); - socket.setSoTimeout(cipherTest.TIMEOUT); - Runnable r = new Runnable() { - public void run() { - try { - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - handleRequest(in, out); - out.flush(); - socket.close(); - socket.getSession().invalidate(); - } catch (IOException e) { - cipherTest.setFailed(); - e.printStackTrace(); - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - cipherTest.setFailed(); - System.out.println("Exception closing socket on server side:"); - e.printStackTrace(); - } - } - } - } - }; - exec.execute(r); - } - } catch (IOException e) { - cipherTest.setFailed(); - e.printStackTrace(); - // - } - } - -}
--- a/test/sun/security/ssl/AppInputStream/ReadBlocksClose.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4814140 - * @summary AppInputStream: read can block a close - * @run main/othervm ReadBlocksClose - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class ReadBlocksClose { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - try { - sslIS.read(); - } catch (IOException e) { - // this is ok, we expect this to time out anyway if the bug - // is not fixed. This is just to make sure that we - // don't inadvertantly fail. - } - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - final InputStream sslIS = sslSocket.getInputStream(); - final OutputStream sslOS = sslSocket.getOutputStream(); - - new Thread(new Runnable() { - public void run() { - try { - System.out.println("Closing Thread started"); - Thread.sleep(3000); - System.out.println("Closing Thread closing"); - sslIS.close(); - } catch (Exception e) { - RuntimeException rte = - new RuntimeException("Check this out"); - rte.initCause(e); - throw rte; - } - } - }).start(); - - try { - /* - * This should timeout and fail the test - */ - System.out.println("Client starting read"); - sslIS.read(); - } catch (IOException e) { - // this is ok, we expect this to time out anyway if the bug - // is not fixed. This is just to make sure that we - // don't inadvertantly fail. - } - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ReadBlocksClose(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ReadBlocksClose() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/sun/security/ssl/AppInputStream/ReadHandshake.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4514971 - * @summary Verify applications do not read handshake data after failure - * @run main/othervm ReadHandshake - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class ReadHandshake { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - // Note: we use anonymous ciphersuites only, no keys/ trusted certs needed - - private final static String[] CLIENT_SUITES = new String[] { - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", - }; - - private final static String[] SERVER_SUITES = new String[] { - "SSL_DH_anon_WITH_RC4_128_MD5", - }; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLSocket sslSocket = null; - SSLServerSocket sslServerSocket = null; - try { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - sslServerSocket.setEnabledCipherSuites(SERVER_SUITES); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - System.out.println("Server waiting for connection"); - - sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - System.out.println("Server starting handshake..."); - - - try { - sslIS.read(); - throw new Exception("No handshake exception on server side"); - } catch (IOException e) { - System.out.println("Handshake failed on server side, OK"); - } - - for (int i = 0; i < 3; i++) { - try { - int ch; - if ((ch = sslIS.read()) != -1) { - throw new Exception("Read succeeded server side: " - + ch); - } - } catch (IOException e) { - System.out.println("Exception for read() on server, OK"); - } - } - - } finally { - closeSocket(sslSocket); - closeSocket(sslServerSocket); - } - } - - private static void closeSocket(Socket s) { - try { - if (s != null) { - s.close(); - } - } catch (Exception e) { - // ignore - } - } - - private static void closeSocket(ServerSocket s) { - try { - if (s != null) { - s.close(); - } - } catch (Exception e) { - // ignore - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(80); - } - - SSLSocket sslSocket = null; - try { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - sslSocket.setEnabledCipherSuites(CLIENT_SUITES); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - System.out.println("Client starting handshake..."); - - try { - sslIS.read(); - throw new Exception("No handshake exception on client side"); - } catch (IOException e) { - System.out.println("Handshake failed on client side, OK"); - } - - for (int i = 0; i < 3; i++) { - try { - int ch; - if ((ch = sslIS.read()) != -1) { - throw new Exception("Read succeeded on client side: " - + ch); - } - } catch (IOException e) { - System.out.println("Exception for read() on client, OK"); - } - } - } finally { - sslSocket.close(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ReadHandshake(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ReadHandshake() throws Exception { - startServer(true); - startClient(true); - - serverThread.join(); - clientThread.join(); - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - if (clientException != null) { - System.out.println("Client exception:"); - clientException.printStackTrace(System.out); - } - throw serverException; - } - if (clientException != null) { - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/AppOutputStream/NoExceptionOnClose.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test 1.3 01/03/08 - * @bug 4378397 - * @summary JSSE socket output stream doesn't throw after socket is closed - * @run main/othervm NoExceptionOnClose - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Jaya Hangal - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class NoExceptionOnClose { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - boolean useSSL = true; - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - ServerSocket serverSocket; - if (useSSL) { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - serverSocket = (SSLServerSocket) sslssf. - createServerSocket(serverPort); - } else { - serverSocket = new ServerSocket(serverPort); - } - serverPort = serverSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - Socket socket = serverSocket.accept(); - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - int read = sslIS.read(); - System.out.println("Server read: " + read); - sslOS.write(85); - sslOS.flush(); - socket.close(); - socket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - Socket socket; - if (useSSL) { - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - socket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - } else - socket = new Socket("localhost", serverPort); - - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(80); - sslOS.flush(); - int read = sslIS.read(); - System.out.println("client read: " + read); - socket.close(); - /* - * The socket closed exception must be thrown here - */ - boolean isSocketClosedThrown = false; - try { - sslOS.write(22); - sslOS.flush(); - } catch (SocketException socketClosed) { - System.out.println("Received \"" + socketClosed.getMessage() - + "\" exception as expected"); - isSocketClosedThrown = true; - } - if (!isSocketClosedThrown) { - throw new Exception("No Exception thrown on write() after" - + " close()"); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new NoExceptionOnClose(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - NoExceptionOnClose() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/CertPathRestrictions/JSSEServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.InputStream; -import java.io.OutputStream; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; - -/* - * A SSL socket server. - */ -public class JSSEServer { - - private SSLServerSocket server = null; - - public JSSEServer(SSLContext context, - boolean needClientAuth) throws Exception { - SSLServerSocketFactory serverFactory = context.getServerSocketFactory(); - server = (SSLServerSocket) serverFactory.createServerSocket(0); - server.setSoTimeout(TLSRestrictions.TIMEOUT); - server.setNeedClientAuth(needClientAuth); // for dual authentication - System.out.println("Server: port=" + getPort()); - } - - public Exception start() { - System.out.println("Server: started"); - Exception exception = null; - try (SSLSocket socket = (SSLSocket) server.accept()) { - System.out.println("Server: accepted connection"); - socket.setSoTimeout(TLSRestrictions.TIMEOUT); - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - sslIS.read(); - sslOS.write('S'); - sslOS.flush(); - System.out.println("Server: finished"); - } catch (Exception e) { - exception = e; - e.printStackTrace(System.out); - System.out.println("Server: failed"); - } - - return exception; - } - - public int getPort() { - return server.getLocalPort(); - } -}
--- a/test/sun/security/ssl/CertPathRestrictions/TLSRestrictions.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,545 +0,0 @@ -/* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.SocketTimeoutException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.KeyFactory; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.Base64; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.TrustManagerFactory; - -import jdk.testlibrary.OutputAnalyzer; -import jdk.testlibrary.ProcessTools; - -/* - * @test - * @bug 8165367 - * @summary Verify the restrictions for certificate path on JSSE with custom trust store. - * @library /lib/testlibrary - * @compile JSSEClient.java - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions DEFAULT - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C1 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S1 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C2 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S2 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C3 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S3 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C4 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S4 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C5 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S5 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C6 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S6 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C7 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S7 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C8 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S8 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions C9 - * @run main/othervm -Djava.security.debug=certpath TLSRestrictions S9 - */ -public class TLSRestrictions { - - private static final String TEST_CLASSES = System.getProperty("test.classes"); - private static final char[] PASSWORD = "".toCharArray(); - private static final String CERT_DIR = System.getProperty("cert.dir", - System.getProperty("test.src") + "/certs"); - - static final String PROP = "jdk.certpath.disabledAlgorithms"; - static final String NOSHA1 = "MD2, MD5"; - private static final String TLSSERVER = "SHA1 usage TLSServer"; - private static final String TLSCLIENT = "SHA1 usage TLSClient"; - static final String JDKCATLSSERVER = "SHA1 jdkCA & usage TLSServer"; - static final String JDKCATLSCLIENT = "SHA1 jdkCA & usage TLSClient"; - - // This is a space holder in command arguments, and stands for none certificate. - static final String NONE_CERT = "NONE_CERT"; - - static final String DELIMITER = ","; - static final int TIMEOUT = 30000; - - // It checks if java.security contains constraint "SHA1 jdkCA & usage TLSServer" - // for jdk.certpath.disabledAlgorithms by default. - private static void checkDefaultConstraint() { - System.out.println( - "Case: Checks the default value of jdk.certpath.disabledAlgorithms"); - if (!Security.getProperty(PROP).contains(JDKCATLSSERVER)) { - throw new RuntimeException(String.format( - "%s doesn't contain constraint \"%s\", the real value is \"%s\".", - PROP, JDKCATLSSERVER, Security.getProperty(PROP))); - } - } - - /* - * This method creates trust store and key store with specified certificates - * respectively. And then it creates SSL context with the stores. - * If trustNames contains NONE_CERT only, it does not create a custom trust - * store, but the default one in JDK. - * - * @param trustNames Trust anchors, which are used to create custom trust store. - * If null, no custom trust store is created and the default - * trust store in JDK is used. - * @param certNames Certificate chain, which is used to create key store. - * It cannot be null. - */ - static SSLContext createSSLContext(String[] trustNames, - String[] certNames) throws Exception { - CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); - - TrustManagerFactory tmf = null; - if (trustNames != null && trustNames.length > 0 - && !trustNames[0].equals(NONE_CERT)) { - KeyStore trustStore = KeyStore.getInstance("JKS"); - trustStore.load(null, null); - for (int i = 0; i < trustNames.length; i++) { - try (InputStream is = new ByteArrayInputStream( - loadCert(trustNames[i]).getBytes())) { - Certificate trustCert = certFactory.generateCertificate(is); - trustStore.setCertificateEntry("trustCert-" + i, trustCert); - } - } - - tmf = TrustManagerFactory.getInstance("PKIX"); - tmf.init(trustStore); - } - - Certificate[] certChain = new Certificate[certNames.length]; - for (int i = 0; i < certNames.length; i++) { - try (InputStream is = new ByteArrayInputStream( - loadCert(certNames[i]).getBytes())) { - Certificate cert = certFactory.generateCertificate(is); - certChain[i] = cert; - } - } - - PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(loadPrivKey(certNames[0]))); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PrivateKey privKey = keyFactory.generatePrivate(privKeySpec); - - KeyStore keyStore = KeyStore.getInstance("JKS"); - keyStore.load(null, null); - keyStore.setKeyEntry("keyCert", privKey, PASSWORD, certChain); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(keyStore, PASSWORD); - - SSLContext context = SSLContext.getInstance("TLS"); - context.init(kmf.getKeyManagers(), - tmf == null ? null : tmf.getTrustManagers(), null); - return context; - } - - /* - * This method sets jdk.certpath.disabledAlgorithms, and then retrieves - * and prints its value. - */ - static void setConstraint(String side, String constraint) { - System.out.printf("%s: Old %s=%s%n", side, PROP, - Security.getProperty(PROP)); - Security.setProperty(PROP, constraint); - System.out.printf("%s: New %s=%s%n", side, PROP, - Security.getProperty(PROP)); - } - - /* - * This method is used to run a variety of cases. - * It launches a server, and then takes a client to connect the server. - * Both of server and client use the same certificates. - * - * @param trustNames Trust anchors, which are used to create custom trust store. - * If null, the default trust store in JDK is used. - * @param certNames Certificate chain, which is used to create key store. - * It cannot be null. The first certificate is regarded as - * the end entity. - * @param serverConstraint jdk.certpath.disabledAlgorithms value on server side. - * @param clientConstraint jdk.certpath.disabledAlgorithms value on client side. - * @param needClientAuth If true, server side acquires client authentication; - * otherwise, false. - * @param pass If true, the connection should be blocked; otherwise, false. - */ - static void testConstraint(String[] trustNames, String[] certNames, - String serverConstraint, String clientConstraint, - boolean needClientAuth, boolean pass) throws Throwable { - String trustNameStr = trustNames == null ? "" - : String.join(DELIMITER, trustNames); - String certNameStr = certNames == null ? "" - : String.join(DELIMITER, certNames); - - System.out.printf("Case:%n" - + " trustNames=%s; certNames=%s%n" - + " serverConstraint=%s; clientConstraint=%s%n" - + " needClientAuth=%s%n" - + " pass=%s%n%n", - trustNameStr, certNameStr, - serverConstraint, clientConstraint, - needClientAuth, - pass); - setConstraint("Server", serverConstraint); - ExecutorService executor = Executors.newFixedThreadPool(1); - try { - JSSEServer server = new JSSEServer( - createSSLContext(trustNames, certNames), - needClientAuth); - int port = server.getPort(); - Future<Exception> serverFuture = executor.submit(() -> server.start()); - - // Run client on another JVM so that its properties cannot be in conflict - // with server's. - OutputAnalyzer outputAnalyzer = ProcessTools.executeTestJvm( - "-Dcert.dir=" + CERT_DIR, - "-Djava.security.debug=certpath", - "-classpath", - TEST_CLASSES, - "JSSEClient", - port + "", - trustNameStr, - certNameStr, - clientConstraint); - int clientExitValue = outputAnalyzer.getExitValue(); - String clientOut = outputAnalyzer.getOutput(); - System.out.println("---------- Client output start ----------"); - System.out.println(clientOut); - System.out.println("---------- Client output end ----------"); - - Exception serverException = serverFuture.get(TIMEOUT, TimeUnit.MILLISECONDS); - if (serverException instanceof SocketTimeoutException - || clientOut.contains("SocketTimeoutException")) { - System.out.println("The communication gets timeout and skips the test."); - return; - } - - if (pass) { - if (serverException != null || clientExitValue != 0) { - throw new RuntimeException( - "Unexpected failure. Operation was blocked."); - } - } else { - if (serverException == null && clientExitValue == 0) { - throw new RuntimeException( - "Unexpected pass. Operation was allowed."); - } - - // The test may encounter non-SSL issues, like network problem. - if (!(serverException instanceof SSLHandshakeException - || clientOut.contains("SSLHandshakeException"))) { - throw new RuntimeException("Failure with unexpected exception."); - } - } - } finally { - executor.shutdown(); - } - } - - /* - * This method is used to run a variety of cases, which don't require client - * authentication by default. - */ - static void testConstraint(String[] trustNames, String[] certNames, - String serverConstraint, String clientConstraint, boolean pass) - throws Throwable { - testConstraint(trustNames, certNames, serverConstraint, clientConstraint, - false, pass); - } - - public static void main(String[] args) throws Throwable { - switch (args[0]) { - // Case DEFAULT only checks one of default settings for - // jdk.certpath.disabledAlgorithms in JDK/conf/security/java.security. - case "DEFAULT": - checkDefaultConstraint(); - break; - - // Cases C1 and S1 use SHA256 root CA in trust store, - // and use SHA256 end entity in key store. - // C1 only sets constraint "SHA1 usage TLSServer" on client side; - // S1 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should not be blocked. - case "C1": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { "INTER_CA_SHA256-ROOT_CA_SHA256" }, - NOSHA1, - TLSSERVER, - true); - break; - case "S1": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { "INTER_CA_SHA256-ROOT_CA_SHA256" }, - TLSCLIENT, - NOSHA1, - true, - true); - break; - - // Cases C2 and S2 use SHA256 root CA in trust store, - // and use SHA1 end entity in key store. - // C2 only sets constraint "SHA1 usage TLSServer" on client side; - // S2 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should be blocked. - case "C2": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { "INTER_CA_SHA1-ROOT_CA_SHA256" }, - NOSHA1, - TLSSERVER, - false); - break; - case "S2": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { "INTER_CA_SHA1-ROOT_CA_SHA256" }, - TLSCLIENT, - NOSHA1, - true, - false); - break; - - // Cases C3 and S3 use SHA1 root CA in trust store, - // and use SHA1 end entity in key store. - // C3 only sets constraint "SHA1 usage TLSServer" on client side; - // S3 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should be blocked. - case "C3": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { "INTER_CA_SHA1-ROOT_CA_SHA1" }, - NOSHA1, - TLSSERVER, - false); - break; - case "S3": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { "INTER_CA_SHA1-ROOT_CA_SHA1" }, - TLSCLIENT, - NOSHA1, - true, - false); - break; - - // Cases C4 and S4 use SHA1 root CA as trust store, - // and use SHA256 end entity in key store. - // C4 only sets constraint "SHA1 usage TLSServer" on client side; - // S4 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should not be blocked. - case "C4": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { "INTER_CA_SHA256-ROOT_CA_SHA1" }, - NOSHA1, - TLSSERVER, - true); - break; - case "S4": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { "INTER_CA_SHA256-ROOT_CA_SHA1" }, - TLSCLIENT, - NOSHA1, - true, - true); - break; - - // Cases C5 and S5 use SHA1 root CA in trust store, - // and use SHA256 intermediate CA and SHA256 end entity in key store. - // C5 only sets constraint "SHA1 usage TLSServer" on client side; - // S5 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should not be blocked. - case "C5": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA256-ROOT_CA_SHA1", - "INTER_CA_SHA256-ROOT_CA_SHA1" }, - NOSHA1, - TLSSERVER, - true); - break; - case "S5": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA256-ROOT_CA_SHA1", - "INTER_CA_SHA256-ROOT_CA_SHA1" }, - TLSCLIENT, - NOSHA1, - true, - true); - break; - - // Cases C6 and S6 use SHA1 root CA as trust store, - // and use SHA1 intermediate CA and SHA256 end entity in key store. - // C6 only sets constraint "SHA1 usage TLSServer" on client side; - // S6 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should be blocked. - case "C6": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA1", - "INTER_CA_SHA1-ROOT_CA_SHA1" }, - NOSHA1, - TLSSERVER, - false); - break; - case "S6": - testConstraint( - new String[] { "ROOT_CA_SHA1" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA1", - "INTER_CA_SHA1-ROOT_CA_SHA1" }, - TLSCLIENT, - NOSHA1, - true, - false); - break; - - // Cases C7 and S7 use SHA256 root CA in trust store, - // and use SHA256 intermediate CA and SHA1 end entity in key store. - // C7 only sets constraint "SHA1 usage TLSServer" on client side; - // S7 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should be blocked. - case "C7": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA1-INTER_CA_SHA256-ROOT_CA_SHA256", - "INTER_CA_SHA256-ROOT_CA_SHA256" }, - NOSHA1, - TLSSERVER, - false); - break; - case "S7": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA1-INTER_CA_SHA256-ROOT_CA_SHA256", - "INTER_CA_SHA256-ROOT_CA_SHA256" }, - TLSCLIENT, - NOSHA1, - true, - false); - break; - - // Cases C8 and S8 use SHA256 root CA in trust store, - // and use SHA1 intermediate CA and SHA256 end entity in key store. - // C8 only sets constraint "SHA1 usage TLSServer" on client side; - // S8 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should be blocked. - case "C8": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA256", - "INTER_CA_SHA1-ROOT_CA_SHA256" }, - NOSHA1, - TLSSERVER, - false); - break; - case "S8": - testConstraint( - new String[] { "ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA256", - "INTER_CA_SHA1-ROOT_CA_SHA256" }, - TLSCLIENT, - NOSHA1, - true, - false); - break; - - // Cases C9 and S9 use SHA256 root CA and SHA1 intermediate CA in trust store, - // and use SHA256 end entity in key store. - // C9 only sets constraint "SHA1 usage TLSServer" on client side; - // S9 only sets constraint "SHA1 usage TLSClient" on server side with client auth. - // The connection of the both cases should not be blocked. - case "C9": - testConstraint( - new String[] { - "ROOT_CA_SHA256", - "INTER_CA_SHA1-ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA256" }, - NOSHA1, - TLSSERVER, - true); - break; - case "S9": - testConstraint( - new String[] { - "ROOT_CA_SHA256", - "INTER_CA_SHA1-ROOT_CA_SHA256" }, - new String[] { - "END_ENTITY_SHA256-INTER_CA_SHA1-ROOT_CA_SHA256" }, - TLSCLIENT, - NOSHA1, - true, - true); - break; - } - System.out.println("Case passed"); - System.out.println("========================================"); - } - - private static String loadCert(String certName) { - try { - Path certFilePath = Paths.get(CERT_DIR, certName + ".cer"); - return String.join("\n", - Files.lines(certFilePath).filter((String line) -> { - return !line.startsWith("Certificate") - && !line.startsWith(" "); - }).collect(Collectors.toList())); - } catch (IOException e) { - throw new RuntimeException("Load certificate failed", e); - } - } - - private static String loadPrivKey(String certName) { - Path priveKeyFilePath = Paths.get(CERT_DIR, certName + "-PRIV.key"); - try { - return new String(Files.readAllBytes(priveKeyFilePath)); - } catch (IOException e) { - throw new RuntimeException("Load private key failed", e); - } - } -}
--- a/test/sun/security/ssl/CipherSuite/SSL_NULL.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/** - * @test - * @bug 4854838 - * @summary Verify that SSL_NULL_WITH_NULL_NULL is returned as ciphersuite if the handshake fails - * @author Andreas Sterbenz - */ - -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import javax.net.ssl.*; - -public class SSL_NULL { - - private static volatile Boolean result; - - public static void main(String[] args) throws Exception { - final SSLServerSocket serverSocket = (SSLServerSocket) - SSLServerSocketFactory.getDefault().createServerSocket(0); - serverSocket.setEnabledCipherSuites( - serverSocket.getSupportedCipherSuites()); - new Thread() { - public void run() { - try { - SSLSocket socket = (SSLSocket) serverSocket.accept(); - String suite = socket.getSession().getCipherSuite(); - if (!"SSL_NULL_WITH_NULL_NULL".equals(suite)) { - System.err.println( - "Wrong suite for failed handshake: " + - "got " + suite + - ", expected SSL_NULL_WITH_NULL_NULL"); - } else { - result = Boolean.TRUE; - return; - } - } catch (IOException e) { - System.err.println("Unexpected exception"); - e.printStackTrace(); - } finally { - if (result == null) { - result = Boolean.FALSE; - } - } - } - }.start(); - - SSLSocket socket = (SSLSocket) - SSLSocketFactory.getDefault().createSocket( - "localhost", serverSocket.getLocalPort()); - socket.setEnabledCipherSuites( - new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); - try { - OutputStream out = socket.getOutputStream(); - out.write(0); - out.flush(); - throw new RuntimeException("No exception received"); - } catch (SSLHandshakeException e) { - } - System.out.println("client: " + socket.getSession().getCipherSuite()); - // wait for other thread to set result - while (result == null) { - Thread.sleep(50); - } - if (result.booleanValue()) { - System.out.println("Test passed"); - } else { - throw new Exception("Test failed"); - } - } -}
--- a/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,814 +0,0 @@ -/* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 8044860 8074462 - * @summary Vectors and fixed length fields should be verified - * for allowed sizes. - * @run main/othervm LengthCheckTest - */ - -/** - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -import java.util.List; -import java.util.ArrayList; -import sun.security.ssl.ProtocolVersion; - -public class LengthCheckTest { - - /* - * Enables logging of the SSLEngine operations. - */ - private static final boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static final boolean debug = false; - private static final boolean dumpBufs = true; - - private final SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - private HandshakeTest handshakeTest; - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static final String pathToStores = "../../../../javax/net/ssl/etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static final String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - // Define a few basic TLS record and message types we might need - private static final int TLS_RECTYPE_CCS = 0x14; - private static final int TLS_RECTYPE_ALERT = 0x15; - private static final int TLS_RECTYPE_HANDSHAKE = 0x16; - private static final int TLS_RECTYPE_APPDATA = 0x17; - - private static final int TLS_HS_HELLO_REQUEST = 0x00; - private static final int TLS_HS_CLIENT_HELLO = 0x01; - private static final int TLS_HS_SERVER_HELLO = 0x02; - private static final int TLS_HS_CERTIFICATE = 0x0B; - private static final int TLS_HS_SERVER_KEY_EXCHG = 0x0C; - private static final int TLS_HS_CERT_REQUEST = 0x0D; - private static final int TLS_HS_SERVER_HELLO_DONE = 0x0E; - private static final int TLS_HS_CERT_VERIFY = 0x0F; - private static final int TLS_HS_CLIENT_KEY_EXCHG = 0x10; - private static final int TLS_HS_FINISHED = 0x14; - - // We're not going to define all the alert types in TLS, just - // the ones we think we'll need to reference by name. - private static final int TLS_ALERT_LVL_WARNING = 0x01; - private static final int TLS_ALERT_LVL_FATAL = 0x02; - - private static final int TLS_ALERT_UNEXPECTED_MSG = 0x0A; - private static final int TLS_ALERT_HANDSHAKE_FAILURE = 0x28; - private static final int TLS_ALERT_INTERNAL_ERROR = 0x50; - - public interface HandshakeTest { - void execTest() throws Exception; - } - - public final HandshakeTest servSendLongID = new HandshakeTest() { - @Override - public void execTest() throws Exception { - boolean gotException = false; - SSLEngineResult clientResult; // results from client's last op - SSLEngineResult serverResult; // results from server's last op - - log("\n==== Test: Client receives 64-byte session ID ===="); - - // Send Client Hello - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - cTOs.flip(); - dumpByteBuffer("CLIENT-TO-SERVER", cTOs); - - // Server consumes Client Hello - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - cTOs.compact(); - - // Server generates ServerHello/Cert/Done record - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - sTOc.flip(); - - // Intercept the ServerHello messages and instead send - // one that has a 64-byte session ID. - if (isTlsMessage(sTOc, TLS_RECTYPE_HANDSHAKE, - TLS_HS_SERVER_HELLO)) { - ArrayList<ByteBuffer> recList = splitRecord(sTOc); - - // Use the original ServerHello as a template to craft one - // with a longer-than-allowed session ID. - ByteBuffer servHelloBuf = - createEvilServerHello(recList.get(0), 64); - - recList.set(0, servHelloBuf); - - // Now send each ByteBuffer (each being a complete - // TLS record) into the client-side unwrap. - for (ByteBuffer bBuf : recList) { - dumpByteBuffer("SERVER-TO-CLIENT", bBuf); - try { - clientResult = clientEngine.unwrap(bBuf, clientIn); - } catch (SSLProtocolException e) { - log("Received expected SSLProtocolException: " + e); - gotException = true; - } - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - } - } else { - dumpByteBuffer("SERVER-TO-CLIENT", sTOc); - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - } - sTOc.compact(); - - // The Client should now send a TLS Alert - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - cTOs.flip(); - dumpByteBuffer("CLIENT-TO-SERVER", cTOs); - - // At this point we can verify that both an exception - // was thrown and the proper action (a TLS alert) was - // sent back to the server. - if (gotException == false || - !isTlsMessage(cTOs, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL, - TLS_ALERT_UNEXPECTED_MSG)) { - throw new SSLException( - "Client failed to throw Alert:fatal:internal_error"); - } - } - }; - - public final HandshakeTest clientSendLongID = new HandshakeTest() { - @Override - public void execTest() throws Exception { - boolean gotException = false; - SSLEngineResult clientResult; // results from client's last op - SSLEngineResult serverResult; // results from server's last op - - log("\n==== Test: Server receives 64-byte session ID ===="); - - // Send Client Hello - ByteBuffer evilClientHello = createEvilClientHello(64); - dumpByteBuffer("CLIENT-TO-SERVER", evilClientHello); - - try { - // Server consumes Client Hello - serverResult = serverEngine.unwrap(evilClientHello, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - evilClientHello.compact(); - - // Under normal circumstances this should be a ServerHello - // But should throw an exception instead due to the invalid - // session ID. - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - sTOc.flip(); - dumpByteBuffer("SERVER-TO-CLIENT", sTOc); - } catch (SSLProtocolException ssle) { - log("Received expected SSLProtocolException: " + ssle); - gotException = true; - } - - // We expect to see the server generate an alert here - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - sTOc.flip(); - dumpByteBuffer("SERVER-TO-CLIENT", sTOc); - - // At this point we can verify that both an exception - // was thrown and the proper action (a TLS alert) was - // sent back to the client. - if (gotException == false || - !isTlsMessage(sTOc, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL, - TLS_ALERT_UNEXPECTED_MSG)) { - throw new SSLException( - "Server failed to throw Alert:fatal:internal_error"); - } - } - }; - - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - List<LengthCheckTest> ccsTests = new ArrayList<>(); - - if (debug) { - System.setProperty("javax.net.debug", "ssl"); - } - - ccsTests.add(new LengthCheckTest("ServSendLongID")); - ccsTests.add(new LengthCheckTest("ClientSendLongID")); - - for (LengthCheckTest test : ccsTests) { - test.runTest(); - } - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public LengthCheckTest(String testName) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - - switch (testName) { - case "ServSendLongID": - handshakeTest = servSendLongID; - break; - case "ClientSendLongID": - handshakeTest = clientSendLongID; - break; - default: - throw new IllegalArgumentException("Unknown test name: " + - testName); - } - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - handshakeTest.execTest(); - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(false); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - - // In order to make a test that will be backwards compatible - // going back to JDK 5, force the handshake to be TLS 1.0 and - // use one of the older cipher suites. - clientEngine.setEnabledProtocols(new String[]{"TLSv1"}); - clientEngine.setEnabledCipherSuites( - new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" + - "\t\"getStatus() / getHandshakeStatus()\" +\n" + - "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str + - result.getStatus() + "/" + hsStatus + ", " + - result.bytesConsumed() + "/" + result.bytesProduced() + - " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } - - /** - * Split a record consisting of multiple TLS handshake messages - * into individual TLS records, each one in a ByteBuffer of its own. - * - * @param tlsRecord A ByteBuffer containing the tls record data. - * The position of the buffer should be at the first byte - * in the TLS record data. - * - * @return An ArrayList consisting of one or more ByteBuffers. Each - * ByteBuffer will contain a single TLS record with one message. - * That message will be taken from the input record. The order - * of the messages in the ArrayList will be the same as they - * were in the input record. - */ - private ArrayList<ByteBuffer> splitRecord(ByteBuffer tlsRecord) { - SSLSession session = clientEngine.getSession(); - int netBufferMax = session.getPacketBufferSize(); - ArrayList<ByteBuffer> recordList = new ArrayList<>(); - - if (tlsRecord.hasRemaining()) { - int type = Byte.toUnsignedInt(tlsRecord.get()); - byte ver_major = tlsRecord.get(); - byte ver_minor = tlsRecord.get(); - int recLen = Short.toUnsignedInt(tlsRecord.getShort()); - byte[] newMsgData = null; - while (tlsRecord.hasRemaining()) { - ByteBuffer newRecord = ByteBuffer.allocateDirect(netBufferMax); - switch (type) { - case TLS_RECTYPE_CCS: - case TLS_RECTYPE_ALERT: - case TLS_RECTYPE_APPDATA: - // None of our tests have multiple non-handshake - // messages coalesced into a single record. - break; - case TLS_RECTYPE_HANDSHAKE: - newMsgData = getHandshakeMessage(tlsRecord); - break; - } - - // Put a new TLS record on the destination ByteBuffer - newRecord.put((byte)type); - newRecord.put(ver_major); - newRecord.put(ver_minor); - newRecord.putShort((short)newMsgData.length); - - // Now add the message content itself and attach to the - // returned ArrayList - newRecord.put(newMsgData); - newRecord.flip(); - recordList.add(newRecord); - } - } - - return recordList; - } - - private static ByteBuffer createEvilClientHello(int sessIdLen) { - ByteBuffer newRecord = ByteBuffer.allocateDirect(4096); - - // Lengths will initially be place holders until we determine the - // finished length of the ByteBuffer. Then we'll go back and scribble - // in the correct lengths. - - newRecord.put((byte)TLS_RECTYPE_HANDSHAKE); // Record type - newRecord.putShort((short)0x0301); // Protocol (TLS 1.0) - newRecord.putShort((short)0); // Length place holder - - newRecord.putInt(TLS_HS_CLIENT_HELLO << 24); // HS type and length - newRecord.putShort((short)0x0301); - newRecord.putInt((int)(System.currentTimeMillis() / 1000)); - SecureRandom sr = new SecureRandom(); - byte[] randBuf = new byte[28]; - sr.nextBytes(randBuf); - newRecord.put(randBuf); // Client Random - newRecord.put((byte)sessIdLen); // Session ID length - if (sessIdLen > 0) { - byte[] sessId = new byte[sessIdLen]; - sr.nextBytes(sessId); - newRecord.put(sessId); // Session ID - } - newRecord.putShort((short)2); // 2 bytes of ciphers - newRecord.putShort((short)0x002F); // TLS_RSA_AES_CBC_SHA - newRecord.putShort((short)0x0100); // only null compression - newRecord.putShort((short)5); // 5 bytes of extensions - newRecord.putShort((short)0xFF01); // Renegotiation info - newRecord.putShort((short)1); - newRecord.put((byte)0); // No reneg info exts - - // Go back and fill in the correct length values for the record - // and handshake message headers. - int recordLength = newRecord.position(); - newRecord.putShort(3, (short)(recordLength - 5)); - int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) | - ((recordLength - 9) & 0x00FFFFFF); - newRecord.putInt(5, newTypeAndLen); - - newRecord.flip(); - return newRecord; - } - - private static ByteBuffer createEvilServerHello(ByteBuffer origHello, - int newSessIdLen) { - if (newSessIdLen < 0 || newSessIdLen > Byte.MAX_VALUE) { - throw new RuntimeException("Length must be 0 <= X <= 127"); - } - - ByteBuffer newRecord = ByteBuffer.allocateDirect(4096); - // Copy the bytes from the old hello to the new up to the session ID - // field. We will go back later and fill in a new length field in - // the record header. This includes the record header (5 bytes), the - // Handshake message header (4 bytes), protocol version (2 bytes), - // and the random (32 bytes). - ByteBuffer scratchBuffer = origHello.slice(); - scratchBuffer.limit(43); - newRecord.put(scratchBuffer); - - // Advance the position in the originial hello buffer past the - // session ID. - origHello.position(43); - int origIDLen = Byte.toUnsignedInt(origHello.get()); - if (origIDLen > 0) { - // Skip over the session ID - origHello.position(origHello.position() + origIDLen); - } - - // Now add our own sessionID to the new record - SecureRandom sr = new SecureRandom(); - byte[] sessId = new byte[newSessIdLen]; - sr.nextBytes(sessId); - newRecord.put((byte)newSessIdLen); - newRecord.put(sessId); - - // Create another slice in the original buffer, based on the position - // past the session ID. Copy the remaining bytes into the new - // hello buffer. Then go back and fix up the length - newRecord.put(origHello.slice()); - - // Go back and fill in the correct length values for the record - // and handshake message headers. - int recordLength = newRecord.position(); - newRecord.putShort(3, (short)(recordLength - 5)); - int newTypeAndLen = (newRecord.getInt(5) & 0xFF000000) | - ((recordLength - 9) & 0x00FFFFFF); - newRecord.putInt(5, newTypeAndLen); - - newRecord.flip(); - return newRecord; - } - - /** - * Look at an incoming TLS record and see if it is the desired - * record type, and where appropriate the correct subtype. - * - * @param srcRecord The input TLS record to be evaluated. This - * method will only look at the leading message if multiple - * TLS handshake messages are coalesced into a single record. - * @param reqRecType The requested TLS record type - * @param recParams Zero or more integer sub type fields. For CCS - * and ApplicationData, no params are used. For handshake records, - * one value corresponding to the HandshakeType is required. - * For Alerts, two values corresponding to AlertLevel and - * AlertDescription are necessary. - * - * @return true if the proper handshake message is the first one - * in the input record, false otherwise. - */ - private boolean isTlsMessage(ByteBuffer srcRecord, int reqRecType, - int... recParams) { - boolean foundMsg = false; - - if (srcRecord.hasRemaining()) { - srcRecord.mark(); - - // Grab the fields from the TLS Record - int recordType = Byte.toUnsignedInt(srcRecord.get()); - byte ver_major = srcRecord.get(); - byte ver_minor = srcRecord.get(); - int recLen = Short.toUnsignedInt(srcRecord.getShort()); - - if (recordType == reqRecType) { - // For any zero-length recParams, making sure the requested - // type is sufficient. - if (recParams.length == 0) { - foundMsg = true; - } else { - switch (recordType) { - case TLS_RECTYPE_CCS: - case TLS_RECTYPE_APPDATA: - // We really shouldn't find ourselves here, but - // if someone asked for these types and had more - // recParams we can ignore them. - foundMsg = true; - break; - case TLS_RECTYPE_ALERT: - // Needs two params, AlertLevel and AlertDescription - if (recParams.length != 2) { - throw new RuntimeException( - "Test for Alert requires level and desc."); - } else { - int level = Byte.toUnsignedInt(srcRecord.get()); - int desc = Byte.toUnsignedInt(srcRecord.get()); - if (level == recParams[0] && - desc == recParams[1]) { - foundMsg = true; - } - } - break; - case TLS_RECTYPE_HANDSHAKE: - // Needs one parameter, HandshakeType - if (recParams.length != 1) { - throw new RuntimeException( - "Test for Handshake requires only HS type"); - } else { - // Go into the first handhshake message in the - // record and grab the handshake message header. - // All we need to do is parse out the leading - // byte. - int msgHdr = srcRecord.getInt(); - int msgType = (msgHdr >> 24) & 0x000000FF; - if (msgType == recParams[0]) { - foundMsg = true; - } - } - break; - } - } - } - - srcRecord.reset(); - } - - return foundMsg; - } - - private byte[] getHandshakeMessage(ByteBuffer srcRecord) { - // At the start of this routine, the position should be lined up - // at the first byte of a handshake message. Mark this location - // so we can return to it after reading the type and length. - srcRecord.mark(); - int msgHdr = srcRecord.getInt(); - int type = (msgHdr >> 24) & 0x000000FF; - int length = msgHdr & 0x00FFFFFF; - - // Create a byte array that has enough space for the handshake - // message header and body. - byte[] data = new byte[length + 4]; - srcRecord.reset(); - srcRecord.get(data, 0, length + 4); - - return (data); - } - - /** - * Hex-dumps a ByteBuffer to stdout. - */ - private static void dumpByteBuffer(String header, ByteBuffer bBuf) { - if (dumpBufs == false) { - return; - } - - int bufLen = bBuf.remaining(); - if (bufLen > 0) { - bBuf.mark(); - - // We expect the position of the buffer to be at the - // beginning of a TLS record. Get the type, version and length. - int type = Byte.toUnsignedInt(bBuf.get()); - int ver_major = Byte.toUnsignedInt(bBuf.get()); - int ver_minor = Byte.toUnsignedInt(bBuf.get()); - int recLen = Short.toUnsignedInt(bBuf.getShort()); - ProtocolVersion pv = ProtocolVersion.valueOf(ver_major, ver_minor); - - log("===== " + header + " (" + tlsRecType(type) + " / " + - pv + " / " + bufLen + " bytes) ====="); - bBuf.reset(); - for (int i = 0; i < bufLen; i++) { - if (i != 0 && i % 16 == 0) { - System.out.print("\n"); - } - System.out.format("%02X ", bBuf.get(i)); - } - log("\n==============================================="); - bBuf.reset(); - } - } - - private static String tlsRecType(int type) { - switch (type) { - case 20: - return "Change Cipher Spec"; - case 21: - return "Alert"; - case 22: - return "Handshake"; - case 23: - return "Application Data"; - default: - return ("Unknown (" + type + ")"); - } - } -}
--- a/test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,493 +0,0 @@ -/* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 6956398 - * @summary make ephemeral DH key match the length of the certificate key - * @run main/othervm - * DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched - * DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy - * DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024 - * DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1259 75 - * - * @run main/othervm - * DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA true 233 75 - * - * @run main/othervm - * DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1387 139 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy - * DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1323 107 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched - * DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1643 267 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024 - * DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1387 139 - * - * @run main/othervm - * DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 false 361 139 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy - * DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 false 297 107 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched - * DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 false 361 139 - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024 - * DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 false 361 139 - */ - -/* - * This is a simple hack to test key sizes of Diffie-Hellman key exchanging - * during SSL/TLS handshaking. - * - * The record length of DH ServerKeyExchange and ClientKeyExchange. - * ServerKeyExchange message are wrapped in ServerHello series messages, which - * contains ServerHello, Certificate and ServerKeyExchange message. - * - * struct { - * opaque dh_p<1..2^16-1>; - * opaque dh_g<1..2^16-1>; - * opaque dh_Ys<1..2^16-1>; - * } ServerDHParams; // Ephemeral DH parameters - * - * struct { - * select (PublicValueEncoding) { - * case implicit: struct { }; - * case explicit: opaque dh_Yc<1..2^16-1>; - * } dh_public; - * } ClientDiffieHellmanPublic; - * - * Fomr above structures, it is clear that if the DH key size increasing 128 - * bits (16 bytes), the ServerHello series messages increases 48 bytes - * (becuase dh_p, dh_g and dh_Ys each increase 16 bytes) and ClientKeyExchange - * increases 16 bytes (because of the size increasing of dh_Yc). - * - * Here is a summary of the record length in the test case. - * - * | ServerHello Series | ClientKeyExchange | ServerHello Anon - * 512-bit | 1259 bytes | 75 bytes | 233 bytes - * 768-bit | 1323 bytes | 107 bytes | 297 bytes - * 1024-bit | 1387 bytes | 139 bytes | 361 bytes - * 2048-bit | 1643 bytes | 267 bytes | 361 bytes - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.nio.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.interfaces.*; -import java.util.Base64; - -public class DHEKeySizing { - - private final static boolean debug = true; - - // key length bias because of the stripping of leading zero bytes of - // negotiated DH keys. - // - // This is an effort to mimum intermittent failure when we cannot - // estimate what's the exact number of leading zero bytes of - // negotiated DH keys. - private final static int KEY_LEN_BIAS = 6; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIIC8jCCAdqgAwIBAgIEUjkuRzANBgkqhkiG9w0BAQUFADA7MR0wGwYDVQQLExRT\n" + - "dW5KU1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMw\n" + - "HhcNMTMwOTE4MDQzODMxWhcNMTMxMjE3MDQzODMxWjA7MR0wGwYDVQQLExRTdW5K\n" + - "U1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMwggEi\n" + - "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCO+IGeaskJAvEcYc7pCl9neK3E\n" + - "a28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0LKXArpI3thLNK\n" + - "QLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO19FbjxAfInJqk\n" + - "3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ7MrIOqHPd+8r\n" + - "RbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTkM65T1hnnOv5n\n" + - "ZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+PqPgWNl3+/AgMB\n" + - "AAEwDQYJKoZIhvcNAQEFBQADggEBAAlrP6DFLRPSy0IgQhcI2i56tR/na8pezSte\n" + - "ZHcCdaCZPDy4UP8mpLJ9QCjEB5VJv8hPm4xdK7ULnKGOGHgYqDpV2ZHvQlhV1woQ\n" + - "TZGb/LM3c6kAs0j4j9KM2fq3iYUYexjIkS1KzsziflxMM6igS9BRMBR2LQyU+cYq\n" + - "YEsFzkF7Aj2ET4v/+tgot9mRr2NioJcaJkdsPDpMU3IKB1cczfu+OuLQ/GCG0Fqu\n" + - "6ijCeCqfnaAbemHbJeVZZ6Qgka3uC2YMntLBmLkhqEo1d9zGYLoh7oWL77y5ibQZ\n" + - "LK5/H/zikcu579TWjlDHcqL3arCwBcrtsjSaPrRSWMrWV/6c0qw=\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8 - static String targetPrivateKey = - "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCO+IGeaskJAvEc\n" + - "Yc7pCl9neK3Ea28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0L\n" + - "KXArpI3thLNKQLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO1\n" + - "9FbjxAfInJqk3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ\n" + - "7MrIOqHPd+8rRbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTk\n" + - "M65T1hnnOv5nZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+Pq\n" + - "PgWNl3+/AgMBAAECggEAPdb5Ycc4m4A9QBSCRcRpzbyiFLKPh0HDg1n65q4hOtYr\n" + - "kAVYTVFTSF/lqGS+Ob3w2YIKujQKSUQrvCc5UHdFuHXMgxKIWbymK0+DAMb9SlYw\n" + - "6lkkcWp9gx9E4dnJ/df2SAAxovvrKMuHlL1SFASHhVtPfH2URvSfUaANLDXxyYOs\n" + - "8BX0Nr6wazhWjLjXo9yIGnKSvFfB8XisYcA78kEgas43zhmIGCDPqaYyyffOfRbx\n" + - "pM1KNwGmlN86iWR1CbwA/wwhcMySWQueS+s7cHbpRqZIYJF9jEeELiwi0vxjealS\n" + - "EMuHYedIRFMWaDIq9XyjrvXamHb0Z25jlXBNZHaM0QKBgQDE9adl+zAezR/n79vw\n" + - "0XiX2Fx1UEo3ApZHuoA2Q/PcBk+rlKqqQ3IwTcy6Wo648wK7v6Nq7w5nEWcsf0dU\n" + - "QA2Ng/AJEev/IfF34x7sKGYxtk1gcE0EuSBA3R+ocEZxnNw1Ryd5nUU24s8d4jCP\n" + - "Mkothnyaim+zE2raDlEtVc0CaQKBgQC509av+02Uq5oMjzbQp5PBJfQFjATOQT15\n" + - "eefYnVYurkQ1kcVfixkrO2ORhg4SjmI2Z5hJDgGtXdwgidpzkad+R2epS5qLMyno\n" + - "lQVpY6bMpEZ7Mos0yQygxnm8uNohEcTExOe+nP5fNJVpzBsGmfeyYOhnPQlf6oqf\n" + - "0cHizedb5wKBgQC/l5LyMil6HOGHlhzmIm3jj7VI7QR0hJC5T6N+phVml8ESUDjA\n" + - "DYHbmSKouISTRtkG14FY+RiSjCxH7bvuKazFV2289PETquogTA/9e8MFYqfcQwG4\n" + - "sXi9gBxWlnj/9a2EKiYtOB5nKLR/BlNkSHA93tAA6N+FXEMZwMmYhxk42QKBgAuY\n" + - "HQgD3PZOsqDf+qKQIhbmAFCsSMx5o5VFtuJ8BpmJA/Z3ruHkMuDQpsi4nX4o5hXQ\n" + - "5t6AAjjH52kcUMXvK40kdWJJtk3DFnVNfvXxYsHX6hHbuHXFqYUKfSP6QJnZmvZP\n" + - "9smcz/4usLfWJUWHK740b6upUkFqx9Vq5/b3s9y3AoGAdM5TW7LkkOFsdMGVAUzR\n" + - "9iXmCWElHTK2Pcp/3yqDBHSfiQx6Yp5ANyPnE9NBM0yauCfOyBB2oxLO4Rdv3Rqk\n" + - "9V9kyR/YAGr7dJaPcQ7pZX0OpkzgueAOJYPrx5VUzPYUtklYV1ycFZTfKlpFCxT+\n" + - "Ei6KUo0NXSdUIcB4yib1J10="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Majority of the test case is here, setup is done below. - */ - - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine("server", 2); - ssle2.setUseClientMode(false); - } - - private boolean isHandshaking(SSLEngine e) { - return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING); - } - - private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut, - SSLEngineResult result, - Status status, HandshakeStatus hsStatus, - int consumed, int produced) - throws Exception { - - if ((status != null) && (result.getStatus() != status)) { - throw new Exception("Unexpected Status: need = " + status + - " got = " + result.getStatus()); - } - - if ((hsStatus != null) && (result.getHandshakeStatus() != hsStatus)) { - throw new Exception("Unexpected hsStatus: need = " + hsStatus + - " got = " + result.getHandshakeStatus()); - } - - if ((consumed != -1) && (consumed != result.bytesConsumed())) { - throw new Exception("Unexpected consumed: need = " + consumed + - " got = " + result.bytesConsumed()); - } - - if ((produced != -1) && (produced != result.bytesProduced())) { - throw new Exception("Unexpected produced: need = " + produced + - " got = " + result.bytesProduced()); - } - - if ((consumed != -1) && (bbIn.position() != result.bytesConsumed())) { - throw new Exception("Consumed " + bbIn.position() + - " != " + consumed); - } - - if ((produced != -1) && (bbOut.position() != result.bytesProduced())) { - throw new Exception("produced " + bbOut.position() + - " != " + produced); - } - } - - private void test(String cipherSuite, boolean exportable, - int lenServerKeyEx, int lenClientKeyEx) throws Exception { - - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - String[] suites = new String [] {cipherSuite}; - - ssle1.setEnabledCipherSuites(suites); - ssle2.setEnabledCipherSuites(suites); - - log("======================================"); - log("==================="); - log("client hello"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - oneToTwo.flip(); - - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - oneToTwo.compact(); - - log("==================="); - log("ServerHello"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); - - log("Message length of ServerHello series: " + twoToOne.remaining()); - if (twoToOne.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) || - twoToOne.remaining() > lenServerKeyEx) { - throw new Exception( - "Expected to generate ServerHello series messages of " + - lenServerKeyEx + " bytes, but not " + twoToOne.remaining()); - } - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0); - runDelegatedTasks(ssle1); - twoToOne.compact(); - - log("==================="); - log("Key Exchange"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - oneToTwo.flip(); - - log("Message length of ClientKeyExchange: " + oneToTwo.remaining()); - if (oneToTwo.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) || - oneToTwo.remaining() > lenClientKeyEx) { - throw new Exception( - "Expected to generate ClientKeyExchange message of " + - lenClientKeyEx + " bytes, but not " + oneToTwo.remaining()); - } - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - oneToTwo.compact(); - - log("==================="); - log("Client CCS"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - oneToTwo.flip(); - - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_UNWRAP, - result1.bytesProduced(), 0); - oneToTwo.compact(); - - log("==================="); - log("Client Finished"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - oneToTwo.flip(); - - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, - Status.OK, HandshakeStatus.NEED_WRAP, - result1.bytesProduced(), 0); - oneToTwo.compact(); - - log("==================="); - log("Server CCS"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("==================="); - log("Server Finished"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, - Status.OK, HandshakeStatus.FINISHED, 0, -1); - twoToOne.flip(); - - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, - Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0); - twoToOne.compact(); - - log("==================="); - log("Check Session/Ciphers"); - String cs = ssle1.getSession().getCipherSuite(); - if (!cs.equals(suites[0])) { - throw new Exception("suites not equal: " + cs + "/" + suites[0]); - } - - cs = ssle2.getSession().getCipherSuite(); - if (!cs.equals(suites[0])) { - throw new Exception("suites not equal: " + cs + "/" + suites[0]); - } - - log("==================="); - log("Done with SSL/TLS handshaking"); - } - - public static void main(String args[]) throws Exception { - // reset security properties to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - Security.setProperty("jdk.certpath.disabledAlgorithms", ""); - - if (args.length != 4) { - System.out.println( - "Usage: java DHEKeySizing cipher-suite " + - "exportable(true|false)\n" + - " size-of-server-hello-record size-of-client-key-exchange"); - throw new Exception("Incorrect usage!"); - } - - (new DHEKeySizing()).test(args[0], - Boolean.parseBoolean(args[1]), - Integer.parseInt(args[2]), - Integer.parseInt(args[3])); - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public DHEKeySizing() throws Exception { - sslc = getSSLContext(); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext() throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ts = KeyStore.getInstance("JKS"); - KeyStore ks = KeyStore.getInstance("JKS"); - ts.load(null, null); - ks.load(null, null); - - // import the trused cert - ByteArrayInputStream is = - new ByteArrayInputStream(trustedCertStr.getBytes()); - Certificate trusedCert = cf.generateCertificate(is); - is.close(); - ts.setCertificateEntry("rsa-trusted-2048", trusedCert); - - // generate the private key. - String keySpecStr = targetPrivateKey; - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - Certificate[] chain = new Certificate[1]; - chain[0] = trusedCert; - - // import the key entry. - ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain); - - // create SSL context - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLSv1"); - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngine engine) throws Exception { - - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/DHKeyExchange/LegacyDHEKeyExchange.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 8148108 - * @summary Disable Diffie-Hellman keys less than 1024 bits - * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy LegacyDHEKeyExchange - */ - -import java.io.*; -import javax.net.ssl.*; - -public class LegacyDHEKeyExchange { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - throw new Exception( - "Legacy DH keys (< 1024) should be restricted"); - } catch (SSLHandshakeException she) { - // ignore, client should terminate the connection - } finally { - sslServerSocket.close(); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - String[] suites = new String [] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"}; - sslSocket.setEnabledCipherSuites(suites); - - try { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - throw new Exception("Legacy DH keys (< 1024) should be restricted"); - } catch (SSLHandshakeException she) { - // ignore, should be caused by algorithm constraints - } finally { - sslSocket.close(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new LegacyDHEKeyExchange(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - LegacyDHEKeyExchange() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.sh Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -#! /bin/sh - -# -# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code 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 -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# @test -# @bug 7126889 -# @summary Incorrect SSLEngine debug output -# -# ${TESTJAVA} is pointing to the JDK under test. -# -# set platform-dependent variables - -OS=`uname -s` -case "$OS" in - SunOS | Linux | Darwin | AIX ) - PS=":" - FS="/" - ;; - CYGWIN* ) - PS=";" - FS="/" - ;; - Windows* ) - PS=";" - FS="\\" - ;; - * ) - echo "Unrecognized system!" - exit 1; - ;; -esac - -${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d . \ - ${TESTSRC}${FS}DebugReportsOneExtraByte.java - -STRING='main, WRITE: TLSv1 Application Data, length = 8' - -echo "Examining debug output for the string:" -echo "${STRING}" -echo "=========" - -${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Djavax.net.debug=all \ - -Dtest.src=${TESTSRC} \ - DebugReportsOneExtraByte 2>&1 | \ - grep "${STRING}" -RETVAL=$? - -echo "=========" - -if [ ${RETVAL} -ne 0 ]; then - echo "Did NOT see the expected debug output." - exit 1 -else - echo "Received the expected debug output." - exit 0 -fi -else - echo "Received the expected debug output." - exit 0 -fi
--- a/test/sun/security/ssl/GenSSLConfigs/main.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,274 +0,0 @@ -/* - * @test - * @build TestThread Traffic Handler ServerHandler ServerThread ClientThread - * @run main/othervm/timeout=140 -Djsse.enableCBCProtection=false main - * @summary Make sure that different configurations of SSL sockets work - */ - -/* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.security.SecureRandom; -import java.security.KeyStore; -import javax.security.cert.*; -import java.util.Date; -import java.util.Vector; -import java.util.ArrayList; - -import javax.net.ssl.*; - -public class main -{ - // NOTE: "prng" doesn't need to be a SecureRandom - - private static final SecureRandom prng - = new SecureRandom (); - private static SSLContext sslContext; - - private static void usage() { - System.err.println ( - "usage: tests.ssl.main default|random|cipher_suite [nthreads]"); - } - - /** - * Runs a test ... there are a variety of configurations, and the way - * they're invoked is subject to change. This program can support - * single and multiple process tests, but by default it's set up for - * single process testing. - * - * <P> The first commandline argument identifies a test configuration. - * Currently identified configurations include "default", "random". - * - * <P> The second commandline argument identifies the number of - * client threads to use. - */ - public static void main (String argv []) - { - String config; - int NTHREADS; - - initContext(); - String supported [] = sslContext.getSocketFactory() - .getSupportedCipherSuites(); - - // Strip out any Kerberos Suites for now. - ArrayList list = new ArrayList(supported.length); - for (int i = 0; i < supported.length; i++) { - if (!supported[i].startsWith("TLS_KRB5")) { - list.add(supported[i]); - } - } - supported = (String [])list.toArray(new String [0]); - - if (argv.length == 2) { - config = argv [0]; - NTHREADS = Integer.parseInt (argv [1]); - } else if (argv.length == 1) { - config = argv [0]; - NTHREADS = 15; - } else { - /* temporaraly changed to make it run under jtreg with - * default configuration, when no input parameters are - * given - */ - //usage(); - //return; - config = "default"; - NTHREADS = supported.length; - } - - // More options ... port #. different clnt/svr configs, - // cipher suites, etc. - - ServerThread server = new ServerThread (0, NTHREADS, sslContext); - Vector clients = new Vector (NTHREADS); - - if (!(config.equals("default") || config.equals("random"))) - supported = new String[] {config}; - - System.out.println("Supported cipher suites are:"); - for(int i=0; i < supported.length; i++) { - System.out.println(supported[i]); - } - - setConfig (server, config, supported); - - // if (OS != Win95) - server.setUseMT (true); - - server.start (); - server.waitTillReady (); - - // - // iterate over all cipher suites - // - int next = 0; - int passes = 0; - - if (usesRandom (config)) - next = nextUnsignedRandom (); - - for (int i = 0; i < NTHREADS; i++, next++) { - ClientThread client = new ClientThread (server.getServerPort(), sslContext); - String cipher [] = new String [1]; - - setConfig (client, config, supported); - next = next % supported.length; - cipher [0] = supported [next]; - client.setBasicCipherSuites (cipher); - - // - // Win95 has been observed to choke if you throw many - // connections at it. So we make it easy to unthread - // everything; it can be handy outside Win95 too. - // - client.start (); - if (!server.getUseMT ()) { - waitForClient (client); - if (client.passed ()) - passes++; - } else - clients.addElement (client); - } - - while (!clients.isEmpty ()) { - ClientThread client; - - client = (ClientThread) clients.elementAt (0); - clients.removeElement (client); - waitForClient (client); - if (client.passed ()) - passes++; - } - - System.out.println ("SUMMARY: threads = " + NTHREADS - + ", passes = " + passes); - } - - - // - // Rather than replicating code, a helper function! - // - private static void waitForClient (Thread client) - { - while (true) - try { - client.join (); - - // System.out.println ("Joined: " + client.getName ()); - break; - } catch (InterruptedException e) { - continue; - } - } - - private static void initContext() - { - try { - String testRoot = System.getProperty("test.src", "."); - System.setProperty("javax.net.ssl.trustStore", testRoot - + "/../../../../javax/net/ssl/etc/truststore"); - - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(testRoot - + "/../../../../javax/net/ssl/etc/keystore"), - "passphrase".toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, "passphrase".toCharArray()); - TrustManagerFactory tmf = - TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); - sslContext = SSLContext.getInstance("SSL"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - } catch (Throwable t) { - // oh well; ignore it, the tester presumably intends this - System.out.println("Failed to read keystore/truststore file... Continuing"); - t.printStackTrace(); - } - } - - private static int nextUnsignedRandom () - { - int retval = prng.nextInt (); - - if (retval < 0) - return -retval; - else - return retval; - } - - - // - // Randomness in testing can be good and bad ... covers more - // territory, but not reproducibly. - // - private static boolean usesRandom (String config) - { - return config.equalsIgnoreCase ("random"); - } - - - private static void setConfig ( - TestThread test, - String config, - String supported [] - ) - { - test.setBasicCipherSuites (supported); - test.setOutput (System.out); - test.setVerbosity (3); - - if (test instanceof ClientThread) { - test.setListenHandshake (true); - test.setIterations (20); - } - -// XXX role reversals !!! - - // - // We can establish a reasonable degree of variability - // on the test data and configs ... expecting that the - // diagnostics will identify any problems that exist. - // Client and server must agree on these things. - // - // Unless we do this, only the SSL nonces and ephemeral - // keys will be unpredictable in a given test run. Those - // affect only the utmost innards of SSL, details which - // are not visible to applications. - // - if (usesRandom (config)) { - int rand = nextUnsignedRandom (); - - if (test instanceof ClientThread) - test.setIterations (rand % 35); - - if ((rand & 0x080) == 0) - test.setInitiateHandshake (true); -// if ((rand & 0x040) == 0) -// test.setDoRenegotiate (true); - - test.setPRNG (new SecureRandom ()); - } - } -}
--- a/test/sun/security/ssl/HandshakeOutStream/NullCerts.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/security/ssl/HandshakeOutStream/NullCerts.java Tue Aug 25 18:03:27 2020 +0300 @@ -56,7 +56,6 @@ /* * Where do we find the keystores? */ - // private final static String pathToStores = "./etc"; private final static String pathToStores = "../../../../javax/net/ssl/etc"; private final static String keyStoreFile = "keystore"; private final static String trustStoreFile = "truststore";
--- a/test/sun/security/ssl/InputRecord/SSLSocketTimeoutNulls.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4456039 - * @summary Setting timeouts on SSLSockets immediately return null - * after timeout occurs. This bug was fixed as part of 4393337, - * but this is another bug we want to check regressions against. - * @run main/othervm/timeout=140 SSLSocketTimeoutNulls - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class SSLSocketTimeoutNulls { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - sslSocket.startHandshake(); - - sslIS.read(); - Thread.sleep(10000); // Stall past the timeout... - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - boolean caught = false; - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslSocket.startHandshake(); - - sslSocket.setSoTimeout(3000); // The stall timeout. - - sslOS.write(280); - sslOS.flush(); - - try { - if (sslIS.read() == -1); - throw new Exception("read == -1"); - // } catch (InterruptedIOException e) { /* if using < JDK 1.4 */ - } catch (SocketTimeoutException e) { - System.out.println("Caught right exception..."); - caught = true; - - // Try to read it again after it should be available. - Thread.sleep(5000); - if (sslIS.read() == 85) - System.out.println("Read the right value"); - else - throw new Exception("Test Failed"); - } - - if (!caught) - throw new Exception("Didn't see exception"); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SSLSocketTimeoutNulls(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketTimeoutNulls() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - System.err.println(e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java Tue Aug 25 18:03:27 2020 +0300 @@ -26,7 +26,7 @@ /* * @test - * @bug 8162362 8208350 + * @bug 8162362 * @summary Cannot enable previously default enabled cipher suites * @run main/othervm * CustomizedCipherSuites Default true
--- a/test/sun/security/ssl/SSLContextImpl/CustomizedDefaultProtocols.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7093640 - * @summary Enable TLS 1.1 and TLS 1.2 by default in client side of SunJSSE - * @run main/othervm -Djdk.tls.client.protocols="SSLv3,TLSv1,TLSv1.1" - * CustomizedDefaultProtocols - */ - -import javax.net.*; -import javax.net.ssl.*; -import java.util.Arrays; -import java.security.Security; - -public class CustomizedDefaultProtocols { - static enum ContextVersion { - TLS_CV_01("SSL", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}), - TLS_CV_02("TLS", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}), - TLS_CV_03("SSLv3", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_04("TLSv1", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_05("TLSv1.1", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}), - TLS_CV_06("TLSv1.2", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_07("Default", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}); - - final String contextVersion; - final String[] enabledProtocols; - final static String[] supportedProtocols = new String[] { - "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; - - ContextVersion(String contextVersion, String[] enabledProtocols) { - this.contextVersion = contextVersion; - this.enabledProtocols = enabledProtocols; - } - } - - private static boolean checkProtocols(String[] target, String[] expected) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No protocols"); - success = false; - } - - if (!Arrays.equals(target, expected)) { - System.out.println("\tError: Expected to get protocols " + - Arrays.toString(expected)); - System.out.println("\tError: The actual protocols " + - Arrays.toString(target)); - success = false; - } - - return success; - } - - private static boolean checkCipherSuites(String[] target) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No cipher suites"); - success = false; - } - - return success; - } - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - boolean failed = false; - for (ContextVersion cv : ContextVersion.values()) { - System.out.println("Checking SSLContext of " + cv.contextVersion); - SSLContext context = SSLContext.getInstance(cv.contextVersion); - - // Default SSLContext is initialized automatically. - if (!cv.contextVersion.equals("Default")) { - // Use default TK, KM and random. - context.init((KeyManager[])null, (TrustManager[])null, null); - } - - // - // Check SSLContext - // - // Check default SSLParameters of SSLContext - System.out.println("\tChecking default SSLParameters"); - SSLParameters parameters = context.getDefaultSSLParameters(); - - String[] protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - String[] ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // Check supported SSLParameters of SSLContext - System.out.println("\tChecking supported SSLParameters"); - parameters = context.getSupportedSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLEngine - // - // Check SSLParameters of SSLEngine - System.out.println(); - System.out.println("\tChecking SSLEngine of this SSLContext"); - System.out.println("\tChecking SSLEngine.getSSLParameters()"); - SSLEngine engine = context.createSSLEngine(); - engine.setUseClientMode(true); - parameters = engine.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = engine.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = engine.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = engine.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = engine.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLSocket - // - // Check SSLParameters of SSLSocket - System.out.println(); - System.out.println("\tChecking SSLSocket of this SSLContext"); - System.out.println("\tChecking SSLSocket.getSSLParameters()"); - SocketFactory fac = context.getSocketFactory(); - SSLSocket socket = (SSLSocket)fac.createSocket(); - parameters = socket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = socket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = socket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = socket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = socket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLServerSocket - // - // Check SSLParameters of SSLServerSocket - System.out.println(); - System.out.println("\tChecking SSLServerSocket of this SSLContext"); - System.out.println("\tChecking SSLServerSocket.getSSLParameters()"); - SSLServerSocketFactory sf = context.getServerSocketFactory(); - SSLServerSocket ssocket = (SSLServerSocket)sf.createServerSocket(); - parameters = ssocket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = ssocket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = ssocket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = ssocket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = ssocket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - } - - if (failed) { - throw new Exception("Run into problems, see log for more details"); - } else { - System.out.println("\t... Success"); - } - } -}
--- a/test/sun/security/ssl/SSLContextImpl/DefaultEnabledProtocols.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,243 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7093640 - * @summary Enable TLS 1.1 and TLS 1.2 by default in client side of SunJSSE - * @run main/othervm DefaultEnabledProtocols - */ - -import javax.net.*; -import javax.net.ssl.*; -import java.util.Arrays; -import java.security.Security; - -public class DefaultEnabledProtocols { - static enum ContextVersion { - TLS_CV_01("SSL", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_02("TLS", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_03("SSLv3", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_04("TLSv1", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_05("TLSv1.1", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}), - TLS_CV_06("TLSv1.2", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_07("Default", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}); - - final String contextVersion; - final String[] enabledProtocols; - final static String[] supportedProtocols = new String[] { - "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; - - ContextVersion(String contextVersion, String[] enabledProtocols) { - this.contextVersion = contextVersion; - this.enabledProtocols = enabledProtocols; - } - } - - private static boolean checkProtocols(String[] target, String[] expected) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No protocols"); - success = false; - } - - if (!Arrays.equals(target, expected)) { - System.out.println("\tError: Expected to get protocols " + - Arrays.toString(expected)); - System.out.println("\tError: The actual protocols " + - Arrays.toString(target)); - success = false; - } - - return success; - } - - private static boolean checkCipherSuites(String[] target) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No cipher suites"); - success = false; - } - - return success; - } - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - boolean failed = false; - for (ContextVersion cv : ContextVersion.values()) { - System.out.println("Checking SSLContext of " + cv.contextVersion); - SSLContext context = SSLContext.getInstance(cv.contextVersion); - - // Default SSLContext is initialized automatically. - if (!cv.contextVersion.equals("Default")) { - // Use default TK, KM and random. - context.init((KeyManager[])null, (TrustManager[])null, null); - } - - // - // Check SSLContext - // - // Check default SSLParameters of SSLContext - System.out.println("\tChecking default SSLParameters"); - SSLParameters parameters = context.getDefaultSSLParameters(); - - String[] protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - String[] ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // Check supported SSLParameters of SSLContext - System.out.println("\tChecking supported SSLParameters"); - parameters = context.getSupportedSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLEngine - // - // Check SSLParameters of SSLEngine - System.out.println(); - System.out.println("\tChecking SSLEngine of this SSLContext"); - System.out.println("\tChecking SSLEngine.getSSLParameters()"); - SSLEngine engine = context.createSSLEngine(); - engine.setUseClientMode(true); - parameters = engine.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = engine.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = engine.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = engine.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = engine.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLSocket - // - // Check SSLParameters of SSLSocket - System.out.println(); - System.out.println("\tChecking SSLSocket of this SSLContext"); - System.out.println("\tChecking SSLSocket.getSSLParameters()"); - SocketFactory fac = context.getSocketFactory(); - SSLSocket socket = (SSLSocket)fac.createSocket(); - parameters = socket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = socket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = socket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = socket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = socket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLServerSocket - // - // Check SSLParameters of SSLServerSocket - System.out.println(); - System.out.println("\tChecking SSLServerSocket of this SSLContext"); - System.out.println("\tChecking SSLServerSocket.getSSLParameters()"); - SSLServerSocketFactory sf = context.getServerSocketFactory(); - SSLServerSocket ssocket = (SSLServerSocket)sf.createServerSocket(); - parameters = ssocket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = ssocket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = ssocket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = ssocket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = ssocket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - } - - if (failed) { - throw new Exception("Run into problems, see log for more details"); - } else { - System.out.println("\t... Success"); - } - } -}
--- a/test/sun/security/ssl/SSLContextImpl/MD2InTrustAnchor.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7113275 - * @summary compatibility issue with MD2 trust anchor and old X509TrustManager - * @run main/othervm MD2InTrustAnchor PKIX TLSv1.1 - * @run main/othervm MD2InTrustAnchor SunX509 TLSv1.1 - * @run main/othervm MD2InTrustAnchor PKIX TLSv1.2 - * @run main/othervm MD2InTrustAnchor SunX509 TLSv1.2 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - -public class MD2InTrustAnchor { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Certificates and key used in the test. - */ - - // It's a trust anchor signed with MD2 hash function. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTE4MTExNDA0WhcNMzIxMDI4MTExNDA0WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAPGyB9tugUGgxtdeqe0qJEwf9x1Gy4BOi1yR\n" + - "wzDZY4H5LquvIfQ2V3J9X1MQENVsFvkvp65ZcFcy+ObOucXUUPFcd/iw2DVb5QXA\n" + - "ffyeVqWD56GPi8Qe37wrJO3L6fBhN9oxp/BbdRLgjU81zx8qLEyPODhPMxV4OkcA\n" + - "SDwZTSxxAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLOAtr/YrYj9H04EDLA0fd14jisF\n" + - "MGMGA1UdIwRcMFqAFLOAtr/YrYj9H04EDLA0fd14jisFoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + - "BQADgYEAr8ExpXu/FTIRiMzPm0ubqwME4lniilwQUiEOD/4DbksNjEIcUyS2hIk1\n" + - "qsmjJz3SHBnwhxl9dhJVwk2tZLkPGW86Zn0TPVRsttK4inTgCC9GFGeqQBdrU/uf\n" + - "lipBzXWljrfbg4N/kK8m2LabtKUMMnGysM8rN0Fx2PYm5xxGvtM=\n" + - "-----END CERTIFICATE-----"; - - // The certificate issued by above trust anchor, signed with MD5 - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICeDCCAeGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTE4MTExNDA2WhcNMzEwODA1MTExNDA2WjBPMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwDnm96mw\n" + - "fXCH4bgXk1US0VcJsQVxUtGMyncAveMuzBzNzOmKZPeqyYX1Fuh4q+cuza03WTJd\n" + - "G9nOkNr364e3Rn1aaHjCMcBmFflObnGnhhufNmIGYogJ9dJPmhUVPEVAXrMG+Ces\n" + - "NKy2E8woGnLMrqu6yiuTClbLBPK8fWzTXrECAwEAAaN4MHYwCwYDVR0PBAQDAgPo\n" + - "MB0GA1UdDgQWBBSdRrpocLPJXyGfDmMWJrcEf29WGDAfBgNVHSMEGDAWgBSzgLa/\n" + - "2K2I/R9OBAywNH3deI4rBTAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIG\n" + - "CCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GBAKJ71ZiCUykkJrCLYUxlFlhvUcr9\n" + - "sTcOc67QdroW5f412NI15SXWDiley/JOasIiuIFPjaJBjOKoHOvTjG/snVu9wEgq\n" + - "YNR8dPsO+NM8r79C6jO+Jx5fYAC7os2XxS75h3NX0ElJcbwIXGBJ6xRrsFh/BGYH\n" + - "yvudOlX4BkVR0l1K\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8. - static String targetPrivateKey = - "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMA55vepsH1wh+G4\n" + - "F5NVEtFXCbEFcVLRjMp3AL3jLswczczpimT3qsmF9RboeKvnLs2tN1kyXRvZzpDa\n" + - "9+uHt0Z9Wmh4wjHAZhX5Tm5xp4YbnzZiBmKICfXST5oVFTxFQF6zBvgnrDSsthPM\n" + - "KBpyzK6rusorkwpWywTyvH1s016xAgMBAAECgYEAn9bF3oRkdDoBU0i/mcww5I+K\n" + - "SH9tFt+WQbiojjz9ac49trkvUfu7MO1Jui2+QbrvaSkyj+HYGFOJd1wMsPXeB7ck\n" + - "5mOIYV4uZK8jfNMSQ8v0tFEeIPp5lKdw1XnrQfSe+abo2eL5Lwso437Y4s3w37+H\n" + - "aY3d76hR5qly+Ys+Ww0CQQDjeOoX89d/xhRqGXKjCx8ImE/dPmsI8O27cwtKrDYJ\n" + - "6t0v/xryVIdvOYcRBvKnqEogOH7T1kI+LnWKUTJ2ehJ7AkEA2FVloPVqCehXcc7e\n" + - "z3TDpU9w1B0JXklcV5HddYsRqp9RukN/VK4szKE7F1yoarIUtfE9Lr9082Jwyp3M\n" + - "L11xwwJBAKsZ+Hur3x0tUY29No2Nf/pnFyvEF57SGwA0uPmiL8Ol9lpz+UDudDEl\n" + - "hIM6Rqv12kwCMuQE9i7vo1o3WU3k5KECQEqhg1L49yD935TqiiFFpe0Ur9btQXse\n" + - "kdXAA4d2d5zGI7q/aGD9SYU6phkUJSHR16VA2RuUfzMrpb+wmm1IrmMCQFtLoKRT\n" + - "A5kokFb+E3Gplu29tJvCUpfwgBFRS+wmkvtiaU/tiyDcVgDO+An5DwedxxdVzqiE\n" + - "njWHoKY3axDQ8OU=\n"; - - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(trustedCertStr, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - sslServerSocket.setNeedClientAuth(true); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = generateSSLContext(trustedCertStr, targetCertStr, - targetPrivateKey); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - // enable the specified TLS protocol - sslSocket.setEnabledProtocols(new String[] {tlsProtocol}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String tlsProtocol; // trust manager - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - tlsProtocol = args[1]; - } - - private static SSLContext generateSSLContext(String trustedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trustedCertStr != null) { - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - // It's not allowed to send MD2 signed certificate to peer, - // even it may be a trusted certificate. Then we will not - // place the trusted certficate in the chain. - Certificate[] chain = new Certificate[1]; - chain[0] = keyCert; - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance(tlsProtocol); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new MD2InTrustAnchor(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - MD2InTrustAnchor() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - // swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/sun/security/ssl/SSLContextImpl/NoOldVersionContext.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7093640 - * @summary Enable TLS 1.1 and TLS 1.2 by default in client side of SunJSSE - * @run main/othervm -Djdk.tls.client.protocols="TLSv1,TLSv1.1,TLSv1.2" - * NoOldVersionContext - */ - -import javax.net.*; -import javax.net.ssl.*; -import java.util.Arrays; -import java.security.Security; - -public class NoOldVersionContext { - static enum ContextVersion { - TLS_CV_01("SSL", - new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_02("TLS", - new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_03("SSLv3", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_04("TLSv1", - new String[] {"SSLv3", "TLSv1"}), - TLS_CV_05("TLSv1.1", - new String[] {"SSLv3", "TLSv1", "TLSv1.1"}), - TLS_CV_06("TLSv1.2", - new String[] {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}), - TLS_CV_07("Default", - new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}); - - final String contextVersion; - final String[] enabledProtocols; - final static String[] supportedProtocols = new String[] { - "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; - - ContextVersion(String contextVersion, String[] enabledProtocols) { - this.contextVersion = contextVersion; - this.enabledProtocols = enabledProtocols; - } - } - - private static boolean checkProtocols(String[] target, String[] expected) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No protocols"); - success = false; - } - - if (!Arrays.equals(target, expected)) { - System.out.println("\tError: Expected to get protocols " + - Arrays.toString(expected)); - System.out.println("\tError: The actual protocols " + - Arrays.toString(target)); - success = false; - } - - return success; - } - - private static boolean checkCipherSuites(String[] target) { - boolean success = true; - if (target.length == 0) { - System.out.println("\tError: No cipher suites"); - success = false; - } - - return success; - } - - public static void main(String[] args) throws Exception { - // reset the security property to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - - boolean failed = false; - for (ContextVersion cv : ContextVersion.values()) { - System.out.println("Checking SSLContext of " + cv.contextVersion); - SSLContext context = SSLContext.getInstance(cv.contextVersion); - - // Default SSLContext is initialized automatically. - if (!cv.contextVersion.equals("Default")) { - // Use default TK, KM and random. - context.init((KeyManager[])null, (TrustManager[])null, null); - } - - // - // Check SSLContext - // - // Check default SSLParameters of SSLContext - System.out.println("\tChecking default SSLParameters"); - SSLParameters parameters = context.getDefaultSSLParameters(); - - String[] protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - String[] ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // Check supported SSLParameters of SSLContext - System.out.println("\tChecking supported SSLParameters"); - parameters = context.getSupportedSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLEngine - // - // Check SSLParameters of SSLEngine - System.out.println(); - System.out.println("\tChecking SSLEngine of this SSLContext"); - System.out.println("\tChecking SSLEngine.getSSLParameters()"); - SSLEngine engine = context.createSSLEngine(); - engine.setUseClientMode(true); - parameters = engine.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = engine.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = engine.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = engine.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = engine.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLSocket - // - // Check SSLParameters of SSLSocket - System.out.println(); - System.out.println("\tChecking SSLSocket of this SSLContext"); - System.out.println("\tChecking SSLSocket.getSSLParameters()"); - SocketFactory fac = context.getSocketFactory(); - SSLSocket socket = (SSLSocket)fac.createSocket(); - parameters = socket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = socket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.enabledProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = socket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = socket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = socket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - // - // Check SSLServerSocket - // - // Check SSLParameters of SSLServerSocket - System.out.println(); - System.out.println("\tChecking SSLServerSocket of this SSLContext"); - System.out.println("\tChecking SSLServerSocket.getSSLParameters()"); - SSLServerSocketFactory sf = context.getServerSocketFactory(); - SSLServerSocket ssocket = (SSLServerSocket)sf.createServerSocket(); - parameters = ssocket.getSSLParameters(); - - protocols = parameters.getProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - ciphers = parameters.getCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getEnabledProtocols()"); - protocols = ssocket.getEnabledProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println("\tChecking SSLEngine.getEnabledCipherSuites()"); - ciphers = ssocket.getEnabledCipherSuites(); - failed |= !checkCipherSuites(ciphers); - - System.out.println("\tChecking SSLEngine.getSupportedProtocols()"); - protocols = ssocket.getSupportedProtocols(); - failed |= !checkProtocols(protocols, cv.supportedProtocols); - - System.out.println( - "\tChecking SSLEngine.getSupportedCipherSuites()"); - ciphers = ssocket.getSupportedCipherSuites(); - failed |= !checkCipherSuites(ciphers); - } - - if (failed) { - throw new Exception("Run into problems, see log for more details"); - } else { - System.out.println("\t... Success"); - } - } -}
--- a/test/sun/security/ssl/SSLContextImpl/TrustTrustedCert.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,510 +0,0 @@ -/* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7113275 8164846 - * @summary compatibility issue with MD2 trust anchor and old X509TrustManager - * @run main/othervm TrustTrustedCert PKIX TLSv1.1 true - * @run main/othervm TrustTrustedCert PKIX TLSv1.1 false - * @run main/othervm TrustTrustedCert SunX509 TLSv1.1 false - * @run main/othervm TrustTrustedCert PKIX TLSv1.2 false - * @run main/othervm TrustTrustedCert SunX509 TLSv1.2 false - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.*; -import java.security.cert.*; -import java.security.spec.*; -import java.security.interfaces.*; -import java.util.Base64; - - -public class TrustTrustedCert { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Certificates and key used in the test. - */ - - // It's a trust anchor signed with MD2 hash function. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTE4MTExNDA0WhcNMzIxMDI4MTExNDA0WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAPGyB9tugUGgxtdeqe0qJEwf9x1Gy4BOi1yR\n" + - "wzDZY4H5LquvIfQ2V3J9X1MQENVsFvkvp65ZcFcy+ObOucXUUPFcd/iw2DVb5QXA\n" + - "ffyeVqWD56GPi8Qe37wrJO3L6fBhN9oxp/BbdRLgjU81zx8qLEyPODhPMxV4OkcA\n" + - "SDwZTSxxAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLOAtr/YrYj9H04EDLA0fd14jisF\n" + - "MGMGA1UdIwRcMFqAFLOAtr/YrYj9H04EDLA0fd14jisFoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + - "BQADgYEAr8ExpXu/FTIRiMzPm0ubqwME4lniilwQUiEOD/4DbksNjEIcUyS2hIk1\n" + - "qsmjJz3SHBnwhxl9dhJVwk2tZLkPGW86Zn0TPVRsttK4inTgCC9GFGeqQBdrU/uf\n" + - "lipBzXWljrfbg4N/kK8m2LabtKUMMnGysM8rN0Fx2PYm5xxGvtM=\n" + - "-----END CERTIFICATE-----"; - - // The certificate issued by above trust anchor, signed with MD5 - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICeDCCAeGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTExMTE4MTExNDA2WhcNMzEwODA1MTExNDA2WjBPMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + - "BAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwDnm96mw\n" + - "fXCH4bgXk1US0VcJsQVxUtGMyncAveMuzBzNzOmKZPeqyYX1Fuh4q+cuza03WTJd\n" + - "G9nOkNr364e3Rn1aaHjCMcBmFflObnGnhhufNmIGYogJ9dJPmhUVPEVAXrMG+Ces\n" + - "NKy2E8woGnLMrqu6yiuTClbLBPK8fWzTXrECAwEAAaN4MHYwCwYDVR0PBAQDAgPo\n" + - "MB0GA1UdDgQWBBSdRrpocLPJXyGfDmMWJrcEf29WGDAfBgNVHSMEGDAWgBSzgLa/\n" + - "2K2I/R9OBAywNH3deI4rBTAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIG\n" + - "CCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GBAKJ71ZiCUykkJrCLYUxlFlhvUcr9\n" + - "sTcOc67QdroW5f412NI15SXWDiley/JOasIiuIFPjaJBjOKoHOvTjG/snVu9wEgq\n" + - "YNR8dPsO+NM8r79C6jO+Jx5fYAC7os2XxS75h3NX0ElJcbwIXGBJ6xRrsFh/BGYH\n" + - "yvudOlX4BkVR0l1K\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8. - static String targetPrivateKey = - "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMA55vepsH1wh+G4\n" + - "F5NVEtFXCbEFcVLRjMp3AL3jLswczczpimT3qsmF9RboeKvnLs2tN1kyXRvZzpDa\n" + - "9+uHt0Z9Wmh4wjHAZhX5Tm5xp4YbnzZiBmKICfXST5oVFTxFQF6zBvgnrDSsthPM\n" + - "KBpyzK6rusorkwpWywTyvH1s016xAgMBAAECgYEAn9bF3oRkdDoBU0i/mcww5I+K\n" + - "SH9tFt+WQbiojjz9ac49trkvUfu7MO1Jui2+QbrvaSkyj+HYGFOJd1wMsPXeB7ck\n" + - "5mOIYV4uZK8jfNMSQ8v0tFEeIPp5lKdw1XnrQfSe+abo2eL5Lwso437Y4s3w37+H\n" + - "aY3d76hR5qly+Ys+Ww0CQQDjeOoX89d/xhRqGXKjCx8ImE/dPmsI8O27cwtKrDYJ\n" + - "6t0v/xryVIdvOYcRBvKnqEogOH7T1kI+LnWKUTJ2ehJ7AkEA2FVloPVqCehXcc7e\n" + - "z3TDpU9w1B0JXklcV5HddYsRqp9RukN/VK4szKE7F1yoarIUtfE9Lr9082Jwyp3M\n" + - "L11xwwJBAKsZ+Hur3x0tUY29No2Nf/pnFyvEF57SGwA0uPmiL8Ol9lpz+UDudDEl\n" + - "hIM6Rqv12kwCMuQE9i7vo1o3WU3k5KECQEqhg1L49yD935TqiiFFpe0Ur9btQXse\n" + - "kdXAA4d2d5zGI7q/aGD9SYU6phkUJSHR16VA2RuUfzMrpb+wmm1IrmMCQFtLoKRT\n" + - "A5kokFb+E3Gplu29tJvCUpfwgBFRS+wmkvtiaU/tiyDcVgDO+An5DwedxxdVzqiE\n" + - "njWHoKY3axDQ8OU=\n"; - - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = generateSSLContext(); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - sslServerSocket.setNeedClientAuth(true); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write('A'); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocket sslSocket = null; - try { - SSLContext context = generateSSLContext(); - SSLSocketFactory sslsf = context.getSocketFactory(); - - sslSocket = (SSLSocket)sslsf.createSocket("localhost", serverPort); - - // enable the specified TLS protocol - sslSocket.setEnabledProtocols(new String[] {tlsProtocol}); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - sslOS.write('B'); - sslOS.flush(); - sslIS.read(); - } catch (SSLHandshakeException e) { - // focus in on the CertPathValidatorException - Throwable t = e.getCause().getCause(); - if ((t == null) || (expectFail && - !t.toString().contains("MD5withRSA"))) { - throw new RuntimeException( - "Expected to see MD5withRSA in exception output " + t); - } - } finally { - if (sslSocket != null) sslSocket.close(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - private static String tmAlgorithm; // trust manager - private static String tlsProtocol; // trust manager - // set this flag to test context of CertificateException - private static boolean expectFail; - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - tlsProtocol = args[1]; - expectFail = Boolean.parseBoolean(args[2]); - } - - private static SSLContext generateSSLContext() throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - X509Certificate trusedCert = null; - ByteArrayInputStream is = - new ByteArrayInputStream(trustedCertStr.getBytes()); - trusedCert = (X509Certificate)cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("Trusted RSA Signer", trusedCert); - - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(targetPrivateKey)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(targetCertStr.getBytes()); - X509Certificate keyCert = (X509Certificate)cf.generateCertificate(is); - is.close(); - - X509Certificate[] chain = new X509Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - - // import the key entry and the chain - ks.setKeyEntry("TheKey", priKey, passphrase, chain); - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - // create the customized KM and TM - NoneExtendedX509TM myTM = - new NoneExtendedX509TM(tmf.getTrustManagers()[0]); - NoneExtendedX509KM myKM = - new NoneExtendedX509KM("TheKey", chain, priKey); - - SSLContext ctx = SSLContext.getInstance(tlsProtocol); - // KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - // kmf.init(ks, passphrase); - // ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ctx.init(new KeyManager[]{myKM}, new TrustManager[]{myTM}, null); - ks = null; - - return ctx; - } - - static class NoneExtendedX509TM implements X509TrustManager { - X509TrustManager tm; - - NoneExtendedX509TM(TrustManager tm) { - this.tm = (X509TrustManager)tm; - } - - public void checkClientTrusted(X509Certificate chain[], String authType) - throws CertificateException { - tm.checkClientTrusted(chain, authType); - } - - public void checkServerTrusted(X509Certificate chain[], String authType) - throws CertificateException { - tm.checkServerTrusted(chain, authType); - } - - public X509Certificate[] getAcceptedIssuers() { - return tm.getAcceptedIssuers(); - } - } - - static class NoneExtendedX509KM implements X509KeyManager { - private String keyAlias; - private X509Certificate[] chain; - private PrivateKey privateKey; - - NoneExtendedX509KM(String keyAlias, X509Certificate[] chain, - PrivateKey privateKey) { - this.keyAlias = keyAlias; - this.chain = chain; - this.privateKey = privateKey; - } - - public String[] getClientAliases(String keyType, Principal[] issuers) { - return new String[] {keyAlias}; - } - - public String chooseClientAlias(String[] keyType, Principal[] issuers, - Socket socket) { - return keyAlias; - } - - public String[] getServerAliases(String keyType, Principal[] issuers) { - return new String[] {keyAlias}; - } - - public String chooseServerAlias(String keyType, Principal[] issuers, - Socket socket) { - return keyAlias; - } - - public X509Certificate[] getCertificateChain(String alias) { - return chain; - } - - public PrivateKey getPrivateKey(String alias) { - return privateKey; - } - } - - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * MD5 is used in this test case, don't disable MD5 algorithm. - * if expectFail is set, we're testing exception message - */ - if (!expectFail) { - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - } - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new TrustTrustedCert(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - TrustTrustedCert() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - System.out.println("Unexpected exception: "); - e.printStackTrace(); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - if (!expectFail) { - // only record if we weren't expecting. - // client side will record exception - serverException = e; - } - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - // only record if we weren't expecting. - // client side will record exception - if (!expectFail) { - serverException = e; - } - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/CloseEngineException.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4969799 - * @summary javax.net.ssl.SSLSocket.SSLSocket(InetAddress,int) shouldn't - * throw exception - * @run main/othervm CloseEngineException - */ - -// -// This is making sure that starting a new handshake throws the right -// exception. There is a similar test for SSLSocket. -// - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class CloseEngineException { - - private static boolean debug = false; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - } - - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - log("================"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); - log(""); - - log("wrap2: " + result2); - log("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - log("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); - log(""); - - log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { - - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); - - log("Closing ssle1's *OUTBOUND*..."); - ssle1.closeOutbound(); - dataDone = true; - - try { - /* - * Check that closed Outbound generates. - */ - ssle1.beginHandshake(); - throw new Exception( - "TEST FAILED: didn't throw Exception"); - } catch (SSLException e) { - System.out.println("PARTIAL PASS"); - } - } - } - - try { - /* - * Check that closed Inbound generates. - */ - ssle2.beginHandshake(); - throw new Exception( - "TEST FAILED: didn't throw Exception"); - } catch (SSLException e) { - System.out.println("TEST PASSED"); - } - } - - public static void main(String args[]) throws Exception { - - CloseEngineException test; - - test = new CloseEngineException(); - - test.createSSLEngines(); - - test.runTest(); - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public CloseEngineException() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/CloseInboundException.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4931274 - * @summary closeInbound does not signal when a close_notify has not - * been received. - * @run main/othervm CloseInboundException - * @author Brad Wetmore - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class CloseInboundException { - - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void runTest(boolean inboundClose) throws Exception { - - boolean done = false; - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - System.out.println("================"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - System.out.println("wrap1 = " + result1); - System.out.println("oneToTwo = " + oneToTwo); - - System.out.println("wrap2 = " + result2); - System.out.println("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - System.out.println("----"); - result1 = ssle1.unwrap(twoToOne, appIn1); - - if (done && inboundClose) { - try { - result2 = ssle2.unwrap(oneToTwo, appIn2); - throw new Exception("Didn't throw Exception"); - } catch (SSLException e) { - System.out.println("Caught proper exception\n" + e); - return; - } - } else { - result2 = ssle2.unwrap(oneToTwo, appIn2); - } - - System.out.println("unwrap1 = " + result1); - System.out.println("twoToOne = " + twoToOne); - - System.out.println("unwrap2 = " + result2); - System.out.println("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!done && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { - - if (inboundClose) { - try { - System.out.println("Closing ssle1's *INBOUND*..."); - ssle1.closeInbound(); - throw new Exception("closeInbound didn't throw"); - } catch (SSLException e) { - System.out.println("Caught closeInbound exc properly"); - checkStatus(); - /* - * Let the message processing continue to - * handle the alert. - */ - } - done = true; - } else { - done = true; - System.out.println("Closing ssle1's *OUTBOUND*..."); - ssle1.closeOutbound(); - } - } - } - } - - /* - * Check to see if the close generated a close_notify message, - * that the result status is sane, and that close again doesn't - * generate a new exception. - * - * We'll consume the wrapped data when we loop back around. - */ - private void checkStatus() throws Exception { - System.out.println("\nCalling last wrap"); - int pos = oneToTwo.position(); - - result1 = ssle1.wrap(appOut1, oneToTwo); - System.out.println("result1 = " + result1); - - if ((pos >= oneToTwo.position()) || - !result1.getStatus().equals(Status.CLOSED) || - !result1.getHandshakeStatus().equals( - HandshakeStatus.NOT_HANDSHAKING) || - !ssle1.isOutboundDone() || - !ssle1.isInboundDone()) { - throw new Exception(result1.toString()); - } - System.out.println("Make sure we don't throw a second SSLException."); - ssle1.closeInbound(); - } - - public static void main(String args[]) throws Exception { - - CloseInboundException test; - - test = new CloseInboundException(); - test.runTest(false); - - test = new CloseInboundException(); - test.runTest(true); - System.out.println("Test PASSED!!!"); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public CloseInboundException() throws Exception { - - SSLContext sslc = getSSLContext(keyFilename, trustFilename); - - ssle1 = sslc.createSSLEngine("host1", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine("host2", 2); - ssle2.setUseClientMode(false); - - createBuffers(); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - System.out.println("AppOut1 = " + appOut1); - System.out.println("AppOut2 = " + appOut2); - System.out.println(); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus().equals(HandshakeStatus.NEED_TASK)) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - System.out.println("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - -}
--- a/test/sun/security/ssl/SSLEngineImpl/CloseStart.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 5019096 - * @summary Add scatter/gather APIs for SSLEngine - * @run main/othervm CloseStart - */ - -// -// Check to see if the args are being parsed properly. -// - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class CloseStart { - - private static boolean debug = false; - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private static void checkDone(SSLEngine ssle) throws Exception { - if (!ssle.isInboundDone()) { - throw new Exception("isInboundDone isn't done"); - } - if (!ssle.isOutboundDone()) { - throw new Exception("isOutboundDone isn't done"); - } - } - - private static void runTest1(SSLEngine ssle) throws Exception { - ssle.closeInbound(); - checkDone(ssle); - } - - private static void runTest2(SSLEngine ssle) throws Exception { - ssle.closeOutbound(); - checkDone(ssle); - } - - public static void main(String args[]) throws Exception { - - SSLEngine ssle = createSSLEngine(keyFilename, trustFilename); - runTest1(ssle); - - ssle = createSSLEngine(keyFilename, trustFilename); - runTest2(ssle); - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - static private SSLEngine createSSLEngine(String keyFile, String trustFile) - throws Exception { - - SSLEngine ssle; - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - ssle = sslCtx.createSSLEngine("client", 1001); - ssle.setUseClientMode(true); - - return ssle; - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4980882 - * @summary SSLEngine should enforce setUseClientMode - * @run main/othervm EngineEnforceUseClientMode - * @author Brad R. Wetmore - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class EngineEnforceUseClientMode { - - private static boolean debug = false; - - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private SSLEngine ssle3; // server - private SSLEngine ssle4; // server - private SSLEngine ssle5; // server - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - - /* - * Note, these are not initialized to client/server - */ - ssle3 = sslc.createSSLEngine(); - ssle4 = sslc.createSSLEngine(); - ssle5 = sslc.createSSLEngine(); - } - - private void runTest() throws Exception { - - createSSLEngines(); - createBuffers(); - - /* - * First try the engines with no client/server initialization - * All should fail. - */ - try { - System.out.println("Testing wrap()"); - ssle3.wrap(appOut1, oneToTwo); - throw new RuntimeException( - "wrap(): Didn't catch the exception properly"); - } catch (IllegalStateException e) { - System.out.println("Caught the correct exception."); - ssle3.wrap(appOut1, oneToTwo); - oneToTwo.flip(); - if (oneToTwo.hasRemaining()) { - throw new Exception("wrap1 generated data"); - } - oneToTwo.clear(); - } - - try { - System.out.println("Testing unwrap()"); - ssle4.unwrap(oneToTwo, appIn1); - throw new RuntimeException( - "unwrap(): Didn't catch the exception properly"); - } catch (IllegalStateException e) { - System.out.println("Caught the correct exception."); - ssle4.wrap(appOut1, oneToTwo); - oneToTwo.flip(); - if (oneToTwo.hasRemaining()) { - throw new Exception("wrap2 generated data"); - } - oneToTwo.clear(); - } - - try { - System.out.println("Testing beginHandshake()"); - ssle5.beginHandshake(); - throw new RuntimeException( - "unwrap(): Didn't catch the exception properly"); - } catch (IllegalStateException e) { - System.out.println("Caught the correct exception."); - ssle5.wrap(appOut1, oneToTwo); - oneToTwo.flip(); - if (oneToTwo.hasRemaining()) { - throw new Exception("wrap3 generated data"); - } - oneToTwo.clear(); - } - - boolean dataDone = false; - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { - - log("================"); - - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); - - log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); - log(""); - - log("wrap2: " + result2); - log("twoToOne = " + twoToOne); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.flip(); - twoToOne.flip(); - - log("----"); - - result1 = ssle1.unwrap(twoToOne, appIn1); - result2 = ssle2.unwrap(oneToTwo, appIn2); - - log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); - log(""); - - log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); - - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); - - oneToTwo.compact(); - twoToOne.compact(); - - /* - * If we've transfered all the data between app1 and app2, - * we try to close and see what that gets us. - */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { - - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); - - System.out.println("Try changing modes..."); - try { - ssle2.setUseClientMode(false); - throw new RuntimeException( - "setUseClientMode(): " + - "Didn't catch the exception properly"); - } catch (IllegalArgumentException e) { - System.out.println("Caught the correct exception."); - } - - return; - } - } - } - - public static void main(String args[]) throws Exception { - - EngineEnforceUseClientMode test; - - test = new EngineEnforceUseClientMode(); - - test.createSSLEngines(); - - test.runTest(); - - System.out.println("Test Passed."); - } - - /* - * ********************************************************** - * Majority of the test case is above, below is just setup stuff - * ********************************************************** - */ - - public EngineEnforceUseClientMode() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.clear(); - b.clear(); - } - - private static void log(String str) { - if (debug) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,523 +0,0 @@ -/* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 6207322 - * @summary SSLEngine is returning a premature FINISHED message when doing - * an abbreviated handshake. - * @run main/othervm RehandshakeFinished - * @author Brad Wetmore - */ - -/* - * This test may need some updating if the messages change order. - * Currently I'm expecting that there is a simple renegotiation, with - * each message being contained in a single SSL packet. - * - * ClientHello - * Server Hello - * CCS - * FINISHED - * CCS - * FINISHED - */ - -/** - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; - -public class RehandshakeFinished { - - /* - * Enables logging of the SSLEngine operations. - */ - private static boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static boolean debug = false; - - static private SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private static Exception loadException = null; - - static { - try { - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = - TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - sslc = sslCtx; - } catch (Exception e) { - loadException = e; - } - } - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - if (loadException != null) { - throw loadException; - } - - // Prime the session cache with a good session - // Second connection should be a simple session resumption. - if ((new RehandshakeFinished().runTest()) != - new RehandshakeFinished().runRehandshake()) { - throw new Exception("Sessions not equivalent"); - } - - System.out.println("Test Passed."); - } - - private void checkResult(SSLEngine engine, SSLEngineResult result, - HandshakeStatus rqdHsStatus, - boolean consumed, boolean produced) throws Exception { - - HandshakeStatus hsStatus = result.getHandshakeStatus(); - - if (hsStatus == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - runnable.run(); - } - hsStatus = engine.getHandshakeStatus(); - } - - if (hsStatus != rqdHsStatus) { - throw new Exception("Required " + rqdHsStatus + - ", got " + hsStatus); - } - - int bc = result.bytesConsumed(); - int bp = result.bytesProduced(); - - if (consumed) { - if (bc <= 0) { - throw new Exception("Should have consumed bytes"); - } - } else { - if (bc > 0) { - throw new Exception("Should not have consumed bytes"); - } - } - - if (produced) { - if (bp <= 0) { - throw new Exception("Should have produced bytes"); - } - } else { - if (bp > 0) { - throw new Exception("Should not have produced bytes"); - } - } - } - - private SSLSession runRehandshake() throws Exception { - - log("\n\n=============================================="); - log("Staring actual test."); - - createSSLEngines(); - createBuffers(); - SSLEngineResult result; - - log("Client's ClientHello"); - checkResult(clientEngine, - clientEngine.wrap(clientOut, cTOs), HandshakeStatus.NEED_UNWRAP, - false, true); - cTOs.flip(); - checkResult(serverEngine, - serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.NEED_WRAP, - true, false); - cTOs.compact(); - - log("Server's ServerHello/ServerHelloDone"); - checkResult(serverEngine, - serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_WRAP, - false, true); - sTOc.flip(); - checkResult(clientEngine, - clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_UNWRAP, - true, false); - sTOc.compact(); - - log("Server's CCS"); - checkResult(serverEngine, - serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_WRAP, - false, true); - sTOc.flip(); - checkResult(clientEngine, - clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_UNWRAP, - true, false); - sTOc.compact(); - - log("Server's FINISHED"); - checkResult(serverEngine, - serverEngine.wrap(serverOut, sTOc), HandshakeStatus.NEED_UNWRAP, - false, true); - sTOc.flip(); - checkResult(clientEngine, - clientEngine.unwrap(sTOc, clientIn), HandshakeStatus.NEED_WRAP, - true, false); - sTOc.compact(); - - log("Client's CCS"); - checkResult(clientEngine, - clientEngine.wrap(clientOut, cTOs), HandshakeStatus.NEED_WRAP, - false, true); - cTOs.flip(); - checkResult(serverEngine, - serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.NEED_UNWRAP, - true, false); - cTOs.compact(); - - log("Client's FINISHED should trigger FINISHED messages all around."); - checkResult(clientEngine, - clientEngine.wrap(clientOut, cTOs), HandshakeStatus.FINISHED, - false, true); - cTOs.flip(); - checkResult(serverEngine, - serverEngine.unwrap(cTOs, serverIn), HandshakeStatus.FINISHED, - true, false); - cTOs.compact(); - - return clientEngine.getSession(); - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private SSLSession runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult clientResult; // results from client's last operation - SSLEngineResult serverResult; // results from server's last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - while (!isEngineClosed(clientEngine) || - !isEngineClosed(serverEngine)) { - - log("================"); - - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - cTOs.flip(); - sTOc.flip(); - - log("----"); - - clientResult = clientEngine.unwrap(sTOc, clientIn); - log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - cTOs.compact(); - sTOc.compact(); - - /* - * After we've transfered all application data between the client - * and server, we close the clientEngine's outbound stream. - * This generates a close_notify handshake message, which the - * server engine receives and responds by closing itself. - */ - if (!dataDone && (clientOut.limit() == serverIn.position()) && - (serverOut.limit() == clientIn.position())) { - - /* - * A sanity check to ensure we got what was sent. - */ - checkTransfer(serverOut, clientIn); - checkTransfer(clientOut, serverIn); - - log("\tClosing clientEngine's *OUTBOUND*..."); - clientEngine.closeOutbound(); - dataDone = true; - } - } - - return clientEngine.getSession(); - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" + - "\t\"getStatus() / getHandshakeStatus()\" +\n" + - "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str + - result.getStatus() + "/" + hsStatus + ", " + - result.bytesConsumed() + "/" + result.bytesProduced() + - " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/SSLEngineBadBufferArrayAccess.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,490 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7031830 - * @summary bad_record_mac failure on TLSv1.2 enabled connection with SSLEngine - * @run main/othervm SSLEngineBadBufferArrayAccess - */ - -/** - * A SSLSocket/SSLEngine interop test case. This is not the way to - * code SSLEngine-based servers, but works for what we need to do here, - * which is to make sure that SSLEngine/SSLSockets can talk to each other. - * SSLEngines can use direct or indirect buffers, and different code - * is used to get at the buffer contents internally, so we test that here. - * - * The test creates one SSLSocket (client) and one SSLEngine (server). - * The SSLSocket talks to a raw ServerSocket, and the server code - * does the translation between byte [] and ByteBuffers that the SSLEngine - * can use. The "transport" layer consists of a Socket Input/OutputStream - * and two byte buffers for the SSLEngines: think of them - * as directly connected pipes. - * - * Again, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * write() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * read() ... ServerHello/Certificate - * write() ... ClientKeyExchange - * write() ... ChangeCipherSpec - * write() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * read() ... ChangeCipherSpec - * read() ... Finished - * - * This particular bug had a problem where byte buffers backed by an - * array didn't offset correctly, and we got bad MAC errors. - */ -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.net.*; -import java.security.*; -import java.nio.*; - -public class SSLEngineBadBufferArrayAccess { - - /* - * Enables logging of the SSL/TLS operations. - */ - private static boolean logging = true; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static boolean debug = false; - private SSLContext sslc; - private SSLEngine serverEngine; // server-side SSLEngine - private SSLSocket sslSocket; // client-side socket - private ServerSocket serverSocket; // server-side Socket, generates the... - private Socket socket; // server-side socket that will read - - private final byte[] serverMsg = "Hi there Client, I'm a Server".getBytes(); - private final byte[] clientMsg = "Hello Server, I'm a Client".getBytes(); - - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - private volatile Exception clientException; - private volatile Exception serverException; - - /* - * For data transport, this example uses local ByteBuffers. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores/trust material. - */ - private static final String pathToStores = "../../../../javax/net/ssl/etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - private static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores - + "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - String [] protocols = new String [] { - "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }; - - for (String protocol : protocols) { - /* - * Run the tests with direct and indirect buffers. - */ - log("Testing " + protocol + ":true"); - new SSLEngineBadBufferArrayAccess(protocol).runTest(true); - - log("Testing " + protocol + ":false"); - new SSLEngineBadBufferArrayAccess(protocol).runTest(false); - } - - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public SSLEngineBadBufferArrayAccess(String protocol) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance(protocol); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Run the test. - * - * Sit in a tight loop, with the server engine calling wrap/unwrap - * regardless of whether data is available or not. We do this until - * we get the application data. Then we shutdown and go to the next one. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest(boolean direct) throws Exception { - boolean serverClose = direct; - - serverSocket = new ServerSocket(0); - int port = serverSocket.getLocalPort(); - Thread thread = createClientThread(port, serverClose); - - socket = serverSocket.accept(); - socket.setSoTimeout(500); - serverSocket.close(); - - createSSLEngine(); - createBuffers(direct); - - try { - boolean closed = false; - - InputStream is = socket.getInputStream(); - OutputStream os = socket.getOutputStream(); - - SSLEngineResult serverResult; // results from last operation - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - byte[] inbound = new byte[8192]; - byte[] outbound = new byte[8192]; - - while (!isEngineClosed(serverEngine)) { - int len = 0; - - // Inbound data - log("================"); - - // Read from the Client side. - try { - len = is.read(inbound); - if (len == -1) { - throw new Exception("Unexpected EOF"); - } - cTOs.put(inbound, 0, len); - } catch (SocketTimeoutException ste) { - // swallow. Nothing yet, probably waiting on us. - } - - cTOs.flip(); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - cTOs.compact(); - - // Outbound data - log("----"); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); - - sTOc.flip(); - - if ((len = sTOc.remaining()) != 0) { - sTOc.get(outbound, 0, len); - os.write(outbound, 0, len); - // Give the other side a chance to process - } - - sTOc.compact(); - - if (!closed && (serverOut.remaining() == 0)) { - closed = true; - - /* - * We'll alternate initiatating the shutdown. - * When the server initiates, it will take one more - * loop, but tests the orderly shutdown. - */ - if (serverClose) { - serverEngine.closeOutbound(); - } - } - - if (closed && isEngineClosed(serverEngine)) { - serverIn.flip(); - - /* - * A sanity check to ensure we got what was sent. - */ - if (serverIn.remaining() != clientMsg.length) { - throw new Exception("Client: Data length error -" + - " IF THIS FAILS, PLEASE REPORT THIS TO THE" + - " SECURITY TEAM. WE HAVE BEEN UNABLE TO" + - " RELIABLY DUPLICATE."); - } - - for (int i = 0; i < clientMsg.length; i++) { - if (clientMsg[i] != serverIn.get()) { - throw new Exception("Client: Data content error -" + - " IF THIS FAILS, PLEASE REPORT THIS TO THE" + - " SECURITY TEAM. WE HAVE BEEN UNABLE TO" + - " RELIABLY DUPLICATE."); - } - } - serverIn.compact(); - } - } - return; - } catch (Exception e) { - serverException = e; - } finally { - socket.close(); - - // Wait for the client to join up with us. - thread.join(); - if (serverException != null) { - throw serverException; - } - if (clientException != null) { - throw clientException; - } - } - } - - /* - * Create a client thread which does simple SSLSocket operations. - * We'll write and read one data packet. - */ - private Thread createClientThread(final int port, - final boolean serverClose) throws Exception { - - Thread t = new Thread("ClientThread") { - - @Override - public void run() { - try { - Thread.sleep(1000); // Give server time to finish setup. - - sslSocket = (SSLSocket) sslc.getSocketFactory(). - createSocket("localhost", port); - OutputStream os = sslSocket.getOutputStream(); - InputStream is = sslSocket.getInputStream(); - - // write(byte[]) goes in one shot. - os.write(clientMsg); - - byte[] inbound = new byte[2048]; - int pos = 0; - - int len; -done: - while ((len = is.read(inbound, pos, 2048 - pos)) != -1) { - pos += len; - // Let the client do the closing. - if ((pos == serverMsg.length) && !serverClose) { - sslSocket.close(); - break done; - } - } - - if (pos != serverMsg.length) { - throw new Exception("Client: Data length error"); - } - - for (int i = 0; i < serverMsg.length; i++) { - if (inbound[i] != serverMsg[i]) { - throw new Exception("Client: Data content error"); - } - } - } catch (Exception e) { - clientException = e; - } - } - }; - t.start(); - return t; - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngine() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.getNeedClientAuth(); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers(boolean direct) { - - SSLSession session = serverEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - if (direct) { - serverIn = ByteBuffer.allocateDirect(appBufferMax + 50); - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - } else { - serverIn = ByteBuffer.allocate(appBufferMax + 50); - cTOs = ByteBuffer.allocate(netBufferMax); - sTOc = ByteBuffer.allocate(netBufferMax); - } - - serverOut = ByteBuffer.wrap(serverMsg); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" - + "\t\"getStatus() / getHandshakeStatus()\" +\n" - + "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str - + result.getStatus() + "/" + hsStatus + ", " - + result.bytesConsumed() + "/" + result.bytesProduced() - + " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,411 +0,0 @@ -/* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 6492872 - * @summary Deadlock in SSLEngine - * @run main/othervm SSLEngineDeadlock - * @author Brad R. Wetmore - */ - -/** - * A SSLEngine usage example which simplifies the presentation - * by removing the I/O and multi-threading concerns. - * - * The test creates two SSLEngines, simulating a client and server. - * The "transport" layer consists two byte buffers: think of them - * as directly connected pipes. - * - * Note, this is a *very* simple example: real code will be much more - * involved. For example, different threading and I/O models could be - * used, transport mechanisms could close unexpectedly, and so on. - * - * When this application runs, notice that several messages - * (wrap/unwrap) pass before any application data is consumed or - * produced. (For more information, please see the SSL/TLS - * specifications.) There may several steps for a successful handshake, - * so it's typical to see the following series of operations: - * - * client server message - * ====== ====== ======= - * wrap() ... ClientHello - * ... unwrap() ClientHello - * ... wrap() ServerHello/Certificate - * unwrap() ... ServerHello/Certificate - * wrap() ... ClientKeyExchange - * wrap() ... ChangeCipherSpec - * wrap() ... Finished - * ... unwrap() ClientKeyExchange - * ... unwrap() ChangeCipherSpec - * ... unwrap() Finished - * ... wrap() ChangeCipherSpec - * ... wrap() Finished - * unwrap() ... ChangeCipherSpec - * unwrap() ... Finished - */ - -import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -import java.lang.management.*; - -public class SSLEngineDeadlock { - - /* - * Enables logging of the SSLEngine operations. - */ - private static boolean logging = false; - - /* - * Enables the JSSE system debugging system property: - * - * -Djavax.net.debug=all - * - * This gives a lot of low-level information about operations underway, - * including specific handshake messages, and might be best examined - * after gaining some familiarity with this application. - */ - private static boolean debug = false; - - private SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - private volatile boolean testDone = false; - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - /* - * Main entry point for this test. - */ - public static void main(String args[]) throws Exception { - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - // Turn off logging, and only output the test iteration to keep - // the noise down. - for (int i = 1; i <= 200; i++) { - if ((i % 5) == 0) { - System.out.println("Test #: " + i); - } - SSLEngineDeadlock test = new SSLEngineDeadlock(); - test.runTest(); - - detectDeadLock(); - } - System.out.println("Test Passed."); - } - - /* - * Create an initialized SSLContext to use for these tests. - */ - public SSLEngineDeadlock() throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; - } - - /* - * Create a thread which simply spins on tasks. This will hopefully - * trigger a deadlock between the wrap/unwrap and the tasks. On our - * slow, single-CPU build machine (sol8), it was very repeatable. - */ - private void doTask() { - Runnable task; - - while (!testDone) { - if ((task = clientEngine.getDelegatedTask()) != null) { - task.run(); - } - if ((task = serverEngine.getDelegatedTask()) != null) { - task.run(); - } - } - } - - /* - * Run the test. - * - * Sit in a tight loop, both engines calling wrap/unwrap regardless - * of whether data is available or not. We do this until both engines - * report back they are closed. - * - * The main loop handles all of the I/O phases of the SSLEngine's - * lifetime: - * - * initial handshaking - * application data transfer - * engine closing - * - * One could easily separate these phases into separate - * sections of code. - */ - private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult clientResult; // results from client's last operation - SSLEngineResult serverResult; // results from server's last operation - - new Thread("SSLEngine Task Dispatcher") { - public void run() { - try { - doTask(); - } catch (Exception e) { - System.err.println("Task thread died...test will hang"); - } - } - }.start(); - - /* - * Examining the SSLEngineResults could be much more involved, - * and may alter the overall flow of the application. - * - * For example, if we received a BUFFER_OVERFLOW when trying - * to write to the output pipe, we could reallocate a larger - * pipe, but instead we wait for the peer to drain it. - */ - while (!isEngineClosed(clientEngine) || - !isEngineClosed(serverEngine)) { - - log("================"); - - clientResult = clientEngine.wrap(clientOut, cTOs); - log("client wrap: ", clientResult); - - serverResult = serverEngine.wrap(serverOut, sTOc); - log("server wrap: ", serverResult); - - cTOs.flip(); - sTOc.flip(); - - log("----"); - - clientResult = clientEngine.unwrap(sTOc, clientIn); - log("client unwrap: ", clientResult); - - serverResult = serverEngine.unwrap(cTOs, serverIn); - log("server unwrap: ", serverResult); - - cTOs.compact(); - sTOc.compact(); - - /* - * After we've transfered all application data between the client - * and server, we close the clientEngine's outbound stream. - * This generates a close_notify handshake message, which the - * server engine receives and responds by closing itself. - */ - if (!dataDone && (clientOut.limit() == serverIn.position()) && - (serverOut.limit() == clientIn.position())) { - - /* - * A sanity check to ensure we got what was sent. - */ - checkTransfer(serverOut, clientIn); - checkTransfer(clientOut, serverIn); - - log("\tClosing clientEngine's *OUTBOUND*..."); - clientEngine.closeOutbound(); - dataDone = true; - } - } - testDone = true; - } - - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - - /* - * Detect dead lock - */ - private static void detectDeadLock() throws Exception { - ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); - long[] threadIds = threadBean.findDeadlockedThreads(); - if (threadIds != null && threadIds.length != 0) { - for (long id : threadIds) { - ThreadInfo info = - threadBean.getThreadInfo(id, Integer.MAX_VALUE); - System.out.println("Deadlocked ThreadInfo: " + info); - } - throw new Exception("Found Deadlock!"); - } - } - - /* - * Logging code - */ - private static boolean resultOnce = true; - - private static void log(String str, SSLEngineResult result) { - if (!logging) { - return; - } - if (resultOnce) { - resultOnce = false; - System.out.println("The format of the SSLEngineResult is: \n" + - "\t\"getStatus() / getHandshakeStatus()\" +\n" + - "\t\"bytesConsumed() / bytesProduced()\"\n"); - } - HandshakeStatus hsStatus = result.getHandshakeStatus(); - log(str + - result.getStatus() + "/" + hsStatus + ", " + - result.bytesConsumed() + "/" + result.bytesProduced() + - " bytes"); - if (hsStatus == HandshakeStatus.FINISHED) { - log("\t...ready for application data"); - } - } - - private static void log(String str) { - if (logging) { - System.out.println(str); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/AsyncSSLSocketClose.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// -// The test may timeout occasionally on heavy loaded system because -// there are lot of TLS transactions involved. Frequent timeout(s) should -// be analyzed further. -// - -/* - * @test - * @bug 6447412 - * @summary Issue with socket.close() for ssl sockets when poweroff on - * other system - * @run main/othervm AsyncSSLSocketClose - */ - -import javax.net.ssl.*; -import java.io.*; - -public class AsyncSSLSocketClose implements Runnable -{ - SSLSocket socket; - SSLServerSocket ss; - - // Where do we find the keystores? - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - public static void main(String[] args) { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - new AsyncSSLSocketClose(); - } - - public AsyncSSLSocketClose() { - try { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - ss = (SSLServerSocket) sslssf.createServerSocket(0); - - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - socket = (SSLSocket)sslsf.createSocket("localhost", - ss.getLocalPort()); - SSLSocket serverSoc = (SSLSocket) ss.accept(); - ss.close(); - - (new Thread(this)).start(); - serverSoc.startHandshake(); - - try { - Thread.sleep(5000); - } catch (Exception e) { - e.printStackTrace(); - } - - socket.setSoLinger(true, 10); - System.out.println("Calling Socket.close"); - socket.close(); - System.out.println("ssl socket get closed"); - System.out.flush(); - - } catch (IOException e) { - e.printStackTrace(); - } - - } - - // block in write - public void run() { - try { - byte[] ba = new byte[1024]; - for (int i=0; i<ba.length; i++) - ba[i] = 0x7A; - - OutputStream os = socket.getOutputStream(); - int count = 0; - while (true) { - count += ba.length; - System.out.println(count + " bytes to be written"); - os.write(ba); - System.out.println(count + " bytes written"); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - -}
--- a/test/sun/security/ssl/SSLSocketImpl/CheckMethods.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4791676 - * @summary various pass through methods missing in SSLSocketImpl - */ -import java.net.*; -import java.util.*; -import java.lang.reflect.*; -import com.sun.net.ssl.internal.ssl.*; - -public class CheckMethods { - static boolean debug = false; - static class MethodSignature { - String name; - Class[] paramTypes; - MethodSignature(String name, Class[] paramTypes) { - this.name = name; - this.paramTypes = paramTypes; - } - - public boolean equals(Object obj) { - if (debug) { - System.out.println("comparing " + this + " against: " + obj); - } - if (!(obj instanceof MethodSignature)) { - if (debug) - System.out.println(false); - return false; - } - MethodSignature ms = (MethodSignature) obj; - Class[] types = ms.paramTypes; - try { - for (int i = 0; i < types.length; i++) { - if (!types[i].equals(paramTypes[i])) { - if (debug) - System.out.println(false); - return false; - } - } - } catch (Exception e) { - if (debug) - System.out.println(false); - return false; - } - boolean result = this.name.equals(ms.name); - if (debug) - System.out.println(result); - return result; - } - - public String toString() { - StringBuffer sb = new StringBuffer(name + "("); - for (int i = 0; i < paramTypes.length; i++) { - sb.append(paramTypes[i].getName() + ","); - if (i == (paramTypes.length - 1)) - sb.deleteCharAt(sb.length() - 1); - } - sb.append(")"); - return sb.toString(); - } - } - - // check that SSLSocket contains all public and protected - // methods defined in Socket - public static void main(String[] args) throws Exception { - ArrayList allMethods = new ArrayList( - Arrays.asList(Socket.class.getDeclaredMethods())); - - ArrayList allMethodSignatures = new ArrayList(); - for (Iterator itr = allMethods.iterator(); itr.hasNext();) { - Method m = (Method) itr.next(); - // don't include static and private methods - if (!Modifier.isStatic(m.getModifiers()) && - (Modifier.isPublic(m.getModifiers()) || - Modifier.isProtected(m.getModifiers()))) { - allMethodSignatures.add( new MethodSignature(m.getName(), - m.getParameterTypes())); - } - } - - // testing Socket - Class sslSI = Class.forName( - "sun.security.ssl.SSLSocketImpl"); - Class baseSSLSI = Class.forName( - "sun.security.ssl.BaseSSLSocketImpl"); - - ArrayList sslSocketMethods = - new ArrayList(Arrays.asList(sslSI.getDeclaredMethods())); - - sslSocketMethods.addAll( new ArrayList( - Arrays.asList(baseSSLSI.getDeclaredMethods()))); - - ArrayList sslSocketMethodSignatures = new ArrayList(); - for (Iterator itr = sslSocketMethods.iterator(); itr.hasNext();) { - Method m = (Method) itr.next(); - if (!Modifier.isStatic(m.getModifiers())) { - sslSocketMethodSignatures.add( - new MethodSignature(m.getName(), - m.getParameterTypes())); - } - } - - if (!sslSocketMethodSignatures.containsAll(allMethodSignatures)) { - throw new RuntimeException( - "Method definition test failed on SSLSocketImpl"); - } - - // testing for non static public field - ArrayList allFields = - new ArrayList(Arrays.asList(Socket.class.getFields())); - - for (Iterator itr = allFields.iterator(); itr.hasNext();) { - Field f = (Field) itr.next(); - if (!Modifier.isStatic(f.getModifiers())) { - throw new RuntimeException("Non static Public fields" + - " declared in superclasses"); - } - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/ClientTimeout.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4836493 - * @summary Socket timeouts for SSLSockets causes data corruption. - * @run main/othervm ClientTimeout - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -import java.io.*; -import java.net.*; -import java.util.*; -import java.security.*; -import javax.net.ssl.*; - -public class ClientTimeout { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - - /* - * define the rhythm of timeout exception - */ - static boolean rhythm = true; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - sslSocket.startHandshake(); - - // transfer a file to client. - String transFilename = - System.getProperty("test.src", "./") + "/" + - this.getClass().getName() + ".java"; - MessageDigest md = MessageDigest.getInstance("SHA"); - DigestInputStream transIns = new DigestInputStream( - new FileInputStream(transFilename), md); - - byte[] bytes = new byte[2000]; - int i = 0; - while (true) { - // reset the cycle - if (i >= bytes.length) { - i = 0; - } - - int length = 0; - if ((length = transIns.read(bytes, 0, i++)) == -1) { - break; - } else { - sslOS.write(bytes, 0, length); - sslOS.flush(); - - if (i % 3 == 0) { - Thread.sleep(300); // Stall past the timeout... - } - } - } - serverDigest = md.digest(); - transIns.close(); - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - boolean caught = false; - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - Socket baseSocket = new Socket("localhost", serverPort) { - MyInputStream ins = null; - - public InputStream getInputStream() throws IOException { - if (ins != null) { - return ins; - } else { - ins = new MyInputStream(super.getInputStream()); - return ins; - } - } - }; - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket(baseSocket, "localhost", serverPort, true); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - // handshaking - sslSocket.setSoTimeout(100); // The stall timeout. - while (true) { - try { - rhythm = true; - sslSocket.startHandshake(); - break; - } catch (SocketTimeoutException e) { - System.out.println("Handshaker exception: " - + e.getMessage()); - } - } - - // read application data from server - MessageDigest md = MessageDigest.getInstance("SHA"); - DigestInputStream transIns = new DigestInputStream(sslIS, md); - byte[] bytes = new byte[2000]; - while (true) { - try { - rhythm = true; - - while (transIns.read(bytes, 0, 17) != -1) { - rhythm = true; - } - break; - } catch (SocketTimeoutException e) { - System.out.println("InputStream Exception: " - + e.getMessage()); - } - } - // Wait for server to get ready. - while (serverDigest == null) { - Thread.sleep(20); - } - - byte[] cliDigest = md.digest(); - if (!Arrays.equals(cliDigest, serverDigest)) { - throw new Exception("Application data trans error"); - } - - transIns.close(); - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - static class MyInputStream extends InputStream { - InputStream ins = null; - - public MyInputStream(InputStream ins) { - this.ins = ins; - } - - public int read() throws IOException { - return read(new byte[1], 0, 1); - } - - public int read(byte[] data, int offset, int len) throws IOException { - if (!ClientTimeout.rhythm) { - throw new SocketTimeoutException( - "Throwing a timeout exception"); - } - ClientTimeout.rhythm = false; - return ins.read(data, offset, len); - } - } - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - volatile byte[] serverDigest = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ClientTimeout(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ClientTimeout() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - System.err.println(e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/InvalidateServerSessionRenegotiate.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4403428 - * @summary Invalidating JSSE session on server causes SSLProtocolException - * @run main/othervm InvalidateServerSessionRenegotiate - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class InvalidateServerSessionRenegotiate implements - HandshakeCompletedListener { - - static byte handshakesCompleted = 0; - - /* - * Define what happens when handshaking is completed - */ - public void handshakeCompleted(HandshakeCompletedEvent event) { - synchronized (this) { - handshakesCompleted++; - System.out.println("Session: " + event.getSession().toString()); - System.out.println("Seen handshake completed #" + - handshakesCompleted); - } - } - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.addHandshakeCompletedListener(this); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - System.out.println("invalidating"); - sslSocket.getSession().invalidate(); - System.out.println("starting new handshake"); - sslSocket.startHandshake(); - - for (int i = 0; i < 10; i++) { - System.out.println("sending/receiving data, iteration: " + i); - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new InvalidateServerSessionRenegotiate(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - InvalidateServerSessionRenegotiate() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - - /* - * Give the Handshaker Thread a chance to run - */ - Thread.sleep(1000); - - synchronized (this) { - if (handshakesCompleted != 2) { - throw new Exception("Didn't see 2 handshake completed events."); - } - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/NoImpactServerRenego.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7188658 - * @summary Add possibility to disable client initiated renegotiation - * @run main/othervm - * -Djdk.tls.rejectClientInitiatedRenegotiation=true NoImpactServerRenego - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class NoImpactServerRenego implements - HandshakeCompletedListener { - - static byte handshakesCompleted = 0; - - /* - * Define what happens when handshaking is completed - */ - public void handshakeCompleted(HandshakeCompletedEvent event) { - synchronized (this) { - handshakesCompleted++; - System.out.println("Session: " + event.getSession().toString()); - System.out.println("Seen handshake completed #" + - handshakesCompleted); - } - } - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.addHandshakeCompletedListener(this); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - System.out.println("invalidating"); - sslSocket.getSession().invalidate(); - System.out.println("starting new handshake"); - sslSocket.startHandshake(); - - for (int i = 0; i < 10; i++) { - System.out.println("sending/receiving data, iteration: " + i); - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new NoImpactServerRenego(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - NoImpactServerRenego() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - - /* - * Give the Handshaker Thread a chance to run - */ - Thread.sleep(1000); - - synchronized (this) { - if (handshakesCompleted != 2) { - throw new Exception("Didn't see 2 handshake completed events."); - } - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/NonAutoClose.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,377 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4404399 - * @summary When a layered SSL socket is closed, it should wait for close_notify - * @run main/othervm NonAutoClose - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.ServerSocket; -import java.net.Socket; -import javax.net.ssl.*; -import java.security.cert.X509Certificate; -import java.security.cert.CertificateException; - - -public class NonAutoClose { - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // private final static String pathToStores = "./etc"; - private final static String pathToStores = "../../../../javax/net/ssl/etc"; - private final static String keyStoreFile = "keystore"; - private final static String trustStoreFile = "truststore"; - private final static String passwd = "passphrase"; - private final static char[] cpasswd = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - private final static boolean DEBUG = false; - private final static boolean VERBOSE = false; - private final static int NUM_ITERATIONS = 10; - private final static int PLAIN_SERVER_VAL = 1; - private final static int PLAIN_CLIENT_VAL = 2; - private final static int TLS_SERVER_VAL = 3; - private final static int TLS_CLIENT_VAL = 4; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - void expectValue(int got, int expected, String msg) throws IOException { - if (VERBOSE) { - System.out.println(msg + ": read (" + got + ")"); - } - if (got != expected) { - throw new IOException(msg + ": read (" + got - + ") but expecting(" + expected + ")"); - } - } - - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - - void doServerSide() throws Exception { - if (VERBOSE) { - System.out.println("Starting server"); - } - - /* - * Setup the SSL stuff - */ - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - ServerSocket serverSocket = new ServerSocket(SERVER_PORT); - - SERVER_PORT = serverSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - Socket plainSocket = serverSocket.accept(); - InputStream is = plainSocket.getInputStream(); - OutputStream os = plainSocket.getOutputStream(); - - expectValue(is.read(), PLAIN_CLIENT_VAL, "Server"); - - os.write(PLAIN_SERVER_VAL); - os.flush(); - - for (int i = 1; i <= NUM_ITERATIONS; i++) { - if (VERBOSE) { - System.out.println("================================="); - System.out.println("Server Iteration #" + i); - } - - SSLSocket ssls = (SSLSocket) sslsf.createSocket(plainSocket, - SERVER_NAME, plainSocket.getPort(), false); - - ssls.setUseClientMode(false); - InputStream sslis = ssls.getInputStream(); - OutputStream sslos = ssls.getOutputStream(); - - expectValue(sslis.read(), TLS_CLIENT_VAL, "Server"); - - sslos.write(TLS_SERVER_VAL); - sslos.flush(); - - sslis.close(); - sslos.close(); - ssls.close(); - - if (VERBOSE) { - System.out.println("TLS socket is closed"); - } - } - - expectValue(is.read(), PLAIN_CLIENT_VAL, "Server"); - - os.write(PLAIN_SERVER_VAL); - os.flush(); - - is.close(); - os.close(); - plainSocket.close(); - - if (VERBOSE) { - System.out.println("Server plain socket is closed"); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - private void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - if (VERBOSE) { - System.out.println("Starting client"); - } - - /* - * Setup the SSL stuff - */ - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - Socket plainSocket = new Socket(SERVER_NAME, SERVER_PORT); - InputStream is = plainSocket.getInputStream(); - OutputStream os = plainSocket.getOutputStream(); - - os.write(PLAIN_CLIENT_VAL); - os.flush(); - - expectValue(is.read(), PLAIN_SERVER_VAL, "Client"); - - for (int i = 1; i <= NUM_ITERATIONS; i++) { - if (VERBOSE) { - System.out.println("==================================="); - System.out.println("Client Iteration #" + i); - } - - SSLSocket ssls = (SSLSocket) sslsf.createSocket(plainSocket, - SERVER_NAME, plainSocket.getPort(), false); - - ssls.setUseClientMode(true); - - InputStream sslis = ssls.getInputStream(); - OutputStream sslos = ssls.getOutputStream(); - - sslos.write(TLS_CLIENT_VAL); - sslos.flush(); - - expectValue(sslis.read(), TLS_SERVER_VAL, "Client"); - - sslis.close(); - sslos.close(); - ssls.close(); - - if (VERBOSE) { - System.out.println("Client TLS socket is closed"); - } - } - - os.write(PLAIN_CLIENT_VAL); - os.flush(); - - expectValue(is.read(), PLAIN_SERVER_VAL, "Client"); - - is.close(); - os.close(); - plainSocket.close(); - - if (VERBOSE) { - System.out.println("Client plain socket is closed"); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - private volatile int SERVER_PORT = 0; - private final static String SERVER_NAME = "localhost"; - - private volatile Exception serverException = null; - private volatile Exception clientException = null; - - private final static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private final static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - - // Used for running test standalone - public static void main(String[] args) throws Exception { - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (DEBUG) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new NonAutoClose(); - } - - private Thread clientThread = null; - private Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - NonAutoClose() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.err.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.err.print("Client Exception:"); - throw clientException; - } - } - - private void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - private void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/RejectClientRenego.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 7188658 - * @summary Add possibility to disable client initiated renegotiation - * @run main/othervm RejectClientRenego true - * @run main/othervm RejectClientRenego false - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class RejectClientRenego implements - HandshakeCompletedListener { - - static byte handshakesCompleted = 0; - - /* - * Define what happens when handshaking is completed - */ - public void handshakeCompleted(HandshakeCompletedEvent event) { - synchronized (this) { - handshakesCompleted++; - System.out.println("Session: " + event.getSession().toString()); - System.out.println("Seen handshake completed #" + - handshakesCompleted); - } - } - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.addHandshakeCompletedListener(this); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - try { - for (int i = 0; i < 10; i++) { - System.out.println("sending/receiving data, iteration: " + i); - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - throw new Exception("Not reject client initialized renegotiation"); - } catch (IOException ioe) { - System.out.println("Got the expected exception"); - } finally { - sslSocket.close(); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - if (!isAbbreviated) { - System.out.println("invalidating"); - sslSocket.getSession().invalidate(); - } - System.out.println("starting new handshake"); - sslSocket.startHandshake(); - - try { - for (int i = 0; i < 10; i++) { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - throw new Exception("Not reject client initialized renegotiation"); - } catch (IOException ioe) { - System.out.println("Got the expected exception"); - } finally { - sslSocket.close(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - // Is it abbreviated handshake? - private static boolean isAbbreviated = false; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - // reject client initialized SSL renegotiation. - System.setProperty( - "jdk.tls.rejectClientInitiatedRenegotiation", "true"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - // Is it abbreviated handshake? - if ("true".equals(args[0])) { - isAbbreviated = true; - } - - /* - * Start the tests. - */ - new RejectClientRenego(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - RejectClientRenego() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.out.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.out.print("Client Exception:"); - throw clientException; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/SSLSocketImplThrowsWrongExceptions.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4361124 4325806 - * @summary SSLServerSocket isn't throwing exceptions when negotiations are - * failing & java.net.SocketException: occures in Auth and clientmode - * @run main/othervm SSLSocketImplThrowsWrongExceptions - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @author Brad Wetmore - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -public class SSLSocketImplThrowsWrongExceptions { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - - /* - * Define the server side of the test. - */ - void doServerSide() throws Exception { - System.out.println("starting Server"); - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - System.out.println("got server socket"); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - try { - System.out.println("Server socket accepting..."); - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - System.out.println("Server starting handshake"); - sslSocket.startHandshake(); - throw new Exception("Handshake was successful"); - } catch (SSLException e) { - /* - * Caught the right Exeption. Swallow it. - */ - System.out.println("Server reported the right exception"); - System.out.println(e.toString()); - } catch (Exception e) { - /* - * Caught the wrong exception. Rethrow it. - */ - System.out.println("Server reported the wrong exception"); - throw e; - } - - } - - /* - * Define the client side of the test. - */ - void doClientSide() throws Exception { - - System.out.println(" Client starting"); - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - try { - System.out.println(" Client creating socket"); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - System.out.println(" Client starting handshake"); - sslSocket.startHandshake(); - throw new Exception("Handshake was successful"); - } catch (SSLException e) { - /* - * Caught the right Exception. Swallow it. - */ - System.out.println(" Client reported correct exception"); - System.out.println(" " + e.toString()); - } catch (Exception e) { - /* - * Caught the wrong exception. Rethrow it. - */ - System.out.println(" Client reported the wrong exception"); - throw e; - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SSLSocketImplThrowsWrongExceptions(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketImplThrowsWrongExceptions () throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.out.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.out.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/SSLSocketImpl/SetClientMode.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 6223624 - * @summary SSLSocket.setUseClientMode() fails to throw expected - * IllegalArgumentException - * @run main/othervm SetClientMode - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -/* - * Attempts to replicate a TCK test failure which creates SSLServerSockets - * and then runs client threads which connect and start handshaking. Once - * handshaking is begun the server side attempts to invoke - * SSLSocket.setUseClientMode() on one or the other of the ends of the - * connection, expecting an IllegalArgumentException. - * - * If the server side of the connection tries setUseClientMode() we - * see the expected exception. If the setting is tried on the - * client side SSLSocket, we do *not* see the exception, except - * occasionally on the very first iteration. - */ - -import java.io.*; -import java.lang.*; -import java.net.*; -import javax.net.ssl.*; -import java.security.*; -import java.security.cert.*; - -public class SetClientMode { - private static String[] algorithms = {"TLS", "SSL", "SSLv3", "TLS"}; - volatile int serverPort = 0; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - - public SetClientMode() { - // trivial constructor - } - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - new SetClientMode().run(); - } - - public void run() throws Exception { - for (int i = 0; i < algorithms.length; i++) { - testCombo( algorithms[i] ); - } - } - - public void testCombo(String algorithm) throws Exception { - Exception modeException = null ; - - // Create a server socket - SSLServerSocketFactory ssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - SSLServerSocket serverSocket = - (SSLServerSocket)ssf.createServerSocket(serverPort); - serverPort = serverSocket.getLocalPort(); - - // Create a client socket - SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault(); - SSLSocket clientSocket = (SSLSocket)sf.createSocket( - InetAddress.getLocalHost(), - serverPort ); - - // Create a client which will use the SSLSocket to talk to the server - SocketClient client = new SocketClient(clientSocket); - - // Start the client and then accept any connection - client.start(); - - SSLSocket connectedSocket = (SSLSocket)serverSocket.accept(); - - // force handshaking to complete - connectedSocket.getSession(); - - try { - // Now try invoking setClientMode() on one - // or the other of our two sockets. We expect - // to see an IllegalArgumentException because - // handshaking has begun. - clientSocket.setUseClientMode(false); - - modeException = new Exception("no IllegalArgumentException"); - } catch (IllegalArgumentException iae) { - System.out.println("succeeded, we can't set the client mode"); - } catch (Exception e) { - modeException = e; - } finally { - // Shut down. - connectedSocket.close(); - serverSocket.close(); - - if (modeException != null) { - throw modeException; - } - } - - return; - } - - // A thread-based client which does nothing except - // start handshaking on the socket it's given. - class SocketClient extends Thread { - SSLSocket clientsideSocket; - Exception clientException = null; - boolean done = false; - - public SocketClient( SSLSocket s ) { - clientsideSocket = s; - } - - public void run() { - try { - clientsideSocket.startHandshake(); - - // If we were to invoke setUseClientMode() - // here, the expected exception will happen. - //clientsideSocket.getSession(); - //clientsideSocket.setUseClientMode( false ); - } catch ( Exception e ) { - e.printStackTrace(); - clientException = e; - } finally { - done = true; - try { - clientsideSocket.close(); - } catch ( IOException e ) { - // eat it - } - } - return; - } - - boolean isDone() { - return done; - } - - Exception getException() { - return clientException; - } - } -}
--- a/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 4392475 - * @summary Calling setWantClientAuth(true) disables anonymous suites - * @run main/othervm/timeout=180 AnonCipherWithWantClientAuth - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.security.Security; - -public class AnonCipherWithWantClientAuth { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - String ciphers[]={"SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"}; - sslServerSocket.setEnabledCipherSuites(ciphers); - sslServerSocket.setWantClientAuth(true); - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - String ciphers[] = {"SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"}; - sslSocket.setEnabledCipherSuites(ciphers); - sslSocket.setUseClientMode(true); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - // reset security properties to make sure that the algorithms - // and keys used in this test are not disabled. - Security.setProperty("jdk.tls.disabledAlgorithms", ""); - Security.setProperty("jdk.certpath.disabledAlgorithms", ""); - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new AnonCipherWithWantClientAuth(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - AnonCipherWithWantClientAuth () throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/ServerHandshaker/GetPeerHostClient.java Tue Aug 25 16:27:54 2020 -0300 +++ b/test/sun/security/ssl/ServerHandshaker/GetPeerHostClient.java Tue Aug 25 18:03:27 2020 +0300 @@ -31,7 +31,6 @@ import java.net.*; import java.io.*; import javax.net.ssl.*; -import com.sun.net.ssl.*; class GetPeerHostClient extends Thread {
--- a/test/sun/security/ssl/SessionIdCollisionTest.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2019, Red Hat Inc. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.lang.reflect.Constructor; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * @test - * @bug 8203190 - * @summary Manual test to verify number of collisions in - * sun.security.ssl.SessionId.hashCode() - * @run main/manual SessionIdCollisionTest 100 20480 10000000 - */ - -/** - * - * Notes: - * - This is a manual test, not run automatically. - * - New default value of javax.net.ssl.sessionCacheSize in JDK 12+ is 20480 - * - According to JDK-8210985 24 hours expired cache may exceed several million - * entries = > 10_000_000 - * - * Example usage: java SessionIdCollissionTest 100 20480 10000000 - * - * Expected outcome of running the test is to see fewer collisions and, more - * importantly fewer elements in buckets when there are collisions. See: - * http://mail.openjdk.java.net/pipermail/jdk8u-dev/2019-May/009345.html - * - */ -public class SessionIdCollisionTest { - - private List<Integer> prepareHashCodes(int total) throws Exception { - Class<?> sessionIdClass = Class.forName("sun.security.ssl.SessionId"); - Constructor<?> c = sessionIdClass.getDeclaredConstructor(byte[].class); - c.setAccessible(true); - // case of rejoinable session ids generates 32 random bytes - byte[] sessionIdBytes = new byte[32]; - List<Integer> hashCodes = new ArrayList<>(); - for (int i = 0; i < total; i++) { - SecureRandom random = new SecureRandom(); - random.nextBytes(sessionIdBytes); - Object sessionId = c.newInstance(sessionIdBytes); - int hashCode = sessionId.hashCode(); - hashCodes.add(hashCode); - } - return hashCodes; - } - - private void printSummary(boolean withDistribution, - List<Integer> hashCodes) throws Exception { - final int bound = hashCodes.size(); - Collections.sort(hashCodes); - int collisions = 0; - Map<Integer, List<Integer>> collCountsReverse = new HashMap<>(); - for (int i = 0; i < bound - 1; i++) { - int oldval = hashCodes.get(i); - int nextval = hashCodes.get(i+1); - if (oldval == nextval) { - collisions++; - if (i == bound - 2) { // last elements - updateCollCountsReverse(collisions, collCountsReverse, oldval); - } - } else { - updateCollCountsReverse(collisions, collCountsReverse, oldval); - collisions = 0; - if (i == bound - 2) { // last elements - updateCollCountsReverse(collisions, collCountsReverse, nextval); - } - } - } - if (withDistribution) { - System.out.println("---- distribution ----"); - } - int collCount = 0; - int maxLength = 0; - List<Integer> sorted = new ArrayList<>(collCountsReverse.size()); - sorted.addAll(collCountsReverse.keySet()); - Collections.sort(sorted); - for (Integer coll: sorted) { - List<Integer> hc = collCountsReverse.get(coll); - if (withDistribution) { - System.out.printf("Hashcodes with %02d collisions | " + - "hashCodes: %s\n", coll, hc.toString()); - } - collCount += coll * hc.size(); - if (coll > maxLength) { - maxLength = coll; - } - } - if (withDistribution) { - System.out.println("---- distribution ----"); - } - System.out.println("Total number of collisions: " + collCount); - if (collCount > 0) { - System.out.println("Max length of collision list over all buckets: " + - maxLength); - } - } - - private void updateCollCountsReverse(int collisions, - Map<Integer, List<Integer>> reverse, int val) { - List<Integer> hc = reverse.get(collisions); - if (hc == null) { - hc = new ArrayList<>(); - hc.add(val); - reverse.put(collisions, hc); - } else { - hc.add(val); - } - } - - public void doCollissionTest(int total) throws Exception { - System.out.println("Collision test for " + total + " sessions:"); - System.out.println("------------------------------------------------"); - List<Integer> hashcodes = prepareHashCodes(total); - printSummary(false, hashcodes); - System.out.println(); - } - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("java " + SessionIdCollisionTest.class.getSimpleName() + - "<num-sessions> [<num-sessions> ...]"); - System.exit(1); - } - SessionIdCollisionTest collTest = new SessionIdCollisionTest(); - for (int i = 0; i < args.length; i++) { - int total = Integer.parseInt(args[i]); - collTest.doCollissionTest(total); - } - } - -}
--- a/test/sun/security/ssl/SocketCreation/SocketCreation.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,511 +0,0 @@ -/* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4414843 - * @summary This test tries all the different ways in which an SSL - * connection can be established to exercise different SSLSocketImpl - * constructors. - * @run main/othervm/timeout=300 SocketCreation - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; - -/** - * This test has been adapted from JSSEClientServerTemplate.java. It runs - * the client and server multiple times while it iterates through the - * different ways in which an SSL connection can be established. - * - * The meat of this test is contained in doClientSide() and - * doServerSide(). The loop is contained in the constructor - * SocketCreation(). - */ -public class SocketCreation { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Accepts a connection from a client and exchanges an int with it. The - * connection can be established in one of three different ways: - * 1. As a regular SSL server socket - * 2. As an SSL server socket that is first unbound - * 3. As an SSL socket layered over a regular TCP/IP socket - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide(int style) throws Exception { - - Socket sslSocket = null; - - // Change the for loop in SocketCreation() if you add more cases - switch (style) { - case 0: - sslSocket = acceptNormally0(); - break; - case 1: - sslSocket = acceptNormally1(); - break; - case 2: - sslSocket = acceptNormally2(); - break; - case 3: - sslSocket = acceptUnbound(); - break; - case 4: - sslSocket = acceptLayered(); - break; - default: - throw new Exception("Incorrectly written test for server side!"); - } - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - System.out.println("Server read: " + sslIS.read()); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - } - - private Socket acceptNormally0() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - - System.out.println("Server: Will call createServerSocket(int)"); - ServerSocket sslServerSocket = sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - System.out.println("Server: Will accept on SSL server socket..."); - - serverReady = true; - - Socket sslSocket = sslServerSocket.accept(); - sslServerSocket.close(); - return sslSocket; - } - - private Socket acceptNormally1() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - - System.out.println("Server: Will call createServerSocket(int, int)"); - ServerSocket sslServerSocket = sslssf.createServerSocket(serverPort, - 1); - serverPort = sslServerSocket.getLocalPort(); - - System.out.println("Server: Will accept on SSL server socket..."); - - serverReady = true; - - Socket sslSocket = sslServerSocket.accept(); - sslServerSocket.close(); - return sslSocket; - } - - private Socket acceptNormally2() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - - System.out.println("Server: Will call createServerSocket(int, " + - " int, InetAddress)"); - ServerSocket sslServerSocket = sslssf.createServerSocket(serverPort, - 1, - InetAddress.getByName("localhost")); - serverPort = sslServerSocket.getLocalPort(); - - System.out.println("Server: Will accept on SSL server socket..."); - - serverReady = true; - - Socket sslSocket = sslServerSocket.accept(); - sslServerSocket.close(); - return sslSocket; - } - - private Socket acceptUnbound() throws Exception { - - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - - System.out.println("Server: Will create unbound SSL server socket..."); - - ServerSocket sslServerSocket = sslssf.createServerSocket(); - - if (sslServerSocket.isBound()) - throw new Exception("Server socket is already bound!"); - - System.out.println("Server: Will bind SSL server socket to port " + - serverPort + "..."); - - sslServerSocket.bind(new java.net.InetSocketAddress(serverPort)); - - if (!sslServerSocket.isBound()) - throw new Exception("Server socket is not bound!"); - - serverReady = true; - - System.out.println("Server: Will accept on SSL server socket..."); - Socket sslSocket = sslServerSocket.accept(); - sslServerSocket.close(); - return sslSocket; - } - - private Socket acceptLayered() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Server: Will create normal server socket bound" - + " to port " + serverPort + "..."); - - ServerSocket ss = new ServerSocket(serverPort); - serverPort = ss.getLocalPort(); - System.out.println("Server: Will accept on server socket..."); - serverReady = true; - Socket s = ss.accept(); - ss.close(); - System.out.println("Server: Will layer SSLSocket on top of" + - " server socket..."); - SSLSocket sslSocket = - (SSLSocket) sslsf.createSocket(s, - s.getInetAddress().getHostName(), - s.getPort(), - true); - sslSocket.setUseClientMode(false); - - return sslSocket; - } - - /* - * Connects to a server and exchanges an int with it. The - * connection can be established in one of three different ways: - * 1. As a regular SSL socket - * 2. As an SSL socket that is first unconnected - * 3. As an SSL socket layered over a regular TCP/IP socket - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide(int style) throws Exception { - - Socket sslSocket = null; - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - // Change the for loop in SocketCreation() if you add more cases - switch (style) { - case 0: - sslSocket = connectNormally0(); - break; - case 1: - sslSocket = connectNormally1(); - break; - case 2: - sslSocket = connectNormally2(); - break; - case 3: - sslSocket = connectNormally3(); - break; - case 4: - sslSocket = connectUnconnected(); - break; - case 5: - sslSocket = connectLayered(); - break; - default: - throw new Exception("Incorrectly written test for client side!"); - } - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - System.out.println("Client read: " + sslIS.read()); - - sslSocket.close(); - } - - private Socket connectNormally0() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will call createSocket(String, int)"); - return sslsf.createSocket("localhost", serverPort); - } - - private Socket connectNormally1() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will call createSocket(InetAddress, int)"); - return sslsf.createSocket(InetAddress.getByName("localhost"), - serverPort); - } - - private Socket connectNormally2() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will call createSocket(String," + - " int, InetAddress, int)"); - return sslsf.createSocket("localhost", serverPort, - InetAddress.getByName("localhost"), - 0); - } - - private Socket connectNormally3() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will call createSocket(InetAddress," + - " int, InetAddress, int)"); - return sslsf.createSocket(InetAddress.getByName("localhost"), - serverPort, - InetAddress.getByName("localhost"), - 0); - } - - private Socket connectUnconnected() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will call createSocket()"); - Socket sslSocket = sslsf.createSocket(); - - if (sslSocket.isConnected()) - throw new Exception("Client socket is already connected!"); - - System.out.println("Client: Will connect to server on port " + - serverPort + "..."); - sslSocket.connect(new java.net.InetSocketAddress("localhost", - serverPort)); - - if (!sslSocket.isConnected()) - throw new Exception("Client socket is not connected!"); - - return sslSocket; - } - - private Socket connectLayered() throws Exception { - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - - System.out.println("Client: Will connect to server on port " + - serverPort + "..."); - Socket s = new Socket("localhost", serverPort); - - System.out.println("Client: Will layer SSL socket on top..."); - return sslsf.createSocket(s, "localhost", serverPort, true); - - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new SocketCreation(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Performs a loop where each iteration establishes one client-server - * connection using a particular way of socket creation. There are - * three ways in each side can create a socket: - * 1. Normal (The client has 4 variations of this and the server 3) - * 2. Unbound/Unconnected - * 3. Layered - * Each side goes through all three of them giving us a total of 5x6 - * possibilites. - */ - SocketCreation() throws Exception { - - for (int serverStyle = 0; serverStyle < 5; serverStyle++) { - System.out.println("-------------------------------------"); - for (int clientStyle = 0; clientStyle < 6; clientStyle++) { - - serverReady = false; - - startServer(separateServerThread, serverStyle); - startClient(!separateServerThread, clientStyle); - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - System.out.println(); - } - } - } - - void startServer(boolean newThread, final int style) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(style); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..." + e); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(style); - } - } - - void startClient(boolean newThread, final int style) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(style); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(style); - } - } -}
--- a/test/sun/security/ssl/X509TrustManagerImpl/BasicConstraints.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,564 +0,0 @@ -/* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7166570 - * @summary JSSE certificate validation has started to fail for - * certificate chains - * @run main/othervm BasicConstraints PKIX - * @run main/othervm BasicConstraints SunX509 - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.*; -import java.security.spec.*; -import java.security.interfaces.*; -import java.math.BigInteger; - -import java.util.Base64; - -public class BasicConstraints { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:50 2012 GMT - // Not After : Apr 15 02:40:50 2033 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce - // X509v3 Subject Key Identifier: - // DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String trusedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUwWhcNMzMwNDE1MDI0MDUwWjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBANtiq0AIJK+iVRwFrqcD7fYXTCbMYC5Qz/k6\n" + - "AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwvzuURbc9+paOBWeHbN+Sc\n" + - "x3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStFhSHXATjtdbskNOAYGLTV\n" + - "x8uEy9GbAgMBAAGjgaUwgaIwHQYDVR0OBBYEFN1OjSoRwIMD8Kzror/58n3IaR+b\n" + - "MGMGA1UdIwRcMFqAFN1OjSoRwIMD8Kzror/58n3IaR+boT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + - "BQADgYEAjjkJesQrkbr36N40egybaIxw7RcqT6iy5fkAGS1JYlBDk8uSCK1o6bCH\n" + - "ls5EpYcGeEoabSS73WRdkO1lgeyWDduO4ef8cCCSpmpT6/YdZG0QS1PtcREeVig+\n" + - "Zr25jNemS4ADHX0aaXP4kiV/G80cR7nX5t5XCUm4bYdbwM07NgI=\n" + - "-----END CERTIFICATE-----"; - static String trustedPrivateKey = // Private key in the format of PKCS#8 - "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANtiq0AIJK+iVRwF\n" + - "rqcD7fYXTCbMYC5Qz/k6AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwv\n" + - "zuURbc9+paOBWeHbN+Scx3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStF\n" + - "hSHXATjtdbskNOAYGLTVx8uEy9GbAgMBAAECgYEA2VjHkIiA0ABjkX+PqKeb+VLb\n" + - "fxS7tSca5C8zfdRhLxAWRui0/3ihst0eCJNrBDuxvAOACovsDWyLuaUjtI2v2ysz\n" + - "vz6SPyGy82PhQOFzyKQuQ814N6EpothpiZzF0yFchfKIGhUsdY89UrGs9nM7m6NT\n" + - "rztYvgIu4avg2VPR2AECQQD+pFAqipR2BplQRIuuRSZfHRxvoEyDjT1xnHJsC6WP\n" + - "I5hCLghL91MhQGWbP4EJMKYQOTRVukWlcp2Kycpf+P5hAkEA3I43gmVUAPEdyZdY\n" + - "fatW7OaLlbbYJb6qEtpCZ1Rwe/BIvm6H6E3qSi/lpz7Ia7WDulpbF6BawHH3pRFq\n" + - "CUY5ewJBAP3pUDqrRpBN0jB0uSeDslhjSciQ+dqvSpZv3rSYBHUvlBJhnkpJiy37\n" + - "7ZUZhIxqYxyIPgRBolLwb+FFh7OdL+ECQCtldDic9WVmC+VheRDpCKZ+SlK/8lGi\n" + - "7VXeShiIvcU1JysJFoa35fSI7hf1O3wt7+hX5PqGG7Un94EsJwACKEcCQQC1TWt6\n" + - "ArKH6tRxKjOxFtqfs8fgEVYUaOr3j1jF4KBUuX2mtQtddZe3VfJ2wPsuKMMxmhkB\n" + - "e7xWWZnJsErt2e+E"; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:53 2012 GMT - // Not After : Jan 21 02:40:53 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // X509v3 Subject Key Identifier: - // 13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String caSignerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICqDCCAhGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUzWhcNMzIwMTIxMDI0MDUzWjBOMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAPBgNV\n" + - "BAMTCGNhc2lnbmVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+x8+o7oM0\n" + - "ct/LZmZLXBL4CQ8jrULD5P7NtEW0hg/zxBFZfBHf+44Oo2eMPYZj+7xaREOH5BmV\n" + - "KRYlzRtONAaC5Ng4Mrm5UKNPcMIIUjUOvm7vWM4oSTMSfoEcSX+vp99uUAkw3w7Z\n" + - "+frYDm1M4At/j0b+lLij71GFN2L8drpgPQIDAQABo4GoMIGlMB0GA1UdDgQWBBQT\n" + - "B+ARB9vrMyOHMdDbfhZWvhGQCjBjBgNVHSMEXDBagBTdTo0qEcCDA/Cs66K/+fJ9\n" + - "yGkfm6E/pD0wOzELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsT\n" + - "FFN1bkpTU0UgVGVzdCBTZXJpdmNlggEAMBIGA1UdEwEB/wQIMAYBAf8CAQEwCwYD\n" + - "VR0PBAQDAgEGMA0GCSqGSIb3DQEBBAUAA4GBAI+LXA/UCPkTANablUkt80JNPWsl\n" + - "pS4XLNgPxWaN0bkRDs5oI4ooWAz1rwpeJ/nfetOvWlpmrVjSeovBFja5Hl+dUHTf\n" + - "VfuyzkxXbhuNiJIpo1mVBpNsjwu9YRxuwX6UA2LTUQpgvtVJEE012x3zRvxBCbu2\n" + - "Y/v1R5fZ4c+hXDfC\n" + - "-----END CERTIFICATE-----"; - static String caSignerPrivateKey = // Private key in the format of PKCS#8 - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL7Hz6jugzRy38tm\n" + - "ZktcEvgJDyOtQsPk/s20RbSGD/PEEVl8Ed/7jg6jZ4w9hmP7vFpEQ4fkGZUpFiXN\n" + - "G040BoLk2DgyublQo09wwghSNQ6+bu9YzihJMxJ+gRxJf6+n325QCTDfDtn5+tgO\n" + - "bUzgC3+PRv6UuKPvUYU3Yvx2umA9AgMBAAECgYBYvu30cW8LONyt62Zua9hPFTe7\n" + - "qt9B7QYyfkdmoG5PQMepTrOp84SzfoOukvgvDm0huFuJnSvhXQl2cCDhkgXskvFj\n" + - "Hh7KBCFViVXokGdq5YoS0/KYMyQV0TZfJUvILBl51uc4/siQ2tClC/N4sa+1JhgW\n" + - "a6dFGfRjiUKSSlmMwQJBAPWpIz3Q/c+DYMvoQr5OD8EaYwYIevlTdXb97RnJJh2b\n" + - "UnhB9jrqesJiHYVzPmP0ukyPOXOwlp2T5Am4Kw0LFOkCQQDGz150NoHOp28Mvyc4\n" + - "CTqz/zYzUhy2eCJESl196uyP4N65Y01VYQ3JDww4DlsXiU17tVSbgA9TCcfTYOzy\n" + - "vyw1AkARUky+1hafZCcWGZljK8PmnMKwsTZikCTvL/Zg5BMA8Wu+OQBwpQnk3OAy\n" + - "Aa87gw0DyvGFG8Vy9POWT9sRP1/JAkBqP0hrMvYMSs6+MSn0eHo2151PsAJIQcuO\n" + - "U2/Da1khSzu8N6WMi2GiobgV/RYRbf9KrY2ZzMZjykZQYOxAjopBAkEAghCu38cN\n" + - "aOsW6ueo24uzsWI1FTdE+qWNVEi3RSP120xXBCyhaBjIq4WVSlJK9K2aBaJpit3j\n" + - "iQ5tl6zrLlxQhg=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // Validity - // Not Before: May 5 02:40:57 2012 GMT - // Not After : Jan 21 02:40:57 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // X509v3 Subject Key Identifier: - // 39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - // X509v3 Authority Key Identifier: - // keyid:13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:02 - static String certIssuerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICvjCCAiegAwIBAgIBAzANBgkqhkiG9w0BAQQFADBOMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAP\n" + - "BgNVBAMTCGNhc2lnbmVyMB4XDTEyMDUwNTAyNDA1N1oXDTMyMDEyMTAyNDA1N1ow\n" + - "UDELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0Ug\n" + - "VGVzdCBTZXJpdmNlMRMwEQYDVQQDEwpjZXJ0aXNzdWVyMIGfMA0GCSqGSIb3DQEB\n" + - "AQUAA4GNADCBiQKBgQCyz55zinU6kNL/LeiTNiBI0QWYmDG0YTotuC4D75liBNqs\n" + - "7Mmladsh2mTtQUAwmuGaGzaZV25a+cUax0DXZoyBwdbTI09u1bUYsZcaUUKbPoCC\n" + - "HH26e4jLFL4olW13Sv4ZAd57tIYevMw+Fp5f4fLPFGegCJTFlv2Qjpmic/cuvQID\n" + - "AQABo4GpMIGmMB0GA1UdDgQWBBQ5DsYzsVC8cwcx5dgE97uXVc+byDBjBgNVHSME\n" + - "XDBagBQTB+ARB9vrMyOHMdDbfhZWvhGQCqE/pD0wOzELMAkGA1UEBhMCVVMxDTAL\n" + - "BgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNlggECMBMG\n" + - "A1UdEwEB/wQJMAcBAf8CAgQAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQQFAAOB\n" + - "gQCQTagenCdClT98C+oTJGJrw/dUBD9K3tE6ZJKPMc/2bUia8G5ei1C0eXj4mWG2\n" + - "lu9umR6C90/A6qB050QB2h50qtqxSrkpu+ym1yypauZpg7U3nUY9wZWJNI1vqrQZ\n" + - "pqUMRcXY3iQIVKx+Qj+4/Za1wwFQzpEoGmqRW31V1SdMEw==\n" + - "-----END CERTIFICATE-----"; - static String certIssuerPrivateKey = // Private key in the format of PKCS#8 - "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALLPnnOKdTqQ0v8t\n" + - "6JM2IEjRBZiYMbRhOi24LgPvmWIE2qzsyaVp2yHaZO1BQDCa4ZobNplXblr5xRrH\n" + - "QNdmjIHB1tMjT27VtRixlxpRQps+gIIcfbp7iMsUviiVbXdK/hkB3nu0hh68zD4W\n" + - "nl/h8s8UZ6AIlMWW/ZCOmaJz9y69AgMBAAECgYEAjtew2tgm4gxDojqIauF4VPM1\n" + - "pzsdqd1p3pAdomNLgrQiBLZ8N7oiph6TNb1EjA+OXc+ThFgF/oM9ZDD8qZZwcvjN\n" + - "qDZlpTkFs2TaGcyEZfUaMB45NHVs6Nn+pSkagSNwwy3xeyAct7sQEzGNTDlEwVv5\n" + - "7V9LQutQtBd6xT48KzkCQQDpNRfv2OFNG/6GtzJoO68oJhpnpl2MsYNi4ntRkre/\n" + - "6uXpiCYaDskcrPMRwOOs0m7mxG+Ev+uKnLnSoEMm1GCbAkEAxEmDtiD0Psb8Z9BL\n" + - "ZRb83Jqho3xe2MCAh3xUfz9b/Mhae9dZ44o4OCgQZuwvW1mczF0NtpgZl93BmYa2\n" + - "hTwHhwJBAKHrEj6ep/fA6x0gD2idoATRR94VfbiU+7NpqtO9ecVP0+gsdr/66hn1\n" + - "3yLBeZLh3MxvMTrLgkAQh1i9m0JXjOcCQQClLXAHHegrw+u3uNMZeKTFR+Lp3sk6\n" + - "AZSnbvr0Me9I45kxSeG81x3ENALJecvIRbrrRws5MvmmkNhQR8rkh8WVAkEAk6b+\n" + - "aVtmBgUaTS5+FFlHGHJY9HFrfT1a1C/dwyMuqlmbC3YsBmZaMOlKli5TXNybLff8\n" + - "5KMeGEpXMzgC7AscGA=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // Validity - // Not Before: May 5 02:41:01 2012 GMT - // Not After : Jan 21 02:41:01 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=localhost - // X509v3 Subject Key Identifier: - // AD:C0:2C:4C:E4:C2:2E:A1:BB:5D:92:BE:66:E0:4E:E0:0D:2F:11:EF - // X509v3 Authority Key Identifier: - // keyid:39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - static String serverCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICjTCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQQFADBQMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEzAR\n" + - "BgNVBAMTCmNlcnRpc3N1ZXIwHhcNMTIwNTA1MDI0MTAxWhcNMzIwMTIxMDI0MTAx\n" + - "WjBPMQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNT\n" + - "RSBUZXN0IFNlcml2Y2UxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0B\n" + - "AQEFAAOBjQAwgYkCgYEAvwaUd7wmBSKqycEstYLWD26vkU08DM39EtaT8wL9HnQ0\n" + - "fgPblwBFI4zdLa2cuYXRZcFUb04N8nrkcpR0D6kkE+AlFAoRWrrZF80B7JTbtEK4\n" + - "1PIeurihXvUT+4MpzGLOojIihMfvM4ufelblD56SInso4WFHm7t4qCln88J1gjkC\n" + - "AwEAAaN4MHYwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBStwCxM5MIuobtdkr5m4E7g\n" + - "DS8R7zAfBgNVHSMEGDAWgBQ5DsYzsVC8cwcx5dgE97uXVc+byDAnBgNVHSUEIDAe\n" + - "BggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GB\n" + - "AGfwcfdvEG/nSCiAn2MGbYHp34mgF3OA1SJLWUW0LvWJhwm2cn4AXlSoyvbwrkaB\n" + - "IDDCwhJvvc0vUyL2kTx7sqVaFTq3mDs+ktlB/FfH0Pb+i8FE+g+7T42Iw/j0qxHL\n" + - "YmgbrjBQf5WYN1AvBE/rrPt9aOtS3UsqtVGW574b0shW\n" + - "-----END CERTIFICATE-----"; - static String serverPrivateKey = // Private key in the format of PKCS#8 - "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAL8GlHe8JgUiqsnB\n" + - "LLWC1g9ur5FNPAzN/RLWk/MC/R50NH4D25cARSOM3S2tnLmF0WXBVG9ODfJ65HKU\n" + - "dA+pJBPgJRQKEVq62RfNAeyU27RCuNTyHrq4oV71E/uDKcxizqIyIoTH7zOLn3pW\n" + - "5Q+ekiJ7KOFhR5u7eKgpZ/PCdYI5AgMBAAECf3CscOYvFD3zNMnMJ5LomVqA7w3F\n" + - "gKYM2jlCWAH+wU41PMEXhW6Lujw92jgXL1o+lERwxFzirVdZJWZwKgUSvzP1G0h3\n" + - "fkucq1/UWnToK+8NSXNM/yS8hXbBgSEoJo5f7LKcIi1Ev6doBVofMxs+njzyWKbM\n" + - "Nb7rOLHadghoon0CQQDgQzbzzSN8Dc1YmmylhI5v+0sQRHH0DL7D24k4Weh4vInG\n" + - "EAbt4x8M7ZKEo8/dv0s4hbmNmAnJl93/RRxIyEqLAkEA2g87DiswSQam2pZ8GlrO\n" + - "+w4Qg9mH8uxx8ou2rl0XlHzH1XiTNbkjfY0EZoL7L31BHFk9n11Fb2P85g6ws+Hy\n" + - "ywJAM/xgyLNM/nzUlS128geAXUULaYH0SHaL4isJ7B4rXZGW/mrIsGxtzjlkNYsj\n" + - "rGujrD6TfNc5rZmexIXowJZtcQJBAIww+pCzZ4mrgx5JXWQ8OZHiiu+ZrPOa2+9J\n" + - "r5sOMpi+WGN/73S8oHqZbNjTINZ5OqEVJq8MchWZPQBTNXuQql0CQHEjUzzkCQa3\n" + - "j6JTa2KAdqyvLOx0XF9zcc1gA069uNQI2gPUHS8V215z57f/gMGnDNhVfLs/vMKz\n" + - "sFkVZ3zg7As="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // Validity - // Not Before: May 5 02:41:02 2012 GMT - // Not After : Jan 21 02:41:02 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=InterOp Tester - // X509v3 Subject Key Identifier: - // 57:7D:E2:33:33:60:DF:DD:5E:ED:81:3F:EB:F2:1B:59:7F:50:9C:99 - // X509v3 Authority Key Identifier: - // keyid:39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - static String clientCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICaTCCAdKgAwIBAgIBBTANBgkqhkiG9w0BAQQFADBQMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEzAR\n" + - "BgNVBAMTCmNlcnRpc3N1ZXIwHhcNMTIwNTA1MDI0MTAyWhcNMzIwMTIxMDI0MTAy\n" + - "WjBUMQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNT\n" + - "RSBUZXN0IFNlcml2Y2UxFzAVBgNVBAMTDkludGVyT3AgVGVzdGVyMIGfMA0GCSqG\n" + - "SIb3DQEBAQUAA4GNADCBiQKBgQC1pA71nDg1KhhnHjRdi/eVDUa7uFZAtN8R9huu\n" + - "pTwFoyqSX8lDMz8jDawOMmaI9dVZLjTh3hnf4KBEqQOearFVz45yBOjlgPLBuI4F\n" + - "D/ORhgmDaIu2NK+c1yj6YQlyiO0DPwh55GtPLVG3iuEpejU7gQyaMuTaddoXrO7s\n" + - "xwzanQIDAQABo08wTTALBgNVHQ8EBAMCA+gwHQYDVR0OBBYEFFd94jMzYN/dXu2B\n" + - "P+vyG1l/UJyZMB8GA1UdIwQYMBaAFDkOxjOxULxzBzHl2AT3u5dVz5vIMA0GCSqG\n" + - "SIb3DQEBBAUAA4GBAHTgB5W7wnl7Jnb4wNQcb6JdR8FRHIdslcRfnReFfZBHZZux\n" + - "ChpA1lf62KIzYohKoxQXXMul86vnVSHnXq5xctHEmxCBnALEnoAcCOv6wfWqEA7g\n" + - "2rX+ydmu+0ArbqKhSOypZ7K3ame0UOJJ6HDxdsgBYJuotmSou4KKq9e8GF+d\n" + - "-----END CERTIFICATE-----"; - static String clientPrivateKey = // Private key in the format of PKCS#8 - "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALWkDvWcODUqGGce\n" + - "NF2L95UNRru4VkC03xH2G66lPAWjKpJfyUMzPyMNrA4yZoj11VkuNOHeGd/goESp\n" + - "A55qsVXPjnIE6OWA8sG4jgUP85GGCYNoi7Y0r5zXKPphCXKI7QM/CHnka08tUbeK\n" + - "4Sl6NTuBDJoy5Np12hes7uzHDNqdAgMBAAECgYEAjLwygwapXjfhdHQoqpp6F9iT\n" + - "h3sKCVSaybXgOO75lHyZzZO9wv1/288KEm3mmBOxXEm6245UievnAYvaq/GKt93O\n" + - "pj2zRefBzZjGbz0v84fmna/MN6zUUYX1PcVRMKWLx9HKKmQihzwoXdBX0o9PPXdi\n" + - "LfzujNa/q8/mpI5PmEECQQDZwLSaL7OReWZTY4NoQuNzwhx5IKJUOtCFQfmHKZSW\n" + - "wtXntZf+E5W9tGaDY5wjpq5cilKDAHdEAlFWxDe1PoE1AkEA1YuTBpctOLBfquFn\n" + - "Y/S3lzGVlnIHDk3dj4bFglkoJ2bCdlwRNUyBSjAjBDcbYhper8S7GlEN5SiEdz9I\n" + - "3OjIyQJBAKEPMgYhZjYhjxf6sQV7A/VpC9pj0u1uGzGVXNUmYisorUKXRHa/UbBh\n" + - "MLnaAXE1Jh54iRMwUwbQmA0PUQ0T0EkCQQCcr6/umwhkWw2nHYK2Vf5LoudGn15M\n" + - "AZg7UsEjVnXfC0hOfllmCT+ohs96rVCbWAv33lsHAUg3x9YChV3aMbf5AkAj1kuV\n" + - "jUTgFKjediyQC6uof7YdLn+gQGiXK1XE0GBN4WMkzcLiS0jC+MFTgKfFnFdh9K0y\n" + - "fswYKdTA/o8RKaa5"; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = getSSLContext(true); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - SSLSocket sslSocket = null; - try { - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.setNeedClientAuth(true); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } finally { - if (sslSocket != null) { - sslSocket.close(); - } - sslServerSocket.close(); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = getSSLContext(false); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - try { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } finally { - sslSocket.close(); - } - } - - // get the ssl context - private static SSLContext getSSLContext(boolean isServer) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - ByteArrayInputStream is = - new ByteArrayInputStream(trusedCertStr.getBytes()); - Certificate trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("SunJSSE Test Serivce", trusedCert); - - // import the certificate chain and key - Certificate[] chain = new Certificate[3]; - - is = new ByteArrayInputStream(caSignerStr.getBytes()); - Certificate caSignerCert = cf.generateCertificate(is); - is.close(); - chain[2] = caSignerCert; - - is = new ByteArrayInputStream(certIssuerStr.getBytes()); - Certificate certIssuerCert = cf.generateCertificate(is); - is.close(); - chain[1] = certIssuerCert; - - PKCS8EncodedKeySpec priKeySpec = null; - if (isServer) { - priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(serverPrivateKey)); - is = new ByteArrayInputStream(serverCertStr.getBytes()); - } else { - priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(clientPrivateKey)); - is = new ByteArrayInputStream(clientCertStr.getBytes()); - } - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - chain[0] = keyCert; - - ks.setKeyEntry("End Entity", priKey, passphrase, chain); - - // check the certification path - PKIXParameters paras = new PKIXParameters(ks); - paras.setRevocationEnabled(false); - CertPath path = cf.generateCertPath(Arrays.asList(chain)); - CertPathValidator cv = CertPathValidator.getInstance("PKIX"); - cv.validate(path, paras); - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - - return ctx; - } - - private static String tmAlgorithm; // trust manager - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String args[]) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new BasicConstraints(); - } - - Thread clientThread = null; - Thread serverThread = null; - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - BasicConstraints() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } - -}
--- a/test/sun/security/ssl/X509TrustManagerImpl/CertRequestOverflow.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,402 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 7200295 - * @summary CertificateRequest message is wrapping when using large - * numbers of Certs - * @run main/othervm CertRequestOverflow - */ - -import java.io.*; -import java.net.*; -import java.util.*; -import javax.net.ssl.*; -import java.security.cert.*; -import java.security.*; - -public class CertRequestOverflow { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - private final static char[] cpasswd = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - getContext(true).getServerSocketFactory(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - // enable endpoint identification - // ignore, we may test the feature when known how to parse client - // hostname - //SSLParameters params = sslServerSocket.getSSLParameters(); - //params.setEndpointIdentificationAlgorithm("HTTPS"); - //sslServerSocket.setSSLParameters(params); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.setNeedClientAuth(true); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - try { - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - throw new Exception("SERVER TEST FAILED! " + - "It is expected to fail with field length overflow"); - } catch (SSLException ssle) { - Throwable cause = ssle.getCause(); - if (!(cause instanceof RuntimeException)) { - System.out.println("We are expecting a RuntimeException!"); - throw ssle; - } - System.out.println("The expected exception! " + ssle); - } finally { - sslSocket.close(); - } - - System.out.println("SERVER TEST PASSED!"); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = getContext(false).getSocketFactory(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - // enable endpoint identification - SSLParameters params = sslSocket.getSSLParameters(); - params.setEndpointIdentificationAlgorithm("HTTPS"); - sslSocket.setSSLParameters(params); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - try { - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } catch (SSLException ssle) { - System.out.println("An expected exception!"); - } finally { - sslSocket.close(); - } - } - - MyExtendedX509TM serverTM; - MyExtendedX509TM clientTM; - - private SSLContext getContext(boolean server) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(keyFilename), cpasswd); - kmf.init(ks, cpasswd); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - KeyStore ts = KeyStore.getInstance("JKS"); - ts.load(new FileInputStream(trustFilename), cpasswd); - tmf.init(ts); - - TrustManager tms[] = tmf.getTrustManagers(); - if (tms == null || tms.length == 0) { - throw new Exception("unexpected trust manager implementation"); - } else { - if (!(tms[0] instanceof X509TrustManager)) { - throw new Exception("unexpected trust manager implementation: " - + tms[0].getClass().getCanonicalName()); - } - } - - if (server) { - serverTM = new MyExtendedX509TM((X509TrustManager)tms[0]); - - tms = new TrustManager[] {serverTM}; - } else { - clientTM = new MyExtendedX509TM((X509TrustManager)tms[0]); - - tms = new TrustManager[] {clientTM}; - } - - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(kmf.getKeyManagers(), tms, null); - - return ctx; - } - - static class MyExtendedX509TM extends X509ExtendedTrustManager - implements X509TrustManager { - - X509TrustManager tm; - - boolean clientChecked; - boolean serverChecked; - - MyExtendedX509TM(X509TrustManager tm) { - clientChecked = false; - serverChecked = false; - - this.tm = tm; - } - - public boolean wasClientChecked() { - return clientChecked; - } - - public boolean wasServerChecked() { - return serverChecked; - } - - - public void checkClientTrusted(X509Certificate chain[], String authType) - throws CertificateException { - tm.checkClientTrusted(chain, authType); - } - - public void checkServerTrusted(X509Certificate chain[], String authType) - throws CertificateException { - tm.checkServerTrusted(chain, authType); - } - - public X509Certificate[] getAcceptedIssuers() { - // (hack code) increase the size of the returned array to make a - // overflow CertificateRequest. - List<X509Certificate> issuersList = new LinkedList<>(); - X509Certificate[] issuers = tm.getAcceptedIssuers(); - for (int i = 0; i < 800; i += issuers.length) { - for (X509Certificate issuer : issuers) { - issuersList.add(issuer); - } - } - - return issuersList.toArray(issuers); - } - - public void checkClientTrusted(X509Certificate[] chain, String authType, - Socket socket) throws CertificateException { - clientChecked = true; - tm.checkClientTrusted(chain, authType); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType, - Socket socket) throws CertificateException { - serverChecked = true; - tm.checkServerTrusted(chain, authType); - } - - public void checkClientTrusted(X509Certificate[] chain, String authType, - SSLEngine engine) throws CertificateException { - clientChecked = true; - tm.checkClientTrusted(chain, authType); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType, - SSLEngine engine) throws CertificateException { - serverChecked = true; - tm.checkServerTrusted(chain, authType); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new CertRequestOverflow(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - CertRequestOverflow() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -} -
--- a/test/sun/security/ssl/X509TrustManagerImpl/ClientServer.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,361 +0,0 @@ -/* - * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 4717766 - * @summary 1.0.3 JsseX509TrustManager erroneously calls isClientTrusted() - * @run main/othervm ClientServer - * - * SunJSSE does not support dynamic system properties, no way to re-use - * system properties in samevm/agentvm mode. - * @ignore JSSE supports algorithm constraints with CR 6916074, - * need to update this test case in JDK 7 soon - * @author Brad Wetmore - * - * This problem didn't exist in JSSE 1.4, only JSSE 1.0.3. However, - * this is a useful test, so I decided to include it in 1.4.2. - */ - -import java.io.*; -import java.net.*; -import javax.net.ssl.*; -import java.security.cert.*; -import java.security.*; -import com.sun.net.ssl.*; - -public class ClientServer { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = getDefaultServer(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.setNeedClientAuth(true); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - - if (!serverTM.wasServerChecked() && serverTM.wasClientChecked()) { - System.out.println("SERVER TEST PASSED!"); - } else { - throw new Exception("SERVER TEST FAILED! " + - !serverTM.wasServerChecked() + " " + - serverTM.wasClientChecked()); - } - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = getDefaultClient(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - - if (clientTM.wasServerChecked() && !clientTM.wasClientChecked()) { - System.out.println("CLIENT TEST PASSED!"); - } else { - throw new Exception("CLIENT TEST FAILED! " + - clientTM.wasServerChecked() + " " + - !clientTM.wasClientChecked()); - } - } - - private com.sun.net.ssl.SSLContext getDefault(MyX509TM tm) - throws Exception { - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - char[] passphrase = "passphrase".toCharArray(); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(keyFilename), passphrase); - - com.sun.net.ssl.KeyManagerFactory kmf = - com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(trustFilename), passphrase); - - com.sun.net.ssl.TrustManagerFactory tmf = - com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509"); - tmf.init(ks); - - com.sun.net.ssl.TrustManager [] tms = tmf.getTrustManagers(); - - int i; - for (i = 0; i < tms.length; i++) { - if (tms[i] instanceof com.sun.net.ssl.X509TrustManager) { - break; - } - } - - if (i >= tms.length) { - throw new Exception("Couldn't find X509TM"); - } - - tm.init((com.sun.net.ssl.X509TrustManager)tms[i]); - tms = new MyX509TM [] { tm }; - - com.sun.net.ssl.SSLContext ctx = - com.sun.net.ssl.SSLContext.getInstance("TLS"); - ctx.init(kmf.getKeyManagers(), tms, null); - return ctx; - } - - MyX509TM serverTM; - MyX509TM clientTM; - - private SSLServerSocketFactory getDefaultServer() throws Exception { - serverTM = new MyX509TM(); - return getDefault(serverTM).getServerSocketFactory(); - } - - private SSLSocketFactory getDefaultClient() throws Exception { - clientTM = new MyX509TM(); - return getDefault(clientTM).getSocketFactory(); - } - - static class MyX509TM implements com.sun.net.ssl.X509TrustManager { - - com.sun.net.ssl.X509TrustManager tm; - boolean clientChecked; - boolean serverChecked; - - void init(com.sun.net.ssl.X509TrustManager x509TM) { - tm = x509TM; - } - - public boolean wasClientChecked() { - return clientChecked; - } - - public boolean wasServerChecked() { - return serverChecked; - } - - public boolean isClientTrusted(X509Certificate[] chain) { - clientChecked = true; - return true; - } - - public boolean isServerTrusted(X509Certificate[] chain) { - serverChecked = true; - return true; - } - - public X509Certificate[] getAcceptedIssuers() { - return tm.getAcceptedIssuers(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - - if (debug) - System.setProperty("javax.net.debug", "all"); - - /* - * Start the tests. - */ - new ClientServer(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ClientServer() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } -}
--- a/test/sun/security/ssl/X509TrustManagerImpl/SelfIssuedCert.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,412 +0,0 @@ -/* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. -// - -/* - * @test - * @bug 6822460 - * @summary support self-issued certificate - * @run main/othervm SelfIssuedCert PKIX - * @run main/othervm SelfIssuedCert SunX509 - * @author Xuelei Fan - */ - -import java.net.*; -import java.util.*; -import java.io.*; -import javax.net.ssl.*; -import java.security.Security; -import java.security.KeyStore; -import java.security.KeyFactory; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.*; -import java.security.interfaces.*; -import java.math.BigInteger; - -import java.util.Base64; - -public class SelfIssuedCert { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - // Certificate information: - // Issuer: C=US, O=Example, CN=localhost - // Validity - // Not Before: May 25 00:35:58 2009 GMT - // Not After : May 5 00:35:58 2030 GMT - // Subject: C=US, O=Example, CN=localhost - // X509v3 Subject Key Identifier: - // 56:AB:FE:15:4C:9C:4A:70:90:DC:0B:9B:EB:BE:DC:03:CC:7F:CE:CF - // X509v3 Authority Key Identifier: - // keyid:56:AB:FE:15:4C:9C:4A:70:90:DC:0B:9B:EB:BE:DC:03:CC:7F:CE:CF - // DirName:/C=US/O=Example/CN=localhost - // serial:00 - static String trusedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICejCCAeOgAwIBAgIBADANBgkqhkiG9w0BAQQFADAzMQswCQYDVQQGEwJVUzEQ\n" + - "MA4GA1UEChMHRXhhbXBsZTESMBAGA1UEAxMJbG9jYWxob3N0MB4XDTA5MDUyNTAw\n" + - "MDQ0M1oXDTMwMDUwNTAwMDQ0M1owMzELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0V4\n" + - "YW1wbGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw\n" + - "gYkCgYEA0Wvh3FHYGQ3vvw59yTjUxT6QuY0fzwCGQTM9evXr/V9+pjWmaTkNDW+7\n" + - "S/LErlWz64gOWTgcMZN162sVgx4ct/q27brY+SlUO5eSud1fSac6SfefhOPBa965\n" + - "Xc4mnpDt5sgQPMDCuFK7Le6A+/S9J42BO2WYmNcmvcwWWrv+ehcCAwEAAaOBnTCB\n" + - "mjAdBgNVHQ4EFgQUq3q5fYEibdvLpab+JY4pmifj2vYwWwYDVR0jBFQwUoAUq3q5\n" + - "fYEibdvLpab+JY4pmifj2vahN6Q1MDMxCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdF\n" + - "eGFtcGxlMRIwEAYDVQQDEwlsb2NhbGhvc3SCAQAwDwYDVR0TAQH/BAUwAwEB/zAL\n" + - "BgNVHQ8EBAMCAgQwDQYJKoZIhvcNAQEEBQADgYEAHL8BSwtX6s8WPPG2FbQBX+K8\n" + - "GquAyQNtgfJNm60B4i+fVBkJiQJtLmE0emvHx/3sIaHmB0Gd0HKnk/cIQXY304vr\n" + - "QpqwudKcIZuzmj+pa7807joV+WzRDVIlt4HpYg7tiUvEoyw+X8jwY2lgiGR7mWu6\n" + - "jQU8PN/06+qgtvSGFpo=\n" + - "-----END CERTIFICATE-----"; - - // Certificate information: - // Issuer: C=US, O=Example, CN=localhost - // Validity - // Not Before: May 25 00:35:58 2009 GMT - // Not After : May 5 00:35:58 2030 GMT - // Subject: C=US, O=Example, CN=localhost - // X509v3 Subject Key Identifier: - // 0D:30:76:22:D6:9D:75:EF:FD:83:50:31:18:08:83:CD:01:4E:6A:C4 - // X509v3 Authority Key Identifier: - // keyid:56:AB:FE:15:4C:9C:4A:70:90:DC:0B:9B:EB:BE:DC:03:CC:7F:CE:CF - // DirName:/C=US/O=Example/CN=localhost - // serial:00 - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICaTCCAdKgAwIBAgIBAjANBgkqhkiG9w0BAQQFADAzMQswCQYDVQQGEwJVUzEQ\n" + - "MA4GA1UEChMHRXhhbXBsZTESMBAGA1UEAxMJbG9jYWxob3N0MB4XDTA5MDUyNTAw\n" + - "MDQ0M1oXDTI5MDIwOTAwMDQ0M1owMzELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0V4\n" + - "YW1wbGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw\n" + - "gYkCgYEAzmPahrH9LTQv3HEWsua+hIpzyU1ACooSd5BtDjc7XnVzSdGW8QD9R8EA\n" + - "xko7TvfJo6IH6wwgHBspySwsl+6xvHhbwQjgtWlT71ksrUbqcUzmvSvcycQYA8RC\n" + - "yk9HK5pEJQgSxldpR3Kmy0V6CHC4dCm15trnJYWisTuezY3fjXECAwEAAaOBjDCB\n" + - "iTAdBgNVHQ4EFgQUQkiWFRkjKsfwFo7UMQfGEzNNW60wWwYDVR0jBFQwUoAUq3q5\n" + - "fYEibdvLpab+JY4pmifj2vahN6Q1MDMxCzAJBgNVBAYTAlVTMRAwDgYDVQQKEwdF\n" + - "eGFtcGxlMRIwEAYDVQQDEwlsb2NhbGhvc3SCAQAwCwYDVR0PBAQDAgPoMA0GCSqG\n" + - "SIb3DQEBBAUAA4GBAIMz7c1R+6KEO7FmH4rnv9XE62xkg03ff0vKXLZMjjs0CX2z\n" + - "ybRttuTFafHA6/JS+Wz0G83FCRVeiw2WPU6BweMwwejzzIrQ/K6mbp6w6sRFcbNa\n" + - "eLBtzkjEtI/htOSSq3/0mbKmWn5uVJckO4QiB8kUR4F7ngM9l1uuI46ZfUsk\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8 - static String targetPrivateKey = - "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAM5j2oax/S00L9xx\n" + - "FrLmvoSKc8lNQAqKEneQbQ43O151c0nRlvEA/UfBAMZKO073yaOiB+sMIBwbKcks\n" + - "LJfusbx4W8EI4LVpU+9ZLK1G6nFM5r0r3MnEGAPEQspPRyuaRCUIEsZXaUdypstF\n" + - "eghwuHQpteba5yWForE7ns2N341xAgMBAAECgYEAgZ8k98OBhopoJMLBxso0jXmH\n" + - "Dr59oiDlSEJku7DkkIajSZFggyxj5lTI78BfT1FASozQ/EY5RG2q6LXdq+41oU/U\n" + - "JVEQWhdIE1mQDwE0vgaYdjzMaVIsC3cZYOCOmCYvNxCiTt7e/z8yBMmAE5udqJMB\n" + - "pim4WXDfpy0ssK81oCECQQDwMC4xu+kn0yD/Qyi9Zn26gIRDv4bjzDQoJfSvMhrY\n" + - "a4duxLzh9u4gCDd0+wHxpPQvNxGCk0c1JUxBJ2rb4G3HAkEA2/oVRV6+xiRXUnoo\n" + - "bdPEO27zEJmdpE42yU/JLIy6DPu2IUhEqY45fU2ZERmwMdhpiK/vsf/CZKJ2j/ZU\n" + - "PdMLBwJBAJIYTFDWAqjFpCGAASzLRZiGiW0H941h7Suqgp159ZhEN5mps1Yis47q\n" + - "UIkoEHOiKSD69vychsiNykcrKbVaWosCQQC1UrYX4Vo1r5z/EkyjAwzcxL68rzM/\n" + - "TW1hkU/NVg7CRvXBB3X5oY+H1t/WNauD2tRa5FMbESwmkbhTQIP+FikfAkEA4goD\n" + - "HCxUn0Z1OQq9QL6y1Yoof6sHxicUwABosuCLJnDJmA5vhpemvdXQTzFII8g1hyQf\n" + - "z1yyDoxhddcleKlJvQ=="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLContext context = getSSLContext(null, targetCertStr, - targetPrivateKey); - SSLServerSocketFactory sslssf = context.getServerSocketFactory(); - - SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - sslSocket.setNeedClientAuth(false); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLContext context = getSSLContext(trusedCertStr, null, null); - SSLSocketFactory sslsf = context.getSocketFactory(); - - SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - // get the ssl context - private static SSLContext getSSLContext(String trusedCertStr, - String keyCertStr, String keySpecStr) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, null); - - // import the trused cert - Certificate trusedCert = null; - ByteArrayInputStream is = null; - if (trusedCertStr != null) { - is = new ByteArrayInputStream(trusedCertStr.getBytes()); - trusedCert = cf.generateCertificate(is); - is.close(); - - ks.setCertificateEntry("RSA Export Signer", trusedCert); - } - - if (keyCertStr != null) { - // generate the private key. - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = - (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - // generate certificate chain - is = new ByteArrayInputStream(keyCertStr.getBytes()); - Certificate keyCert = cf.generateCertificate(is); - is.close(); - - Certificate[] chain = null; - if (trusedCert != null) { - chain = new Certificate[2]; - chain[0] = keyCert; - chain[1] = trusedCert; - } else { - chain = new Certificate[1]; - chain[0] = keyCert; - } - - // import the key entry. - ks.setKeyEntry("Whatever", priKey, passphrase, chain); - } - - // create SSL context - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); - tmf.init(ks); - - SSLContext ctx = SSLContext.getInstance("TLS"); - if (keyCertStr != null && !keyCertStr.isEmpty()) { - KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); - kmf.init(ks, passphrase); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - ks = null; - } else { - ctx.init(null, tmf.getTrustManagers(), null); - } - - return ctx; - } - - private static String tmAlgorithm; // trust manager - - private static void parseArguments(String[] args) { - tmAlgorithm = args[0]; - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String args[]) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); - - if (debug) - System.setProperty("javax.net.debug", "all"); - - - /* - * Get the customized arguments. - */ - parseArguments(args); - - /* - * Start the tests. - */ - new SelfIssuedCert(); - } - - Thread clientThread = null; - Thread serverThread = null; - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SelfIssuedCert() throws Exception { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) - throw serverException; - if (clientException != null) - throw clientException; - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } - } - -}
--- a/test/sun/security/ssl/X509TrustManagerImpl/Symantec/Distrust.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,273 +0,0 @@ -/* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.math.BigInteger; -import java.security.*; -import java.security.cert.*; -import java.time.*; -import java.util.*; -import javax.net.ssl.*; -import sun.security.validator.Validator; -import sun.security.validator.ValidatorException; - - -/** - * @test - * @bug 8207258 8216280 - * @summary Check that TLS Server certificates chaining back to distrusted - * Symantec roots are invalid - * @library /lib/security - * @run main/othervm Distrust after policyOn invalid - * @run main/othervm Distrust after policyOff valid - * @run main/othervm Distrust before policyOn valid - * @run main/othervm Distrust before policyOff valid - */ - -public class Distrust { - - private static final String TEST_SRC = System.getProperty("test.src", "."); - private static CertificateFactory cf; - - // Each of the roots have a test certificate chain stored in a file - // named "<root>-chain.pem". - private static String[] rootsToTest = new String[] { - "geotrustglobalca", "geotrustprimarycag2", "geotrustprimarycag3", - "geotrustuniversalca", "thawteprimaryrootca", "thawteprimaryrootcag2", - "thawteprimaryrootcag3", "verisignclass3g3ca", "verisignclass3g4ca", - "verisignclass3g5ca", "verisignuniversalrootca" }; - - // Each of the subCAs with a delayed distrust date have a test certificate - // chain stored in a file named "<subCA>-chain.pem". - private static String[] subCAsToTest = new String[] { - "appleistca2g1", "appleistca8g1" }; - - - // A date that is after the restrictions take affect - private static final Date APRIL_17_2019 = - Date.from(LocalDate.of(2019, 4, 17) - .atStartOfDay(ZoneOffset.UTC) - .toInstant()); - - // A date that is a second before the restrictions take affect - private static final Date BEFORE_APRIL_17_2019 = - Date.from(LocalDate.of(2019, 4, 17) - .atStartOfDay(ZoneOffset.UTC) - .minusSeconds(1) - .toInstant()); - - // A date that is after the subCA restrictions take affect - private static final Date JANUARY_1_2020 = - Date.from(LocalDate.of(2020, 1, 1) - .atStartOfDay(ZoneOffset.UTC) - .toInstant()); - - // A date that is a second before the subCA restrictions take affect - private static final Date BEFORE_JANUARY_1_2020 = - Date.from(LocalDate.of(2020, 1, 1) - .atStartOfDay(ZoneOffset.UTC) - .minusSeconds(1) - .toInstant()); - - public static void main(String[] args) throws Exception { - - cf = CertificateFactory.getInstance("X.509"); - boolean distrust = args[0].equals("true"); - - boolean before = args[0].equals("before"); - boolean policyOn = args[1].equals("policyOn"); - boolean isValid = args[2].equals("valid"); - - if (!policyOn) { - // disable policy (default is on) - Security.setProperty("jdk.security.caDistrustPolicies", ""); - } - - Date notBefore = before ? BEFORE_APRIL_17_2019 : APRIL_17_2019; - - X509TrustManager pkixTM = getTMF("PKIX", null); - X509TrustManager sunX509TM = getTMF("SunX509", null); - for (String test : rootsToTest) { - System.err.println("Testing " + test); - X509Certificate[] chain = loadCertificateChain(test); - - testTM(sunX509TM, chain, notBefore, isValid); - testTM(pkixTM, chain, notBefore, isValid); - - } - - // test chain if params are passed to TrustManager - System.err.println("Testing verisignuniversalrootca with params"); - testTM(getTMF("PKIX", getParams()), - loadCertificateChain("verisignuniversalrootca"), - notBefore, isValid); - - // test code-signing chain (should be valid as restrictions don't apply) - System.err.println("Testing verisignclass3g5ca code-signing chain"); - Validator v = Validator.getInstance(Validator.TYPE_PKIX, - Validator.VAR_CODE_SIGNING, - getParams()); - // set validation date so this will still pass when cert expires - v.setValidationDate(new Date(1544197375493l)); - v.validate(loadCertificateChain("verisignclass3g5ca-codesigning")); - - // test chains issued through subCAs - notBefore = before ? BEFORE_JANUARY_1_2020 : JANUARY_1_2020; - for (String test : subCAsToTest) { - System.err.println("Testing " + test); - X509Certificate[] chain = loadCertificateChain(test); - - testTM(sunX509TM, chain, notBefore, isValid); - testTM(pkixTM, chain, notBefore, isValid); - } - } - - private static X509TrustManager getTMF(String type, - PKIXBuilderParameters params) throws Exception { - TrustManagerFactory tmf = TrustManagerFactory.getInstance(type); - if (params == null) { - tmf.init((KeyStore)null); - } else { - tmf.init(new CertPathTrustManagerParameters(params)); - } - TrustManager[] tms = tmf.getTrustManagers(); - for (TrustManager tm : tms) { - X509TrustManager xtm = (X509TrustManager)tm; - return xtm; - } - throw new Exception("No TrustManager for " + type); - } - - private static PKIXBuilderParameters getParams() throws Exception { - PKIXBuilderParameters pbp = - new PKIXBuilderParameters(SecurityUtils.getCacertsKeyStore(), - new X509CertSelector()); - pbp.setRevocationEnabled(false); - return pbp; - } - - private static void testTM(X509TrustManager xtm, X509Certificate[] chain, - Date notBefore, boolean valid) throws Exception { - // Check if TLS Server certificate (the first element of the chain) - // is issued after the specified notBefore date (should be rejected - // unless distrust property is false). To do this, we need to - // fake the notBefore date since none of the test certs are issued - // after then. - chain[0] = new DistrustedTLSServerCert(chain[0], notBefore); - - try { - xtm.checkServerTrusted(chain, "ECDHE_RSA"); - if (!valid) { - throw new Exception("chain should be invalid"); - } - } catch (CertificateException ce) { - if (valid) { - throw new Exception("Unexpected exception, chain " + - "should be valid", ce); - } - if (ce instanceof ValidatorException) { - ValidatorException ve = (ValidatorException)ce; - if (ve.getErrorType() != ValidatorException.T_UNTRUSTED_CERT) { - throw new Exception("Unexpected exception: " + ce); - } - } else { - throw new Exception("Unexpected exception: " + ce); - } - } - } - - private static X509Certificate[] loadCertificateChain(String name) - throws Exception { - try (InputStream in = new FileInputStream(TEST_SRC + File.separator + - name + "-chain.pem")) { - Collection<X509Certificate> certs = - (Collection<X509Certificate>)cf.generateCertificates(in); - return certs.toArray(new X509Certificate[0]); - } - } - - private static class DistrustedTLSServerCert extends X509Certificate { - private final X509Certificate cert; - private final Date notBefore; - DistrustedTLSServerCert(X509Certificate cert, Date notBefore) { - this.cert = cert; - this.notBefore = notBefore; - } - public Set<String> getCriticalExtensionOIDs() { - return cert.getCriticalExtensionOIDs(); - } - public byte[] getExtensionValue(String oid) { - return cert.getExtensionValue(oid); - } - public Set<String> getNonCriticalExtensionOIDs() { - return cert.getNonCriticalExtensionOIDs(); - } - public boolean hasUnsupportedCriticalExtension() { - return cert.hasUnsupportedCriticalExtension(); - } - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { - // always pass - } - public void checkValidity(Date date) throws CertificateExpiredException, - CertificateNotYetValidException { - // always pass - } - public int getVersion() { return cert.getVersion(); } - public BigInteger getSerialNumber() { return cert.getSerialNumber(); } - public Principal getIssuerDN() { return cert.getIssuerDN(); } - public Principal getSubjectDN() { return cert.getSubjectDN(); } - public Date getNotBefore() { return notBefore; } - public Date getNotAfter() { return cert.getNotAfter(); } - public byte[] getTBSCertificate() throws CertificateEncodingException { - return cert.getTBSCertificate(); - } - public byte[] getSignature() { return cert.getSignature(); } - public String getSigAlgName() { return cert.getSigAlgName(); } - public String getSigAlgOID() { return cert.getSigAlgOID(); } - public byte[] getSigAlgParams() { return cert.getSigAlgParams(); } - public boolean[] getIssuerUniqueID() { - return cert.getIssuerUniqueID(); - } - public boolean[] getSubjectUniqueID() { - return cert.getSubjectUniqueID(); - } - public boolean[] getKeyUsage() { return cert.getKeyUsage(); } - public int getBasicConstraints() { return cert.getBasicConstraints(); } - public byte[] getEncoded() throws CertificateEncodingException { - return cert.getEncoded(); - } - public void verify(PublicKey key) throws CertificateException, - InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { - cert.verify(key); - } - public void verify(PublicKey key, String sigProvider) throws - CertificateException, InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { - cert.verify(key, sigProvider); - } - public PublicKey getPublicKey() { return cert.getPublicKey(); } - public String toString() { return cert.toString(); } - } -}
--- a/test/sun/security/ssl/templates/SSLSocketTemplate.java Tue Aug 25 16:27:54 2020 -0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,311 +0,0 @@ -/* - * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. - -/* - * @test - * @bug 1234567 - * @summary Use this template to help speed your client/server tests. - * @run main/othervm SSLSocketTemplate - * @author Brad Wetmore - */ - -import java.io.*; -import javax.net.ssl.*; - -public class SSLSocketTemplate { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Turn on SSL debugging? - */ - static boolean debug = false; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - - sslSocket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - - sslSocket.close(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new SSLSocketTemplate(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketTemplate() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } -}