test/jdk/javax/net/ssl/TLSCommon/ConcurrentClientAccessTest.java
changeset 51353 f3e15dcdc333
equal deleted inserted replaced
51352:f646ca47e561 51353:f3e15dcdc333
       
     1 /*
       
     2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 import java.io.ByteArrayInputStream;
       
    26 import java.io.IOException;
       
    27 import java.io.InputStream;
       
    28 import java.io.OutputStream;
       
    29 import java.net.SocketException;
       
    30 import java.net.SocketTimeoutException;
       
    31 import java.security.KeyFactory;
       
    32 import java.security.KeyStore;
       
    33 import java.security.PrivateKey;
       
    34 import java.security.Security;
       
    35 import java.security.cert.Certificate;
       
    36 import java.security.cert.CertificateFactory;
       
    37 import java.security.spec.PKCS8EncodedKeySpec;
       
    38 import java.util.Base64;
       
    39 import java.util.concurrent.CountDownLatch;
       
    40 import java.util.concurrent.ExecutorService;
       
    41 import java.util.concurrent.Executors;
       
    42 import javax.net.ssl.KeyManagerFactory;
       
    43 import javax.net.ssl.SSLContext;
       
    44 import javax.net.ssl.SSLServerSocket;
       
    45 import javax.net.ssl.SSLServerSocketFactory;
       
    46 import javax.net.ssl.SSLSocket;
       
    47 import javax.net.ssl.SSLSocketFactory;
       
    48 import javax.net.ssl.TrustManagerFactory;
       
    49 
       
    50 /*
       
    51  * @test
       
    52  * @bug 8208496
       
    53  * @summary Test to verify concurrent behavior of TLS.
       
    54  * @run main/othervm ConcurrentClientAccessTest
       
    55  */
       
    56 public class ConcurrentClientAccessTest {
       
    57 
       
    58     private static final int THREADS = 50;
       
    59 
       
    60     public static void main(String[] args) throws Exception {
       
    61 
       
    62         Security.setProperty("jdk.tls.disabledAlgorithms", "");
       
    63         for (String tlsProtocol : new String[]{"TLSv1.3", "TLSv1.2",
       
    64             "TLSv1.1", "TLSv1"}) {
       
    65             System.out.printf("Protocol: %s%n", tlsProtocol);
       
    66             CountDownLatch tillServerReady = new CountDownLatch(1);
       
    67             Server server = new Server(tlsProtocol, tillServerReady);
       
    68             server.start();
       
    69 
       
    70             // Wait till server is ready to accept connection.
       
    71             tillServerReady.await();
       
    72             CountDownLatch tillClientComplete = new CountDownLatch(THREADS);
       
    73             ExecutorService executor = null;
       
    74             try {
       
    75                 executor = newExecutorService();
       
    76                 // Run 50 TLS clients for concurrent access to TLS Port.
       
    77                 for (int count = 1; count <= THREADS; count++) {
       
    78                     Client client = new Client(tlsProtocol, server.port,
       
    79                             tillClientComplete);
       
    80                     executor.execute(client);
       
    81                     // If Client has any Exception indicates problem
       
    82                     if (client.exception != null) {
       
    83                         throw new RuntimeException(client.exception);
       
    84                     }
       
    85                 }
       
    86                 // Wait till all client thread complete execution
       
    87                 tillClientComplete.await();
       
    88                 System.out.println("All client processed successfully.");
       
    89             } finally {
       
    90                 if (executor != null) {
       
    91                     executor.shutdown();
       
    92                 }
       
    93                 // Fail Safe: Shutdown the server
       
    94                 server.stopServer();
       
    95             }
       
    96             // If Sever has any Exception indicates problem
       
    97             if (server.exception != null) {
       
    98                 throw new RuntimeException(server.exception);
       
    99             }
       
   100             System.out.println();
       
   101         }
       
   102     }
       
   103 
       
   104     public static class Server implements Runnable {
       
   105 
       
   106         private volatile int port = 0;
       
   107         private final String tlsProtocol;
       
   108         private final CountDownLatch tillServerReady;
       
   109         private volatile Exception exception;
       
   110         private SSLServerSocket sslServerSocket;
       
   111 
       
   112         public Server(String tlsProtocol, CountDownLatch tillServerReady) {
       
   113             this.tlsProtocol = tlsProtocol;
       
   114             this.tillServerReady = tillServerReady;
       
   115         }
       
   116 
       
   117         public void start() {
       
   118 
       
   119             ExecutorService executor = null;
       
   120             try {
       
   121                 executor = newExecutorService();
       
   122                 executor.execute(this);
       
   123             } finally {
       
   124                 if (executor != null) {
       
   125                     executor.shutdown();
       
   126                 }
       
   127             }
       
   128         }
       
   129 
       
   130         /*
       
   131          * Define the server side operation.
       
   132          */
       
   133         void doServerSide() throws Exception {
       
   134 
       
   135             SSLContext ctx = getSSLContext(tlsProtocol);
       
   136             SSLServerSocketFactory sslssf = ctx.getServerSocketFactory();
       
   137             sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(port);
       
   138             port = sslServerSocket.getLocalPort();
       
   139             System.out.println("Server listening on port: " + port);
       
   140             sslServerSocket.setEnabledProtocols(new String[]{tlsProtocol});
       
   141             // ServerSocket will timeout after waiting for 20 seconds
       
   142             // before accepting a connection
       
   143             sslServerSocket.setSoTimeout(20000);
       
   144             // Signal Client, the server is ready to accept client request.
       
   145             tillServerReady.countDown();
       
   146             while (sslServerSocket != null && !sslServerSocket.isClosed()) {
       
   147                 try (SSLSocket sslSocket
       
   148                         = (SSLSocket) sslServerSocket.accept()) {
       
   149                     try (InputStream sslIS = sslSocket.getInputStream();
       
   150                             OutputStream sslOS
       
   151                             = sslSocket.getOutputStream();) {
       
   152                         sslIS.read();
       
   153                         sslOS.write(85);
       
   154                         sslOS.flush();
       
   155                     }
       
   156                 } catch (SocketTimeoutException | SocketException e) {
       
   157                     // Let the server exit
       
   158                     return;
       
   159                 }
       
   160             }
       
   161         }
       
   162 
       
   163         @Override
       
   164         public void run() {
       
   165             try {
       
   166                 doServerSide();
       
   167             } catch (Exception e) {
       
   168                 this.exception = e;
       
   169             } finally {
       
   170                 // Stop server
       
   171                 stopServer();
       
   172             }
       
   173         }
       
   174 
       
   175         public void stopServer() {
       
   176             if (sslServerSocket != null && !sslServerSocket.isClosed()) {
       
   177                 System.out.println("Stopping Server.");
       
   178                 try {
       
   179                     sslServerSocket.close();
       
   180                 } catch (IOException e) {
       
   181                     throw new RuntimeException(e);
       
   182                 }
       
   183             }
       
   184         }
       
   185     }
       
   186 
       
   187     /*
       
   188      * Define the client side of the test.
       
   189      */
       
   190     public static class Client implements Runnable {
       
   191 
       
   192         private final int serverPort;
       
   193         private final String tlsProtocol;
       
   194         private final CountDownLatch tillClientComplete;
       
   195         private volatile Exception exception;
       
   196 
       
   197         public Client(String tlsProtocol, int serverPort,
       
   198                 CountDownLatch tillClientComplete) {
       
   199             this.tlsProtocol = tlsProtocol;
       
   200             this.serverPort = serverPort;
       
   201             this.tillClientComplete = tillClientComplete;
       
   202         }
       
   203 
       
   204         void doClientSide() throws Exception {
       
   205 
       
   206             SSLContext ctx = getSSLContext(this.tlsProtocol);
       
   207             SSLSocketFactory sslsf = ctx.getSocketFactory();
       
   208             try (SSLSocket sslSocket
       
   209                     = (SSLSocket) sslsf.createSocket("localhost", serverPort)) {
       
   210                 sslSocket.setEnabledProtocols(new String[]{this.tlsProtocol});
       
   211                 try (InputStream sslIS = sslSocket.getInputStream();
       
   212                         OutputStream sslOS = sslSocket.getOutputStream()) {
       
   213                     sslOS.write(86);
       
   214                     sslOS.flush();
       
   215                     sslIS.read();
       
   216                 }
       
   217             } finally {
       
   218                 tillClientComplete.countDown();
       
   219             }
       
   220         }
       
   221 
       
   222         @Override
       
   223         public void run() {
       
   224             try {
       
   225                 doClientSide();
       
   226             } catch (Exception e) {
       
   227                 // Print the exception for debug purpose.
       
   228                 e.printStackTrace(System.out);
       
   229                 this.exception = e;
       
   230             }
       
   231         }
       
   232     }
       
   233 
       
   234     // Get the ssl context
       
   235     protected static SSLContext getSSLContext(String tlsProtocol)
       
   236             throws Exception {
       
   237 
       
   238         // Generate certificate from cert string
       
   239         CertificateFactory cf = CertificateFactory.getInstance("X.509");
       
   240 
       
   241         // Create a key store
       
   242         KeyStore ts = KeyStore.getInstance("PKCS12");
       
   243         KeyStore ks = KeyStore.getInstance("PKCS12");
       
   244         ts.load(null, null);
       
   245         ks.load(null, null);
       
   246         char passphrase[] = "passphrase".toCharArray();
       
   247 
       
   248         // Import the trusted cert
       
   249         ts.setCertificateEntry("trusted-cert-"
       
   250                 + KeyType.rsa_pkcs1_sha256.getKeyType(),
       
   251                 cf.generateCertificate(new ByteArrayInputStream(
       
   252                         KeyType.rsa_pkcs1_sha256.getTrustedCert().getBytes())));
       
   253 
       
   254         boolean hasKeyMaterials = KeyType.rsa_pkcs1_sha256.getEndCert() != null
       
   255                 && KeyType.rsa_pkcs1_sha256.getPrivateKey() != null;
       
   256         if (hasKeyMaterials) {
       
   257 
       
   258             // Generate the private key.
       
   259             PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
       
   260                     Base64.getMimeDecoder().decode(
       
   261                             KeyType.rsa_pkcs1_sha256.getPrivateKey()));
       
   262             KeyFactory kf = KeyFactory.getInstance(
       
   263                     KeyType.rsa_pkcs1_sha256.getKeyType());
       
   264             PrivateKey priKey = kf.generatePrivate(priKeySpec);
       
   265 
       
   266             // Generate certificate chain
       
   267             Certificate keyCert = cf.generateCertificate(
       
   268                     new ByteArrayInputStream(
       
   269                             KeyType.rsa_pkcs1_sha256.getEndCert().getBytes()));
       
   270             Certificate[] chain = new Certificate[]{keyCert};
       
   271 
       
   272             // Import the key entry.
       
   273             ks.setKeyEntry("cert-" + KeyType.rsa_pkcs1_sha256.getKeyType(),
       
   274                     priKey, passphrase, chain);
       
   275         }
       
   276 
       
   277         // Create SSL context
       
   278         TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
       
   279         tmf.init(ts);
       
   280 
       
   281         SSLContext context = SSLContext.getInstance(tlsProtocol);
       
   282         if (hasKeyMaterials) {
       
   283             KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
       
   284             kmf.init(ks, passphrase);
       
   285             context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
       
   286         } else {
       
   287             context.init(null, tmf.getTrustManagers(), null);
       
   288         }
       
   289         return context;
       
   290     }
       
   291 
       
   292     private static ExecutorService newExecutorService() {
       
   293         return Executors.newCachedThreadPool((Runnable r) -> {
       
   294             Thread t = Executors.defaultThreadFactory()
       
   295                     .newThread(r);
       
   296             t.setDaemon(true);
       
   297             return t;
       
   298         });
       
   299     }
       
   300 }
       
   301 
       
   302 enum KeyType {
       
   303 
       
   304     rsa_pkcs1_sha256(
       
   305             "RSA",
       
   306             /**
       
   307              * Signature Algorithm: sha256WithRSAEncryption
       
   308              * Issuer: CN = localhost
       
   309              * Validity Not Before: Jun 4 15:22:04 2018 GMT
       
   310              * Not After: May 30 15:22:04 2038 GMT
       
   311              * Subject: CN = localhost
       
   312              * Public Key Algorithm: rsaEncryption
       
   313              */
       
   314             "-----BEGIN CERTIFICATE-----\n"
       
   315             + "MIIDBjCCAe6gAwIBAgIUc8yTYekR2LuXkkCJYqWlS/pBMKIwDQYJKoZIhvcNAQEL\n"
       
   316             + "BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTE4MDYwNDE1MjIwNFoXDTM4MDUz\n"
       
   317             + "MDE1MjIwNFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF\n"
       
   318             + "AAOCAQ8AMIIBCgKCAQEA2jDPGMogc9dq2w5b+FHqbfaGPokRmyObiU8y/l/dqkM5\n"
       
   319             + "9IV+qj8VQUI4NtpdCTWr16812z4AjXrk5HIBrECfQbHPUcm1rme5YVZ0WxV0+Ufy\n"
       
   320             + "hDmrGwDLhkxGqc3hOhRrlF2wdXeUfjIzhvS9+S/401++t/jvq+cqFF1BHnzYOu+l\n"
       
   321             + "nbi/o95Oqo8MlwiRqg3xy3fNRfqXk7DWy+QT8s+Vc3Pcj1EW6K0iJJ23BVTdv6YT\n"
       
   322             + "Ja5IKiWL4XsLht3fWvZwF+PoYfKb+JYflt0rafpxg9xkowe7GnGh2SpV7bJaH/QN\n"
       
   323             + "3PTFEKQWgWHjWwjR171GOzSaEgaklvKde6+zNWeYKwIDAQABo1AwTjAdBgNVHQ4E\n"
       
   324             + "FgQUqCtGe8/Ky4O6pH7xeTUy9yrv4n0wHwYDVR0jBBgwFoAUqCtGe8/Ky4O6pH7x\n"
       
   325             + "eTUy9yrv4n0wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAuqch30im\n"
       
   326             + "M09sARarbfK3OExqYK2xoyuUscgTqQNDpNL2gMdXY9e0lTmGVgw9pVYtNZPZRxem\n"
       
   327             + "jR5an2XegvG9qVU6vLENDwLCqZgsTb2gvmXngiG8NVcYd81GNqD228mkgBosNJku\n"
       
   328             + "6BR+C8zlURzsNEt657eVvIp9ObGomdAbWhpdqihBD180PP18DIBWopyfHfJtT5FA\n"
       
   329             + "U2kSPBp+P1EtdceW0zfwv3rF8hwRbnQBzuoYrZfn2PiMYaGUqOgbqUltCMD/Dp9G\n"
       
   330             + "xK0nfAXEwIqHWWnijGwAd6YrszMjBUcSGmlehdF+XZK6jHNlw64RB4WTfavr+rY0\n"
       
   331             + "dTe6g4o5GYr9nQ==\n"
       
   332             + "-----END CERTIFICATE-----\n",
       
   333             //
       
   334             // Private key.
       
   335             //
       
   336             "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDaMM8YyiBz12rb\n"
       
   337             + "Dlv4Uept9oY+iRGbI5uJTzL+X92qQzn0hX6qPxVBQjg22l0JNavXrzXbPgCNeuTk\n"
       
   338             + "cgGsQJ9Bsc9RybWuZ7lhVnRbFXT5R/KEOasbAMuGTEapzeE6FGuUXbB1d5R+MjOG\n"
       
   339             + "9L35L/jTX763+O+r5yoUXUEefNg676WduL+j3k6qjwyXCJGqDfHLd81F+peTsNbL\n"
       
   340             + "5BPyz5Vzc9yPURborSIknbcFVN2/phMlrkgqJYvhewuG3d9a9nAX4+hh8pv4lh+W\n"
       
   341             + "3Stp+nGD3GSjB7sacaHZKlXtslof9A3c9MUQpBaBYeNbCNHXvUY7NJoSBqSW8p17\n"
       
   342             + "r7M1Z5grAgMBAAECggEAHs/7vw10TcejEHJTrJqs14CT7qresKDzqw1jLycMn6nE\n"
       
   343             + "unJLs/EaqE+Yrq5hqxZIQTo+CcsUuuYbAuPStqedleJtW6h3nryJImTaI67BCR8O\n"
       
   344             + "8XtPXY3cMAf/hqVLZC9UDey5Ka2Ma9HdEvbnCRSsN/VycnqWJhmMCLouowaQZqoE\n"
       
   345             + "VopscUix8GqELv0vEo2CszZfUjtSVbNTlNgwDf5U7eSKXMuFsnSn/LE7AMvHsEyo\n"
       
   346             + "HatxogwlM/WjpTnf/WIeJY3VhaK10IsP6OEgUn/p4VtI2DQ/TJdgYrvD5vhjY8ip\n"
       
   347             + "XuUPuPILRvJWo8dRXJqa4diXB12q5YhP8iiOp4BgkQKBgQD1GtlOR+JVgOzpQ11h\n"
       
   348             + "s5/iJOsczee80pQscbSRJnzSsIaP9WM8CyJgvbPxIQxLUQeYnxM/bxNKkpJtzxRK\n"
       
   349             + "pob+v4NoRn8PTpqbOp1obmWJT7uHTaoeavQo7r7uZI4i3eEgHCCQkMzpqzz7UFTY\n"
       
   350             + "2Yst7bBTPUivlSVQQBEc8bLpeQKBgQDj47EjpAlh8DmJRTElg58t+XJehXGTqmlx\n"
       
   351             + "nYu8DQLSzGbOQ/Z4srakC1mkM0LHCmULIIWk3KhV1GBCeArv7DlZ9A1SkI95bsq9\n"
       
   352             + "GBeQpovL0PXKkOOWMJBklP/CTECO4eyA8r6c1d8wytBb6MrJ8bi74DdT+JlFjK5A\n"
       
   353             + "zNoeNx6JwwKBgQCehIPABeuSYvRVlDTDqFkh98B6+4wBaatc5xjhuyOFW5dbaVeJ\n"
       
   354             + "kKXmLSpAK6B44WnpQhA/uUWfuBWtoPy9nt+1yARjnxwzuSFyfUEqNiPC32coBYmd\n"
       
   355             + "bIyGIIopQa1PTXJ4wtgoxw1PnmitHHITYPaLeKrN2te0fuAH+7dVodeU+QKBgAct\n"
       
   356             + "VJbaw7Dh7+3yz+lui8TW5lMzwK/13fxGCfCSOFSLO3Gjkk+a0UW5VclmE+RQ333K\n"
       
   357             + "OGtIx8RsO9vcC/wiZGwA06qWAu7AHoJ2D8fudtikbBlFFuXUAbgpOSTVYfMeCmTF\n"
       
   358             + "QFuQIMdYm9dJLZnOkxLXrOZoHeui0poX2Ya6FawhAoGAAI/QCyDbuvnJzGmjSbvl\n"
       
   359             + "5Ndr9lNAansCXaUzXuVLp6dD6PnB8HVCE8tdETZrcXseyTBeltaxAhj+tCybJvDO\n"
       
   360             + "sV8UmPR0w9ibExmUIVGX5BpoRlB/KWxEG3ar/wJbUZVZ2oSdIAZvCvdbN956SLDg\n"
       
   361             + "Pg5M5wrRqs71s2EiIJd0HrU="
       
   362     );
       
   363     private final String keyType;
       
   364     private final String trustedCert;
       
   365     private final String endCert;
       
   366     private final String privateKey;
       
   367 
       
   368     private KeyType(String keyType, String selfCert, String privateKey) {
       
   369         this.keyType = keyType;
       
   370         this.trustedCert = selfCert;
       
   371         this.endCert = selfCert;
       
   372         this.privateKey = privateKey;
       
   373     }
       
   374 
       
   375     public String getKeyType() {
       
   376         return keyType;
       
   377     }
       
   378 
       
   379     public String getTrustedCert() {
       
   380         return trustedCert;
       
   381     }
       
   382 
       
   383     public String getEndCert() {
       
   384         return endCert;
       
   385     }
       
   386 
       
   387     public String getPrivateKey() {
       
   388         return privateKey;
       
   389     }
       
   390 }