8306015: Update sun.security.ssl TLS tests to use SSLContextTemplate or SSLEngineTemplate

Reviewed-by: xuelei
This commit is contained in:
Matthew Donovan 2023-05-09 14:25:40 +00:00
parent 672bade522
commit 5842fd5beb
22 changed files with 497 additions and 2059 deletions

@ -645,9 +645,63 @@ public abstract class SSLContextTemplate {
"zjgEAwMvADAsAhQ6Y1I6LtIEBMqNo8o6GIe4LLEJuwIUbVQUKi8tvtWyRoxm8AFV\n" +
"0axJYUU=\n" +
"-----END CERTIFICATE-----",
""
""
),
CA_SHA1_RSA_2048( // for DHEKeySizing.java
"RSA",
// Signature Algorithm: sha1WithRSAEncryption
// Issuer: OU = SunJSSE Test Serivce, O = Java, C = US
// Validity
// Not Before: Sep 18 04:38:31 2013 GMT
// Not After : Dec 17 04:38:31 2013 GMT
"-----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-----",
"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="
),
EE_DSA_SHA1_1024( // for SignatureAlgorithms test
"DSA",
// Signature Algorithm: dsaWithSHA1
@ -1170,7 +1224,41 @@ public abstract class SSLContextTemplate {
"ofaiiWffsaytVvotmT6+atElvAMbAua42V+nAQKBgHtIn3mYMHLriYGhQzpkFEA2\n" +
"8YcAMlKppueOMAKVy8nLu2r3MidmLAhMiKJQKG45I3Yg0/t/25tXLiOPJlwrOebh\n" +
"xQqUBI/JUOIpGAEnr48jhOXnCS+i+z294G5U/RgjXrlR4bCPvrtCmwzWwe0h79w2\n" +
"Q2hO5ZTW6UD9CVA85whf");
"Q2hO5ZTW6UD9CVA85whf"),
DSA_SHA1_1024_EXPIRED( // for NullCerts test
"DSA",
// Signature Algorithm: dsaWithSHA1
// Issuer: C = US, ST = CA, L = Cupertino, O = Dummy, OU = Dummy, CN = Example
// Validity
// Not Before: Mar 11 06:33:43 2001 GMT
// Not After : Dec 6 06:33:43 2003 GMT
"-----BEGIN CERTIFICATE-----\n" +
"MIIC9TCCArMCBDqrHEcwCwYHKoZIzjgEAwUAMGAxCzAJBgNVBAYTAlVTMQswCQYD\n" +
"VQQIEwJDQTESMBAGA1UEBxMJQ3VwZXJ0aW5vMQ4wDAYDVQQKEwVEdW1teTEOMAwG\n" +
"A1UECxMFRHVtbXkxEDAOBgNVBAMTB0V4YW1wbGUwHhcNMDEwMzExMDYzMzQzWhcN\n" +
"MDMxMjA2MDYzMzQzWjBgMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNV\n" +
"BAcTCUN1cGVydGlubzEOMAwGA1UEChMFRHVtbXkxDjAMBgNVBAsTBUR1bW15MRAw\n" +
"DgYDVQQDEwdFeGFtcGxlMIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIp\n" +
"Ut9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7\n" +
"gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1\n" +
"VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUC\n" +
"gYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCB\n" +
"gLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6\n" +
"ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAPqO/boo\n" +
"m+n+tAdqetoQ2ZRoS8BpYIEFOJt4OJ8flb52T3vGNNdapq9pbjN+HKrT62ggNhZs\n" +
"hajxYwFCpaidKZuGQXvvpHkj0UHjhZFry6Dd41cfEG13dfgACf8uooeTzPGFvUPv\n" +
"TCHcPRh820BZMeOqdS4PjWPyf3HEtiTtFWR7MAsGByqGSM44BAMFAAMvADAsAhRH\n" +
"dZQef04MwUTlAALf2J6PIcgmQAIUB2H/RnW2tVg+mbCl5jQLfudsEhI=\n" +
"-----END CERTIFICATE-----",
"MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdS\n" +
"PO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVCl\n" +
"pJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith\n" +
"1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7L\n" +
"vKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3\n" +
"zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImo\n" +
"g9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoEFgIUZC+jBuwAPm8ejkybfAm2gT49ApY="
);
final String keyAlgo;
final String certStr;

@ -92,14 +92,22 @@ public class SSLEngineTemplate extends SSLContextTemplate {
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());
clientOut = createClientOutputBuffer();
serverOut = createServerOutputBuffer();
}
protected ByteBuffer createServerOutputBuffer() {
return ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
}
//
// Protected methods could be used to customize the test case.
//
protected ByteBuffer createClientOutputBuffer() {
return ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
}
/*
* Configure the client side engine.
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2023, 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
@ -26,7 +26,7 @@
* @bug 8044860
* @summary Vectors and fixed length fields should be verified
* for allowed sizes.
* @library /test/lib
* @library /test/lib /javax/net/ssl/templates
* @modules java.base/sun.security.ssl
* @run main/othervm LengthCheckTest
* @key randomness
@ -70,7 +70,6 @@
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
import java.util.List;
@ -79,7 +78,7 @@ import java.util.Iterator;
import jdk.test.lib.security.SecurityUtils;
public class LengthCheckTest {
public class LengthCheckTest extends SSLEngineTemplate {
/*
* Enables logging of the SSLEngine operations.
@ -98,41 +97,9 @@ public class LengthCheckTest {
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;
@ -176,20 +143,20 @@ public class LengthCheckTest {
// Send Client Hello
clientResult = clientEngine.wrap(clientOut, cTOs);
log("client wrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
cTOs.flip();
dumpByteBuffer("CLIENT-TO-SERVER", cTOs);
// Server consumes Client Hello
serverResult = serverEngine.unwrap(cTOs, serverIn);
log("server unwrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
cTOs.compact();
// Server generates ServerHello/Cert/Done record
serverResult = serverEngine.wrap(serverOut, sTOc);
log("server wrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
sTOc.flip();
// Intercept the ServerHello messages and instead send
@ -220,19 +187,19 @@ public class LengthCheckTest {
gotException = true;
}
log("client unwrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
}
} else {
dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
log("client unwrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
}
sTOc.compact();
// The Client should now send a TLS Alert
clientResult = clientEngine.wrap(clientOut, cTOs);
log("client wrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
cTOs.flip();
dumpByteBuffer("CLIENT-TO-SERVER", cTOs);
@ -264,7 +231,7 @@ public class LengthCheckTest {
// Server consumes Client Hello
serverResult = serverEngine.unwrap(evilClientHello, serverIn);
log("server unwrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
evilClientHello.compact();
// Under normal circumstances this should be a ServerHello
@ -273,7 +240,7 @@ public class LengthCheckTest {
try {
serverResult = serverEngine.wrap(serverOut, sTOc);
log("server wrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
} catch (SSLProtocolException ssle) {
log("Received expected SSLProtocolException: " + ssle);
gotException = true;
@ -282,7 +249,7 @@ public class LengthCheckTest {
// We expect to see the server generate an alert here
serverResult = serverEngine.wrap(serverOut, sTOc);
log("server wrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
sTOc.flip();
dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
@ -326,26 +293,7 @@ public class LengthCheckTest {
* 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;
super();
switch (testName) {
case "ServSendLongID":
@ -378,10 +326,8 @@ public class LengthCheckTest {
* sections of code.
*/
private void runTest() throws Exception {
boolean dataDone = false;
createSSLEngines();
createBuffers();
configureSSLEngine();
// createBuffers();
handshakeTest.execTest();
}
@ -390,19 +336,17 @@ public class LengthCheckTest {
* Using the SSLContext created during object creation,
* create/configure the SSLEngines we'll use for this test.
*/
private void createSSLEngines() throws Exception {
private void configureSSLEngine() 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
@ -413,84 +357,6 @@ public class LengthCheckTest {
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
*/

@ -30,6 +30,7 @@
* @test
* @bug 6956398 8301700
* @summary make ephemeral DH key match the length of the certificate key
* @library /javax/net/ssl/templates
* @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false
* DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1643 267
* @run main/othervm -Djsse.enableFFDHE=false
@ -122,18 +123,10 @@
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.nio.*;
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 {
public class DHEKeySizing extends SSLEngineTemplate {
private final static boolean debug = true;
@ -145,89 +138,6 @@ public class DHEKeySizing {
// 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,
@ -268,130 +178,127 @@ public class DHEKeySizing {
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
SSLEngineResult result1; // clientEngine's results from last operation
SSLEngineResult result2; // serverEngine's results from last operation
String[] suites = new String [] {cipherSuite};
ssle1.setEnabledCipherSuites(suites);
ssle2.setEnabledCipherSuites(suites);
clientEngine.setEnabledCipherSuites(suites);
serverEngine.setEnabledCipherSuites(suites);
log("======================================");
log("===================");
log("client hello");
result1 = ssle1.wrap(appOut1, oneToTwo);
checkResult(appOut1, oneToTwo, result1,
result1 = clientEngine.wrap(clientOut, cTOs);
checkResult(clientOut, cTOs, result1,
Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
oneToTwo.flip();
cTOs.flip();
result2 = ssle2.unwrap(oneToTwo, appIn2);
checkResult(oneToTwo, appIn2, result2,
result2 = serverEngine.unwrap(cTOs, serverIn);
checkResult(cTOs, serverIn, result2,
Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
runDelegatedTasks(ssle2);
oneToTwo.compact();
runDelegatedTasks(serverEngine);
cTOs.compact();
log("===================");
log("ServerHello");
result2 = ssle2.wrap(appOut2, twoToOne);
checkResult(appOut2, twoToOne, result2,
result2 = serverEngine.wrap(serverOut, sTOc);
checkResult(serverOut, sTOc, result2,
Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
twoToOne.flip();
sTOc.flip();
log("Message length of ServerHello series: " + twoToOne.remaining());
if (twoToOne.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) ||
twoToOne.remaining() > lenServerKeyEx) {
log("Message length of ServerHello series: " + sTOc.remaining());
if (sTOc.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) ||
sTOc.remaining() > lenServerKeyEx) {
throw new Exception(
"Expected to generate ServerHello series messages of " +
lenServerKeyEx + " bytes, but not " + twoToOne.remaining());
lenServerKeyEx + " bytes, but not " + sTOc.remaining());
}
result1 = ssle1.unwrap(twoToOne, appIn1);
checkResult(twoToOne, appIn1, result1,
result1 = clientEngine.unwrap(sTOc, clientIn);
checkResult(sTOc, clientIn, result1,
Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0);
runDelegatedTasks(ssle1);
twoToOne.compact();
runDelegatedTasks(clientEngine);
sTOc.compact();
log("===================");
log("Key Exchange");
result1 = ssle1.wrap(appOut1, oneToTwo);
checkResult(appOut1, oneToTwo, result1,
result1 = clientEngine.wrap(clientOut, cTOs);
checkResult(clientOut, cTOs, result1,
Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
oneToTwo.flip();
cTOs.flip();
log("Message length of ClientKeyExchange: " + oneToTwo.remaining());
if (oneToTwo.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) ||
oneToTwo.remaining() > lenClientKeyEx) {
log("Message length of ClientKeyExchange: " + cTOs.remaining());
if (cTOs.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) ||
cTOs.remaining() > lenClientKeyEx) {
throw new Exception(
"Expected to generate ClientKeyExchange message of " +
lenClientKeyEx + " bytes, but not " + oneToTwo.remaining());
lenClientKeyEx + " bytes, but not " + cTOs.remaining());
}
result2 = ssle2.unwrap(oneToTwo, appIn2);
checkResult(oneToTwo, appIn2, result2,
result2 = serverEngine.unwrap(cTOs, serverIn);
checkResult(cTOs, serverIn, result2,
Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
runDelegatedTasks(ssle2);
oneToTwo.compact();
runDelegatedTasks(serverEngine);
cTOs.compact();
log("===================");
log("Client CCS");
result1 = ssle1.wrap(appOut1, oneToTwo);
checkResult(appOut1, oneToTwo, result1,
result1 = clientEngine.wrap(clientOut, cTOs);
checkResult(clientOut, cTOs, result1,
Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
oneToTwo.flip();
cTOs.flip();
result2 = ssle2.unwrap(oneToTwo, appIn2);
checkResult(oneToTwo, appIn2, result2,
result2 = serverEngine.unwrap(cTOs, serverIn);
checkResult(cTOs, serverIn, result2,
Status.OK, HandshakeStatus.NEED_UNWRAP,
result1.bytesProduced(), 0);
oneToTwo.compact();
cTOs.compact();
log("===================");
log("Client Finished");
result1 = ssle1.wrap(appOut1, oneToTwo);
checkResult(appOut1, oneToTwo, result1,
result1 = clientEngine.wrap(clientOut, cTOs);
checkResult(clientOut, cTOs, result1,
Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
oneToTwo.flip();
cTOs.flip();
result2 = ssle2.unwrap(oneToTwo, appIn2);
checkResult(oneToTwo, appIn2, result2,
result2 = serverEngine.unwrap(cTOs, serverIn);
checkResult(cTOs, serverIn, result2,
Status.OK, HandshakeStatus.NEED_WRAP,
result1.bytesProduced(), 0);
oneToTwo.compact();
cTOs.compact();
log("===================");
log("Server CCS");
result2 = ssle2.wrap(appOut2, twoToOne);
checkResult(appOut2, twoToOne, result2,
result2 = serverEngine.wrap(serverOut, sTOc);
checkResult(serverOut, sTOc, result2,
Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
twoToOne.flip();
sTOc.flip();
result1 = ssle1.unwrap(twoToOne, appIn1);
checkResult(twoToOne, appIn1, result1,
result1 = clientEngine.unwrap(sTOc, clientIn);
checkResult(sTOc, clientIn, result1,
Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0);
twoToOne.compact();
sTOc.compact();
log("===================");
log("Server Finished");
result2 = ssle2.wrap(appOut2, twoToOne);
checkResult(appOut2, twoToOne, result2,
result2 = serverEngine.wrap(serverOut, sTOc);
checkResult(serverOut, sTOc, result2,
Status.OK, HandshakeStatus.FINISHED, 0, -1);
twoToOne.flip();
sTOc.flip();
result1 = ssle1.unwrap(twoToOne, appIn1);
checkResult(twoToOne, appIn1, result1,
result1 = clientEngine.unwrap(sTOc, clientIn);
checkResult(sTOc, clientIn, result1,
Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0);
twoToOne.compact();
sTOc.compact();
log("===================");
log("Check Session/Ciphers");
String cs = ssle1.getSession().getCipherSuite();
String cs = clientEngine.getSession().getCipherSuite();
if (!cs.equals(suites[0])) {
throw new Exception("suites not equal: " + cs + "/" + suites[0]);
}
cs = ssle2.getSession().getCipherSuite();
cs = serverEngine.getSession().getCipherSuite();
if (!cs.equals(suites[0])) {
throw new Exception("suites not equal: " + cs + "/" + suites[0]);
}
@ -428,84 +335,36 @@ public class DHEKeySizing {
*/
public DHEKeySizing() throws Exception {
sslc = getSSLContext();
super();
}
/*
* 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;
@Override
protected SSLEngine configureServerEngine(SSLEngine engine) {
engine.setNeedClientAuth(false);
engine.setUseClientMode(false);
return engine;
}
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("");
@Override
protected SSLContext createServerSSLContext() throws Exception {
return createSSLContext(null, new Cert[]{Cert.CA_SHA1_RSA_2048},
getServerContextParameters());
}
private static void runDelegatedTasks(SSLEngine engine) throws Exception {
@Override
protected SSLContext createClientSSLContext() throws Exception {
return createSSLContext(new Cert[]{Cert.CA_SHA1_RSA_2048}, null,
getClientContextParameters());
}
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
log("running delegated task...");
runnable.run();
}
@Override
protected ContextParameters getClientContextParameters() {
return new ContextParameters("TLSv1", "PKIX", "NewSunX509");
}
@Override
protected ContextParameters getServerContextParameters() {
return new ContextParameters("TLSv1", "PKIX", "NewSunX509");
}
private static void log(String str) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2023, 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
@ -25,7 +25,7 @@
* @test
* @bug 7126889
* @summary Incorrect SSLEngine debug output
* @library /test/lib
* @library /test/lib /javax/net/ssl/templates
* @run main DebugReportsOneExtraByte
*/
/*
@ -74,54 +74,19 @@
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.security.SecurityUtils;
public class DebugReportsOneExtraByte {
public class DebugReportsOneExtraByte extends SSLEngineTemplate {
/*
* Enables logging of the SSLEngine operations.
*/
private static boolean logging = true;
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;
/*
* Main entry point for this test.
*/
@ -147,26 +112,38 @@ public class DebugReportsOneExtraByte {
* Create an initialized SSLContext to use for these tests.
*/
public DebugReportsOneExtraByte() throws Exception {
super();
}
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
@Override
protected SSLEngine configureServerEngine(SSLEngine serverEngine) {
serverEngine.setUseClientMode(false);
// Force a block-oriented ciphersuite.
serverEngine.setEnabledCipherSuites(
new String [] {"TLS_RSA_WITH_AES_128_CBC_SHA"});
return serverEngine;
}
char[] passphrase = "passphrase".toCharArray();
@Override
protected ContextParameters getClientContextParameters() {
return new ContextParameters("TLSv1", "PKIX", "NewSunX509");
}
ks.load(new FileInputStream(keyFilename), passphrase);
ts.load(new FileInputStream(trustFilename), passphrase);
@Override
protected ContextParameters getServerContextParameters() {
return new ContextParameters("TLSv1", "PKIX", "NewSunX509");
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
@Override
protected ByteBuffer createClientOutputBuffer() {
// No need to write anything on the client side, it will
// just confuse the output.
return ByteBuffer.wrap("".getBytes());
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
SSLContext sslCtx = SSLContext.getInstance("TLSv1");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslc = sslCtx;
@Override
protected ByteBuffer createServerOutputBuffer() {
return ByteBuffer.wrap("Hi Client!".getBytes());
}
/*
@ -189,9 +166,6 @@ public class DebugReportsOneExtraByte {
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
@ -217,11 +191,11 @@ public class DebugReportsOneExtraByte {
clientResult = clientEngine.wrap(clientOut, cTOs);
log("client wrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
serverResult = serverEngine.wrap(serverOut, sTOc);
log("server wrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
// Next wrap will split.
if (serverOut.position() == 1) {
@ -235,11 +209,11 @@ public class DebugReportsOneExtraByte {
clientResult = clientEngine.unwrap(sTOc, clientIn);
log("client unwrap: ", clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
serverResult = serverEngine.unwrap(cTOs, serverIn);
log("server unwrap: ", serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
cTOs.compact();
sTOc.compact();
@ -266,111 +240,10 @@ public class DebugReportsOneExtraByte {
}
}
/*
* 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);
// Force a block-oriented ciphersuite.
serverEngine.setEnabledCipherSuites(
new String [] {"TLS_RSA_WITH_AES_128_CBC_SHA"});
/*
* 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);
// No need to write anything on the client side, it will
// just confuse the output.
clientOut = ByteBuffer.wrap("".getBytes());
// 10 bytes long
serverOut = ByteBuffer.wrap("Hi Client!".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
*/

@ -26,6 +26,7 @@
* @bug 4453053
* @summary If a server shuts down correctly during handshaking, the client
* doesn't see it.
* @library /javax/net/ssl/templates
* @run main/othervm NullCerts
*
* SunJSSE does not support dynamic system properties, no way to re-use
@ -34,40 +35,11 @@
*/
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
public class NullCerts {
public class NullCerts extends 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.
*/
private static boolean separateServerThread = true;
/*
* Where do we find the keystores?
*/
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;
@ -81,29 +53,22 @@ public class NullCerts {
* smart about it....
*/
@Override
protected void configureServerSocket(SSLServerSocket socket) {
socket.setNeedClientAuth(true);
socket.setUseClientMode(false);
}
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
private void doServerSide() throws Exception {
SSLServerSocketFactory sslssf =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort, 3);
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();
@Override
protected void runServerApplication(SSLSocket socket) throws Exception {
InputStream sslIS = socket.getInputStream();
OutputStream sslOS = socket.getOutputStream();
try {
sslIS.read();
@ -115,7 +80,6 @@ public class NullCerts {
+ e.toString());
}
sslSocket.close();
System.out.println("Server done and exiting!");
}
@ -125,36 +89,11 @@ public class NullCerts {
* 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);
}
@Override
protected void runClientApplication(SSLSocket sslSocket) throws Exception {
System.out.println("Starting test");
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore uks = KeyStore.getInstance("JKS");
SSLContext ctx = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
uks.load(new FileInputStream(unknownFilename), cpasswd);
kmf.init(uks, cpasswd);
ks.load(new FileInputStream(trustFilename), cpasswd);
tmf.init(ks);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory sslsf =
(SSLSocketFactory) ctx.getSocketFactory();
SSLSocket sslSocket = (SSLSocket)
sslsf.createSocket("localhost", serverPort);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
@ -163,7 +102,6 @@ public class NullCerts {
sslOS.flush();
sslIS.read();
sslSocket.close();
} catch (IOException e) {
String str =
"\nYou will either see a bad_certificate SSLException\n" +
@ -174,131 +112,21 @@ public class NullCerts {
}
}
/*
* =============================================================
* The remainder is just support stuff
*/
// use any free port by default
volatile int serverPort = 0;
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;
private final static String unknownFilename =
System.getProperty("test.src", ".") + "/" + pathToStores +
"/" + "unknown_keystore";
@Override
protected KeyManager createClientKeyManager() throws Exception {
return createKeyManager(new Cert[]{Cert.DSA_SHA1_1024_EXPIRED},
getClientContextParameters());
}
// Used for running test standalone
public static void main(String[] args) throws Exception {
String testRoot = System.getProperty("test.src", ".");
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 NullCerts();
}
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.
*/
NullCerts() 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();
}
new NullCerts().run();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2023, 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
@ -31,6 +31,7 @@
* @bug 4969799
* @summary javax.net.ssl.SSLSocket.SSLSocket(InetAddress,int) shouldn't
* throw exception
* @library /javax/net/ssl/templates
* @run main/othervm CloseEngineException
*/
@ -40,128 +41,85 @@
//
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
// Note that this test case depends on JSSE provider implementation details.
public class CloseEngineException {
public class CloseEngineException extends SSLEngineTemplate {
private static boolean debug = true;
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 result1; // clientEngine's results from last operation
SSLEngineResult result2; // ssle2's results from last operation
while (!isEngineClosed(ssle1) && !isEngineClosed(ssle2)) {
while (!isEngineClosed(clientEngine) && !isEngineClosed(serverEngine)) {
log("================");
if (!isEngineClosed(ssle1)) {
result1 = ssle1.wrap(appOut1, oneToTwo);
runDelegatedTasks(result1, ssle1);
if (!isEngineClosed(clientEngine)) {
result1 = clientEngine.wrap(clientOut, cTOs);
runDelegatedTasks(clientEngine);
log("wrap1: " + result1);
log("oneToTwo = " + oneToTwo);
log("oneToTwo = " + cTOs);
log("");
oneToTwo.flip();
cTOs.flip();
}
if (!isEngineClosed(ssle2)) {
result2 = ssle2.wrap(appOut2, twoToOne);
runDelegatedTasks(result2, ssle2);
if (!isEngineClosed(serverEngine)) {
result2 = serverEngine.wrap(serverOut, sTOc);
runDelegatedTasks(serverEngine);
log("wrap2: " + result2);
log("twoToOne = " + twoToOne);
log("twoToOne = " + sTOc);
twoToOne.flip();
sTOc.flip();
}
log("----");
if (!isEngineClosed(ssle1) && !dataDone) {
if (!isEngineClosed(clientEngine) && !dataDone) {
log("--");
result1 = ssle1.unwrap(twoToOne, appIn1);
runDelegatedTasks(result1, ssle1);
result1 = clientEngine.unwrap(sTOc, clientIn);
runDelegatedTasks(clientEngine);
log("unwrap1: " + result1);
log("twoToOne = " + twoToOne);
log("twoToOne = " + sTOc);
log("");
twoToOne.compact();
sTOc.compact();
}
if (!isEngineClosed(ssle2)) {
if (!isEngineClosed(serverEngine)) {
log("---");
result2 = ssle2.unwrap(oneToTwo, appIn2);
runDelegatedTasks(result2, ssle2);
result2 = serverEngine.unwrap(cTOs, serverIn);
runDelegatedTasks(serverEngine);
log("unwrap2: " + result2);
log("oneToTwo = " + oneToTwo);
log("oneToTwo = " + cTOs);
oneToTwo.compact();
cTOs.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())) {
if (!dataDone && (clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
checkTransfer(appOut1, appIn2);
checkTransfer(appOut2, appIn1);
checkTransfer(clientOut, serverIn);
checkTransfer(serverOut, clientIn);
log("Closing ssle1's *OUTBOUND*...");
ssle1.closeOutbound();
log("Closing clientEngine's *OUTBOUND*...");
clientEngine.closeOutbound();
dataDone = true;
try {
/*
* Check that closed Outbound generates.
*/
ssle1.beginHandshake();
clientEngine.beginHandshake();
throw new Exception(
"TEST FAILED: didn't throw Exception");
} catch (SSLException e) {
@ -174,7 +132,7 @@ public class CloseEngineException {
/*
* Check that closed Inbound generates.
*/
ssle2.beginHandshake();
serverEngine.beginHandshake();
throw new Exception(
"TEST FAILED: didn't throw Exception");
} catch (SSLException e) {
@ -184,12 +142,7 @@ public class CloseEngineException {
public static void main(String args[]) throws Exception {
CloseEngineException test;
test = new CloseEngineException();
test.createSSLEngines();
CloseEngineException test = new CloseEngineException();
test.runTest();
System.err.println("Test Passed.");
@ -202,90 +155,20 @@ public class CloseEngineException {
*/
public CloseEngineException() throws Exception {
sslc = getSSLContext(keyFilename, trustFilename);
super();
}
/*
* 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();
}
}
@Override
protected SSLEngine configureServerEngine(SSLEngine engine) {
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
return engine;
}
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.err.println(str);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2023, 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
@ -30,6 +30,7 @@
* @test
* @bug 5019096
* @summary Add scatter/gather APIs for SSLEngine
* @library /javax/net/ssl/templates
* @run main/othervm CloseStart
*/
@ -38,26 +39,8 @@
//
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;
public class CloseStart extends SSLContextTemplate {
private static void checkDone(SSLEngine ssle) throws Exception {
if (!ssle.isInboundDone()) {
@ -74,14 +57,17 @@ public class CloseStart {
}
public static void main(String args[]) throws Exception {
new CloseStart().run();
}
SSLEngine ssle = createSSLEngine(keyFilename, trustFilename);
private void run() throws Exception {
SSLEngine ssle = createSSLEngine();
ssle.closeInbound();
if (!ssle.isInboundDone()) {
throw new Exception("isInboundDone isn't done");
}
ssle = createSSLEngine(keyFilename, trustFilename);
ssle = createSSLEngine();
ssle.closeOutbound();
if (!ssle.isOutboundDone()) {
throw new Exception("isOutboundDone isn't done");
@ -93,30 +79,10 @@ public class CloseStart {
/*
* Create an initialized SSLContext to use for this test.
*/
static private SSLEngine createSSLEngine(String keyFile, String trustFile)
throws Exception {
private SSLEngine createSSLEngine() 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);
SSLContext sslCtx = createClientSSLContext();
SSLEngine ssle = sslCtx.createSSLEngine("client", 1001);
ssle.setUseClientMode(true);
return ssle;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2023, 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
@ -30,72 +30,38 @@
* @test
* @bug 4969459
* @summary Delegated tasks are not reflecting the subclasses of SSLException
* @library /javax/net/ssl/templates
* @run main/othervm DelegatedTaskWrongException
*/
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
public class DelegatedTaskWrongException {
public class DelegatedTaskWrongException extends SSLEngineTemplate {
private static boolean debug = false;
private SSLContext sslc;
private SSLEngine ssle1; // client
private SSLEngine ssle2; // server
@Override
protected SSLEngine configureServerEngine(SSLEngine engine) {
engine.setUseClientMode(false);
engine.setEnabledProtocols(new String [] { "TLSv1" });
return engine;
}
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);
ssle1.setEnabledProtocols(new String [] { "SSLv3" });
ssle2.setEnabledProtocols(new String [] { "TLSv1" });
@Override
protected SSLEngine configureClientEngine(SSLEngine engine) {
engine.setUseClientMode(true);
engine.setEnabledProtocols(new String [] { "SSLv3" });
return engine;
}
private void runTest() throws Exception {
boolean dataDone = false;
createSSLEngines();
createBuffers();
clientEngine.wrap(clientOut, cTOs);
cTOs.flip();
SSLEngineResult result1; // ssle1's results from last operation
SSLEngineResult result2; // ssle2's results from last operation
result1 = ssle1.wrap(appOut1, oneToTwo);
oneToTwo.flip();
result2 = ssle2.unwrap(oneToTwo, appIn2);
runDelegatedTasks(result2, ssle2);
serverEngine.unwrap(cTOs, serverIn);
runDelegatedTasks(serverEngine);
try {
/*
@ -103,7 +69,7 @@ public class DelegatedTaskWrongException {
* If this changes, we'll need to update this test.
* Anything else and we fail.
*/
result2 = ssle2.unwrap(oneToTwo, appIn2);
serverEngine.unwrap(cTOs, serverIn);
throw new Exception(
"TEST FAILED: Didn't generate any exception");
} catch (SSLHandshakeException e) {
@ -119,12 +85,7 @@ public class DelegatedTaskWrongException {
// and keys used in this test are not disabled.
Security.setProperty("jdk.tls.disabledAlgorithms", "");
DelegatedTaskWrongException test;
test = new DelegatedTaskWrongException();
test.createSSLEngines();
DelegatedTaskWrongException test = new DelegatedTaskWrongException();
test.runTest();
System.out.println("Test Passed.");
@ -137,88 +98,7 @@ public class DelegatedTaskWrongException {
*/
public DelegatedTaskWrongException() 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());
super();
}
private static void log(String str) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2023, 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
@ -30,44 +30,21 @@
* @test
* @bug 6728126
* @summary Parsing Extensions in Client Hello message is done in a wrong way
* @library /test/lib
* @library /test/lib /javax/net/ssl/templates
* @run main/othervm EmptyExtensionData
*/
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
import jdk.test.lib.security.SecurityUtils;
public class EmptyExtensionData {
public class EmptyExtensionData extends SSLContextTemplate {
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 runTest(SSLEngine ssle) throws Exception {
private void runTest(SSLEngine ssle) throws Exception {
// a client hello message with an empty extension data
byte[] msg_clihello = {
(byte)0x16, (byte)0x03, (byte)0x01, (byte)0x00,
@ -138,7 +115,7 @@ public class EmptyExtensionData {
* 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,
private void runDelegatedTasks(SSLEngineResult result,
SSLEngine engine) throws Exception {
if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
@ -159,46 +136,17 @@ public class EmptyExtensionData {
public static void main(String args[]) throws Exception {
// Re-enable TLSv1 since test depends on it.
SecurityUtils.removeFromDisabledTlsAlgs("TLSv1");
new EmptyExtensionData().run();
}
SSLEngine ssle = createSSLEngine(keyFilename, trustFilename);
private void run() throws Exception {
SSLEngine ssle = createServerSSLContext().createSSLEngine();
ssle.setUseClientMode(false);
runTest(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();
ssle.setUseClientMode(false);
return ssle;
}
private static void log(String str) {
if (debug) {
System.out.println(str);

@ -1,5 +1,5 @@
/*
* Copyright (c) 2004, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2023, 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
@ -30,67 +30,34 @@
* @test
* @bug 4980882 8207250 8237474
* @summary SSLEngine should enforce setUseClientMode
* @library /javax/net/ssl/templates
* @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 {
public class EngineEnforceUseClientMode extends SSLEngineTemplate {
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
private SSLEngine serverEngine2; // server
private SSLEngine serverEngine3; // server
private SSLEngine serverEngine4; // server
/*
* 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 createAdditionalSSLEngines() throws Exception {
SSLContext sslc = createServerSSLContext();
/*
* Note, these are not initialized to client/server
*/
ssle3 = sslc.createSSLEngine();
ssle4 = sslc.createSSLEngine();
ssle5 = sslc.createSSLEngine();
serverEngine2 = sslc.createSSLEngine();
serverEngine3 = sslc.createSSLEngine();
serverEngine4 = sslc.createSSLEngine();
//Check default SSLEngine role.
if (ssle5.getUseClientMode()) {
if (serverEngine4.getUseClientMode()) {
throw new RuntimeException("Expected default role to be server");
}
@ -98,8 +65,7 @@ public class EngineEnforceUseClientMode {
private void runTest() throws Exception {
createSSLEngines();
createBuffers();
createAdditionalSSLEngines();
/*
* First try the engines with no client/server initialization
@ -107,35 +73,35 @@ public class EngineEnforceUseClientMode {
*/
try {
System.out.println("Testing wrap()");
ssle3.wrap(appOut1, oneToTwo);
serverEngine2.wrap(clientOut, cTOs);
throw new RuntimeException(
"wrap(): Didn't catch the exception properly");
} catch (IllegalStateException e) {
System.out.println("Caught the correct exception.");
oneToTwo.flip();
if (oneToTwo.hasRemaining()) {
cTOs.flip();
if (cTOs.hasRemaining()) {
throw new Exception("wrap generated data");
}
oneToTwo.clear();
cTOs.clear();
}
try {
System.out.println("Testing unwrap()");
ssle4.unwrap(oneToTwo, appIn1);
serverEngine3.unwrap(cTOs, clientIn);
throw new RuntimeException(
"unwrap(): Didn't catch the exception properly");
} catch (IllegalStateException e) {
System.out.println("Caught the correct exception.");
appIn1.flip();
if (appIn1.hasRemaining()) {
clientIn.flip();
if (clientIn.hasRemaining()) {
throw new Exception("unwrap generated data");
}
appIn1.clear();
clientIn.clear();
}
try {
System.out.println("Testing beginHandshake()");
ssle5.beginHandshake();
serverEngine4.beginHandshake();
throw new RuntimeException(
"unwrap(): Didn't catch the exception properly");
} catch (IllegalStateException e) {
@ -147,60 +113,60 @@ public class EngineEnforceUseClientMode {
SSLEngineResult result1; // ssle1's results from last operation
SSLEngineResult result2; // ssle2's results from last operation
while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) {
while (!isEngineClosed(clientEngine) || !isEngineClosed(serverEngine)) {
log("================");
result1 = ssle1.wrap(appOut1, oneToTwo);
result2 = ssle2.wrap(appOut2, twoToOne);
result1 = clientEngine.wrap(clientOut, cTOs);
result2 = serverEngine.wrap(serverOut, sTOc);
log("wrap1: " + result1);
log("oneToTwo = " + oneToTwo);
log("oneToTwo = " + cTOs);
log("");
log("wrap2: " + result2);
log("twoToOne = " + twoToOne);
log("twoToOne = " + sTOc);
runDelegatedTasks(result1, ssle1);
runDelegatedTasks(result2, ssle2);
runDelegatedTasks(clientEngine);
runDelegatedTasks(serverEngine);
oneToTwo.flip();
twoToOne.flip();
cTOs.flip();
sTOc.flip();
log("----");
result1 = ssle1.unwrap(twoToOne, appIn1);
result2 = ssle2.unwrap(oneToTwo, appIn2);
result1 = clientEngine.unwrap(sTOc, clientIn);
result2 = serverEngine.unwrap(cTOs, serverIn);
log("unwrap1: " + result1);
log("twoToOne = " + twoToOne);
log("twoToOne = " + sTOc);
log("");
log("unwrap2: " + result2);
log("oneToTwo = " + oneToTwo);
log("oneToTwo = " + cTOs);
runDelegatedTasks(result1, ssle1);
runDelegatedTasks(result2, ssle2);
runDelegatedTasks(clientEngine);
runDelegatedTasks(serverEngine);
oneToTwo.compact();
twoToOne.compact();
cTOs.compact();
sTOc.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())) {
if (!dataDone && (clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
checkTransfer(appOut1, appIn2);
checkTransfer(appOut2, appIn1);
checkTransfer(clientOut, serverIn);
checkTransfer(serverOut, clientIn);
// Should not be able to set mode now, no matter if
// it is the same of different.
System.out.println("Try changing modes...");
for (boolean b : new Boolean[] {true, false}) {
try {
ssle2.setUseClientMode(b);
serverEngine.setUseClientMode(b);
throw new RuntimeException(
"setUseClientMode(" + b + "): " +
"Didn't catch the exception properly");
@ -216,12 +182,8 @@ public class EngineEnforceUseClientMode {
public static void main(String args[]) throws Exception {
EngineEnforceUseClientMode test;
test = new EngineEnforceUseClientMode();
test.createSSLEngines();
EngineEnforceUseClientMode test = new EngineEnforceUseClientMode();
test.createAdditionalSSLEngines();
test.runTest();
System.out.println("Test Passed.");
@ -234,89 +196,13 @@ public class EngineEnforceUseClientMode {
*/
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();
}
}
super();
}
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) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2023, 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
@ -31,6 +31,7 @@
* @bug 6207322
* @summary SSLEngine is returning a premature FINISHED message when doing
* an abbreviated handshake.
* @library /javax/net/ssl/templates
* @run main/othervm RehandshakeFinished
* @author Brad Wetmore
*/
@ -86,11 +87,9 @@
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
public class RehandshakeFinished {
public class RehandshakeFinished extends SSLContextTemplate {
/*
* Enables logging of the SSLEngine operations.
@ -108,7 +107,7 @@ public class RehandshakeFinished {
*/
private static boolean debug = false;
static private SSLContext sslc;
private final SSLContext sslc;
private SSLEngine clientEngine; // client Engine
private ByteBuffer clientOut; // write side of clientEngine
@ -126,46 +125,8 @@ public class RehandshakeFinished {
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("TLSv1.2");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslc = sslCtx;
} catch (Exception e) {
loadException = e;
}
public RehandshakeFinished() throws Exception {
sslc = createServerSSLContext();
}
/*
@ -176,14 +137,10 @@ public class RehandshakeFinished {
System.setProperty("javax.net.debug", "all");
}
if (loadException != null) {
throw loadException;
}
RehandshakeFinished test = new RehandshakeFinished();
// Prime the session cache with a good session
// Second connection should be a simple session resumption.
if ((new RehandshakeFinished().runTest()) !=
new RehandshakeFinished().runRehandshake()) {
if (test.runTest() != test.runRehandshake()) {
throw new Exception("Sessions not equivalent");
}
@ -412,6 +369,11 @@ public class RehandshakeFinished {
clientEngine.setUseClientMode(true);
}
@Override
protected ContextParameters getServerContextParameters() {
return new ContextParameters("TLSv1.2", "PKIX", "NewSunX509");
}
/*
* Create and size the buffers appropriately.
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2023, 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
@ -28,6 +28,7 @@
* @test
* @bug 6492872
* @summary Deadlock in SSLEngine
* @library /javax/net/ssl/templates
* @run main/othervm SSLEngineDeadlock
* @author Brad R. Wetmore
*/
@ -70,12 +71,9 @@
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 {
public class SSLEngineDeadlock extends SSLEngineTemplate {
/*
* Enables logging of the SSLEngine operations.
@ -93,41 +91,8 @@ public class SSLEngineDeadlock {
*/
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.
*/
@ -154,26 +119,7 @@ public class SSLEngineDeadlock {
* 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;
super();
}
/*
@ -214,9 +160,6 @@ public class SSLEngineDeadlock {
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
@ -287,82 +230,10 @@ public class SSLEngineDeadlock {
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
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2023, 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
@ -29,6 +29,7 @@
* @bug 8207317
* @summary SSLEngine negotiation fail Exception behavior changed from
* fail-fast to fail-lazy
* @library /javax/net/ssl/templates
* @run main/othervm SSLEngineFailedALPN
*/
/**
@ -68,11 +69,8 @@
*/
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;
public class SSLEngineFailedALPN {
public class SSLEngineFailedALPN extends SSLEngineTemplate {
/*
* Enables logging of the SSLEngine operations.
@ -90,39 +88,6 @@ public class SSLEngineFailedALPN {
*/
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 = "../../../../javax/net/ssl/etc";
private static final String keyStoreFile = "keystore";
private static final String trustStoreFile = "truststore";
private static final char[] passphrase = "passphrase".toCharArray();
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.
*/
@ -141,24 +106,7 @@ public class SSLEngineFailedALPN {
* Create an initialized SSLContext to use for these tests.
*/
public SSLEngineFailedALPN() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
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;
super();
}
/*
@ -181,9 +129,6 @@ public class SSLEngineFailedALPN {
private void runTest() throws Exception {
boolean dataDone = false;
createSSLEngines();
createBuffers();
// results from client's last operation
SSLEngineResult clientResult;
@ -309,113 +254,33 @@ public class SSLEngineFailedALPN {
log("\tisOutboundDone(): " + engine.isOutboundDone());
}
/*
* 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);
@Override
protected SSLEngine configureServerEngine(SSLEngine engine) {
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
// Get/set parameters if needed
SSLParameters paramsServer = serverEngine.getSSLParameters();
SSLParameters paramsServer = engine.getSSLParameters();
paramsServer.setApplicationProtocols(new String[]{"one"});
serverEngine.setSSLParameters(paramsServer);
engine.setSSLParameters(paramsServer);
return engine;
}
/*
* Similar to above, but using client mode instead.
*/
clientEngine = sslc.createSSLEngine("client", 80);
clientEngine.setUseClientMode(true);
@Override
protected SSLEngine configureClientEngine(SSLEngine engine) {
engine.setUseClientMode(true);
// Get/set parameters if needed
SSLParameters paramsClient = clientEngine.getSSLParameters();
SSLParameters paramsClient = engine.getSSLParameters();
paramsClient.setApplicationProtocols(new String[]{"two"});
clientEngine.setSSLParameters(paramsClient);
}
/*
* 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(SSLEngine engine) throws Exception {
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
log(" running delegated task...");
runnable.run();
}
HandshakeStatus hsStatus = engine.getHandshakeStatus();
if (hsStatus == HandshakeStatus.NEED_TASK) {
throw new Exception(
"handshake shouldn't need additional tasks");
}
logEngineStatus(engine);
}
engine.setSSLParameters(paramsClient);
return engine;
}
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
*/

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2023, 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
@ -25,7 +25,8 @@
* @test
* @bug 8164879
* @library ../../
* @library /test/lib
* /test/lib
* /javax/net/ssl/templates
* @summary Verify AES/GCM's limits set in the jdk.tls.keyLimits property
* start a new handshake sequence to renegotiate the symmetric key with an
* SSLSocket connection. This test verifies the handshake method was called
@ -42,23 +43,19 @@
* success.
*/
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.TrustManagerFactory;
import java.io.File;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.Utils;
public class SSLEngineKeyLimit {
public class SSLEngineKeyLimit extends SSLContextTemplate {
SSLEngine eng;
static ByteBuffer cTos;
@ -66,11 +63,6 @@ public class SSLEngineKeyLimit {
static ByteBuffer outdata;
ByteBuffer buf;
static boolean ready = false;
static String pathToStores = "../../../../javax/net/ssl/etc/";
static String keyStoreFile = "keystore";
static String passwd = "passphrase";
static String keyFilename;
static int dataLen = 10240;
static boolean serverwrite = true;
int totalDataLen = 0;
@ -154,13 +146,6 @@ public class SSLEngineKeyLimit {
}
cTos = ByteBuffer.allocateDirect(dataLen*4);
keyFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + keyStoreFile;
System.setProperty("javax.net.ssl.keyStore", keyFilename);
System.setProperty("javax.net.ssl.keyStorePassword", passwd);
sToc = ByteBuffer.allocateDirect(dataLen*4);
outdata = ByteBuffer.allocateDirect(dataLen);
@ -401,19 +386,12 @@ public class SSLEngineKeyLimit {
SSLContext initContext() throws Exception {
SSLContext sc = SSLContext.getInstance("TLSv1.3");
KeyStore ks = KeyStore.getInstance(
new File(System.getProperty("javax.net.ssl.keyStore")),
passwd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, passwd.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
sc.init(kmf.getKeyManagers(),
tmf.getTrustManagers(), new SecureRandom());
return sc;
return createServerSSLContext();
}
@Override
protected ContextParameters getServerContextParameters() {
return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509");
}
static class Server extends SSLEngineKeyLimit implements Runnable {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2023, 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
@ -25,52 +25,36 @@
* @test
* @summary Test SSLEngine.begineHandshake() triggers a KeyUpdate handshake
* in TLSv1.3
* @library /javax/net/ssl/templates
* @run main/othervm TLS13BeginHandshake
*/
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import java.io.File;
import java.nio.ByteBuffer;
import java.security.KeyStore;
import java.security.SecureRandom;
public class TLS13BeginHandshake {
static String pathToStores =
System.getProperty("test.src") + "/../../../../javax/net/ssl/etc/";
static String keyStoreFile = "keystore";
static String passwd = "passphrase";
private SSLEngine serverEngine, clientEngine;
public class TLS13BeginHandshake extends SSLEngineTemplate {
SSLEngineResult clientResult, serverResult;
private ByteBuffer clientOut, clientIn;
private ByteBuffer serverOut, serverIn;
private ByteBuffer cTOs,sTOc;
public static void main(String args[]) throws Exception{
new TLS13BeginHandshake().runDemo();
}
public TLS13BeginHandshake() throws Exception {
super();
}
private void runDemo() throws Exception {
int done = 0;
createSSLEngines();
createBuffers();
while (!isEngineClosed(clientEngine) || !isEngineClosed(serverEngine)) {
System.out.println("================");
clientResult = clientEngine.wrap(clientOut, cTOs);
System.out.println("client wrap: " + clientResult);
runDelegatedTasks(clientResult, clientEngine);
runDelegatedTasks(clientEngine);
serverResult = serverEngine.wrap(serverOut, sTOc);
System.out.println("server wrap: " + serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
cTOs.flip();
sTOc.flip();
@ -80,10 +64,11 @@ public class TLS13BeginHandshake {
System.out.println("client unwrap: " + clientResult);
if (clientResult.getStatus() == SSLEngineResult.Status.CLOSED) {
break;
} runDelegatedTasks(clientResult, clientEngine);
}
runDelegatedTasks(clientEngine);
serverResult = serverEngine.unwrap(cTOs, serverIn);
System.out.println("server unwrap: " + serverResult);
runDelegatedTasks(serverResult, serverEngine);
runDelegatedTasks(serverEngine);
cTOs.compact();
sTOc.compact();
@ -121,71 +106,13 @@ public class TLS13BeginHandshake {
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 {
System.out.println("\tData transferred cleanly");
}
a.compact();
b.compact();
}
private void createBuffers() {
SSLSession session = clientEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
clientIn = ByteBuffer.allocate(appBufferMax + 50);
serverIn = ByteBuffer.allocate(appBufferMax + 50);
cTOs = ByteBuffer.allocateDirect(netBufferMax);
sTOc = ByteBuffer.allocateDirect(netBufferMax);
clientOut = ByteBuffer.wrap("client".getBytes());
serverOut = ByteBuffer.wrap("server".getBytes());
@Override
protected ContextParameters getServerContextParameters() {
return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509");
}
private void createSSLEngines() throws Exception {
serverEngine = initContext().createSSLEngine();
serverEngine.setUseClientMode(false);
serverEngine.setNeedClientAuth(true);
clientEngine = initContext().createSSLEngine("client", 80);
clientEngine.setUseClientMode(true);
}
private SSLContext initContext() throws Exception {
SSLContext sc = SSLContext.getInstance("TLSv1.3");
KeyStore ks = KeyStore.getInstance(new File(pathToStores + keyStoreFile),
passwd.toCharArray());
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, passwd.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return sc;
}
private static void runDelegatedTasks(SSLEngineResult result,
SSLEngine engine) throws Exception {
if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
runnable.run();
}
HandshakeStatus hsStatus = engine.getHandshakeStatus();
if (hsStatus == HandshakeStatus.NEED_TASK) {
throw new Exception(
"handshake shouldn't need additional tasks");
}
}
@Override
protected ContextParameters getClientContextParameters() {
return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509");
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2023, 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
@ -25,6 +25,7 @@
* @test
* @bug 4910892
* @summary 4518403 was not properly fixed. hashcode should be hashCode.
* @library /javax/net/ssl/templates
* @run main/othervm HashCodeMissing
*
* SunJSSE does not support dynamic system properties, no way to re-use
@ -33,72 +34,19 @@
*/
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.lang.reflect.*;
public class HashCodeMissing {
/*
* =============================================================
* 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;
public class HashCodeMissing extends SSLSocketTemplate {
/*
* 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();
@Override
protected void runServerApplication(SSLSocket sslSocket) throws Exception {
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
@ -106,28 +54,10 @@ public class HashCodeMissing {
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);
@Override
protected void runClientApplication(SSLSocket sslSocket) throws Exception {
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
@ -150,29 +80,7 @@ public class HashCodeMissing {
System.out.println("Method = " + method);
}
/*
* =============================================================
* 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");
@ -180,129 +88,7 @@ public class HashCodeMissing {
/*
* Start the tests.
*/
new HashCodeMissing();
new HashCodeMissing().run();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
HashCodeMissing() 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;
}
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2023, 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
@ -26,6 +26,7 @@
* @bug 8206929 8212885
* @summary ensure that client only resumes a session if certain properties
* of the session are compatible with the new connection
* @library /javax/net/ssl/templates
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC
@ -47,13 +48,7 @@ import java.security.*;
import java.net.*;
import java.util.*;
public class ResumeChecksClient {
static String pathToStores = "../../../../javax/net/ssl/etc";
static String keyStoreFile = "keystore";
static String trustStoreFile = "truststore";
static String passwd = "passphrase";
public class ResumeChecksClient extends SSLContextTemplate {
enum TestMode {
BASIC,
VERSION_2_TO_3,
@ -63,38 +58,32 @@ public class ResumeChecksClient {
}
public static void main(String[] args) throws Exception {
new ResumeChecksClient(TestMode.valueOf(args[0])).run();
}
TestMode mode = TestMode.valueOf(args[0]);
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);
private final TestMode testMode;
public ResumeChecksClient(TestMode mode) {
this.testMode = mode;
}
private void run() throws Exception {
Server server = startServer();
server.signal();
SSLContext sslContext = SSLContext.getDefault();
SSLContext sslContext = createClientSSLContext();
while (!server.started) {
Thread.yield();
}
SSLSession firstSession = connect(sslContext, server.port, mode, false);
SSLSession firstSession = connect(sslContext, server.port, testMode, false);
server.signal();
long secondStartTime = System.currentTimeMillis();
Thread.sleep(10);
SSLSession secondSession = connect(sslContext, server.port, mode, true);
SSLSession secondSession = connect(sslContext, server.port, testMode, true);
server.go = false;
server.signal();
switch (mode) {
switch (testMode) {
case BASIC:
// fail if session is not resumed
checkResumedSession(firstSession, secondSession);
@ -109,7 +98,7 @@ public class ResumeChecksClient {
}
break;
default:
throw new RuntimeException("unknown mode: " + mode);
throw new RuntimeException("unknown mode: " + testMode);
}
}
@ -291,7 +280,7 @@ public class ResumeChecksClient {
return server;
}
private static class Server implements Runnable {
private static class Server extends SSLContextTemplate implements Runnable {
public volatile boolean go = true;
private boolean signal = false;
@ -317,7 +306,7 @@ public class ResumeChecksClient {
public void run() {
try {
SSLContext sc = SSLContext.getDefault();
SSLContext sc = createServerSSLContext();
ServerSocketFactory fac = sc.getServerSocketFactory();
SSLServerSocket ssock = (SSLServerSocket)
fac.createServerSocket(0);

@ -26,6 +26,7 @@
* @bug 8211018
* @summary ensure that client only resumes a session if certain properties
* of the session are compatible with the new connection
* @library /javax/net/ssl/templates
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2023, 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
@ -26,6 +26,7 @@
* @bug 8206929
* @summary ensure that server only resumes a session if certain properties
* of the session are compatible with the new connection
* @library /javax/net/ssl/templates
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer BASIC
@ -48,12 +49,7 @@ import java.security.*;
import java.net.*;
import java.util.*;
public class ResumeChecksServer {
static String pathToStores = "../../../../javax/net/ssl/etc";
static String keyStoreFile = "keystore";
static String trustStoreFile = "truststore";
static String passwd = "passphrase";
public class ResumeChecksServer extends SSLContextTemplate {
enum TestMode {
BASIC,
@ -66,23 +62,18 @@ public class ResumeChecksServer {
public static void main(String[] args) throws Exception {
TestMode mode = TestMode.valueOf(args[0]);
new ResumeChecksServer(TestMode.valueOf(args[0])).run();
}
private final TestMode testMode;
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);
public ResumeChecksServer(TestMode testMode) {
this.testMode = testMode;
}
private void run() throws Exception {
SSLSession secondSession = null;
SSLContext sslContext = SSLContext.getDefault();
SSLContext sslContext = createServerSSLContext();
ServerSocketFactory fac = sslContext.getServerSocketFactory();
SSLServerSocket ssock = (SSLServerSocket)
fac.createServerSocket(0);
@ -90,7 +81,7 @@ public class ResumeChecksServer {
Client client = startClient(ssock.getLocalPort());
try {
connect(client, ssock, mode, false);
connect(client, ssock, testMode, false);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
@ -98,7 +89,7 @@ public class ResumeChecksServer {
long secondStartTime = System.currentTimeMillis();
Thread.sleep(10);
try {
secondSession = connect(client, ssock, mode, true);
secondSession = connect(client, ssock, testMode, true);
} catch (SSLHandshakeException ex) {
// this is expected
} catch (Exception ex) {
@ -108,7 +99,7 @@ public class ResumeChecksServer {
client.go = false;
client.signal();
switch (mode) {
switch (testMode) {
case BASIC:
// fail if session is not resumed
if (secondSession.getCreationTime() > secondStartTime) {
@ -129,7 +120,7 @@ public class ResumeChecksServer {
}
break;
default:
throw new RuntimeException("unknown mode: " + mode);
throw new RuntimeException("unknown mode: " + testMode);
}
}
@ -244,7 +235,7 @@ public class ResumeChecksServer {
return client;
}
private static class Client implements Runnable {
private static class Client extends SSLContextTemplate implements Runnable {
public volatile boolean go = true;
private boolean signal = false;
@ -278,7 +269,7 @@ public class ResumeChecksServer {
public void run() {
try {
SSLContext sc = SSLContext.getDefault();
SSLContext sc = createClientSSLContext();
waitForSignal();
while (go) {

@ -26,6 +26,7 @@
* @bug 8211018
* @summary ensure that server only resumes a session if certain properties
* of the session are compatible with the new connection
* @library /javax/net/ssl/templates
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer BASIC
* @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CLIENT_AUTH
* @run main/othervm ResumeChecksServer VERSION_2_TO_3

@ -23,7 +23,7 @@
/*
* @test
* @library /test/lib
* @library /test/lib /javax/net/ssl/templates
* @summary Test that a New Session Ticket will be generated when a
* SSLSessionBindingListener is set (boundValues)
* @key intermittent
@ -48,7 +48,7 @@ import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.Utils;
public class ResumptionUpdateBoundValues {
public class ResumptionUpdateBoundValues extends SSLContextTemplate {
static boolean separateServerThread = true;
@ -77,8 +77,7 @@ public class ResumptionUpdateBoundValues {
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
SSLServerSocketFactory sslssf =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocketFactory sslssf = createServerSSLContext().getServerSocketFactory();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort);
serverPort = sslServerSocket.getLocalPort();
@ -123,8 +122,7 @@ public class ResumptionUpdateBoundValues {
Thread.sleep(50);
}
SSLSocketFactory sslsf =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocketFactory sslsf = createClientSSLContext().getSocketFactory();
try {
SSLSocket sslSocket = (SSLSocket)
@ -210,17 +208,6 @@ public class ResumptionUpdateBoundValues {
return;
}
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");
@ -228,19 +215,14 @@ public class ResumptionUpdateBoundValues {
* Start the tests.
*/
new ResumptionUpdateBoundValues();
new ResumptionUpdateBoundValues().run();
}
ArrayBlockingQueue<Thread> threads = new ArrayBlockingQueue<Thread>(100);
ArrayBlockingQueue<SBListener> sbListeners = new ArrayBlockingQueue<>(100);
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
ResumptionUpdateBoundValues() throws Exception {
private void run() throws Exception {
final int count = 1;
if (separateServerThread) {
startServer(true);