1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 //
  25 // SunJSSE does not support dynamic system properties, no way to re-use
  26 // system properties in samevm/agentvm mode.
  27 //
  28 
  29 /*
  30  * @test
  31  * @bug 8144566
  32  * @summary Custom HostnameVerifier disables SNI extension
  33  * @run main/othervm ImpactOnSNI
  34  */
  35 
  36 import java.io.*;
  37 import java.net.*;
  38 import javax.net.ssl.*;
  39 
  40 public class ImpactOnSNI {
  41 
  42     /*
  43      * =============================================================
  44      * Set the various variables needed for the tests, then
  45      * specify what tests to run on each side.
  46      */
  47 
  48     /*
  49      * Should we run the client or server in a separate thread?
  50      * Both sides can throw exceptions, but do you have a preference
  51      * as to which side should be the main thread.
  52      */
  53     static boolean separateServerThread = true;
  54 
  55     /*
  56      * Where do we find the keystores?
  57      */
  58     static String pathToStores = "../../../../../../javax/net/ssl/etc";
  59     static String keyStoreFile = "keystore";
  60     static String trustStoreFile = "truststore";
  61     static String passwd = "passphrase";
  62 
  63     /*
  64      * Is the server ready to serve?
  65      */
  66     volatile static boolean serverReady = false;
  67 
  68     /*
  69      * Is the connection ready to close?
  70      */
  71     volatile static boolean closeReady = false;
  72 
  73     /*
  74      * Turn on SSL debugging?
  75      */
  76     static boolean debug = false;
  77 
  78     /*
  79      * Message posted
  80      */
  81     static String postMsg = "HTTP post on a https server";
  82 
  83     /*
  84      * the fully qualified domain name of localhost
  85      */
  86     static String hostname = null;
  87 
  88     /*
  89      * If the client or server is doing some kind of object creation
  90      * that the other side depends on, and that thread prematurely
  91      * exits, you may experience a hang.  The test harness will
  92      * terminate all hung threads after its timeout has expired,
  93      * currently 3 minutes by default, but you might try to be
  94      * smart about it....
  95      */
  96 
  97     /*
  98      * Define the server side of the test.
  99      *
 100      * If the server prematurely exits, serverReady will be set to true
 101      * to avoid infinite hangs.
 102      */
 103     void doServerSide() throws Exception {
 104         SSLServerSocketFactory sslssf =
 105             (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
 106         try (SSLServerSocket sslServerSocket =
 107                 (SSLServerSocket)sslssf.createServerSocket(serverPort)) {
 108 
 109             serverPort = sslServerSocket.getLocalPort();
 110 
 111             /*
 112              * Signal Client, we're ready for his connect.
 113              */
 114             serverReady = true;
 115 
 116             /*
 117              * Accept connections
 118              */
 119             try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) {
 120                 InputStream sslIS = sslSocket.getInputStream();
 121                 OutputStream sslOS = sslSocket.getOutputStream();
 122                 BufferedReader br =
 123                         new BufferedReader(new InputStreamReader(sslIS));
 124                 PrintStream ps = new PrintStream(sslOS);
 125 
 126                 // process HTTP POST request from client
 127                 System.out.println("status line: " + br.readLine());
 128                 String msg = null;
 129                 while ((msg = br.readLine()) != null && msg.length() > 0);
 130 
 131                 msg = br.readLine();
 132                 if (msg.equals(postMsg)) {
 133                     ps.println("HTTP/1.1 200 OK\n\n");
 134                 } else {
 135                     ps.println("HTTP/1.1 500 Not OK\n\n");
 136                 }
 137                 ps.flush();
 138 
 139                 ExtendedSSLSession session =
 140                         (ExtendedSSLSession)sslSocket.getSession();
 141                 if (session.getRequestedServerNames().isEmpty()) {
 142                     throw new Exception("No expected Server Name Indication");
 143                 }
 144 
 145                 // close the socket
 146                 while (!closeReady) {
 147                     Thread.sleep(50);
 148                 }
 149             }
 150         }
 151     }
 152 
 153     /*
 154      * Define the client side of the test.
 155      *
 156      * If the server prematurely exits, serverReady will be set to true
 157      * to avoid infinite hangs.
 158      */
 159     void doClientSide() throws Exception {
 160         /*
 161          * Wait for server to get started.
 162          */
 163         while (!serverReady) {
 164             Thread.sleep(50);
 165         }
 166 
 167         // Send HTTP POST request to server
 168         URL url = new URL("https://" + hostname + ":" + serverPort);
 169 
 170         HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());
 171         HttpsURLConnection http = (HttpsURLConnection)url.openConnection();
 172         http.setDoOutput(true);
 173 
 174         http.setRequestMethod("POST");
 175         PrintStream ps = new PrintStream(http.getOutputStream());
 176         try {
 177             ps.println(postMsg);
 178             ps.flush();
 179             if (http.getResponseCode() != 200) {
 180                 throw new RuntimeException("test Failed");
 181             }
 182         } finally {
 183             ps.close();
 184             http.disconnect();
 185             closeReady = true;
 186         }
 187     }
 188 
 189     static class NameVerifier implements HostnameVerifier {
 190         public boolean verify(String hostname, SSLSession session) {
 191             return true;
 192         }
 193     }
 194 
 195     /*
 196      * =============================================================
 197      * The remainder is just support stuff
 198      */
 199 
 200     // use any free port by default
 201     volatile int serverPort = 0;
 202 
 203     volatile Exception serverException = null;
 204     volatile Exception clientException = null;
 205 
 206     public static void main(String[] args) throws Exception {
 207         String keyFilename =
 208             System.getProperty("test.src", "./") + "/" + pathToStores +
 209                 "/" + keyStoreFile;
 210         String trustFilename =
 211             System.getProperty("test.src", "./") + "/" + pathToStores +
 212                 "/" + trustStoreFile;
 213 
 214         System.setProperty("javax.net.ssl.keyStore", keyFilename);
 215         System.setProperty("javax.net.ssl.keyStorePassword", passwd);
 216         System.setProperty("javax.net.ssl.trustStore", trustFilename);
 217         System.setProperty("javax.net.ssl.trustStorePassword", passwd);
 218 
 219         if (debug) {
 220             System.setProperty("javax.net.debug", "all");
 221         }
 222 
 223         try {
 224             hostname = InetAddress.getLocalHost().getCanonicalHostName();
 225         } catch (UnknownHostException uhe) {
 226             System.out.println(
 227                 "Ignore the test as the local hostname cannot be determined");
 228 
 229             return;
 230         }
 231 
 232         System.out.println(
 233                 "The fully qualified domain name of the local host is " +
 234                 hostname);
 235         // Ignore the test if the hostname does not sound like a domain name.
 236         if ((hostname == null) || hostname.isEmpty() ||
 237                 hostname.startsWith("localhost") ||
 238                 Character.isDigit(hostname.charAt(hostname.length() - 1))) {
 239 
 240             System.out.println("Ignore the test as the local hostname " +
 241                     "cannot be determined as fully qualified domain name");
 242 
 243             return;
 244         }
 245 
 246         /*
 247          * Start the tests.
 248          */
 249         new ImpactOnSNI();
 250     }
 251 
 252     Thread clientThread = null;
 253     Thread serverThread = null;
 254 
 255     /*
 256      * Primary constructor, used to drive remainder of the test.
 257      *
 258      * Fork off the other side, then do your work.
 259      */
 260     ImpactOnSNI() throws Exception {
 261         Exception startException = null;
 262         try {
 263             if (separateServerThread) {
 264                 startServer(true);
 265                 startClient(false);
 266             } else {
 267                 startClient(true);
 268                 startServer(false);
 269             }
 270         } catch (Exception e) {
 271             startException = e;
 272         }
 273 
 274         /*
 275          * Wait for other side to close down.
 276          */
 277         if (separateServerThread) {
 278             if (serverThread != null) {
 279                 serverThread.join();
 280             }
 281         } else {
 282             if (clientThread != null) {
 283                 clientThread.join();
 284             }
 285         }
 286 
 287         /*
 288          * When we get here, the test is pretty much over.
 289          * Which side threw the error?
 290          */
 291         Exception local;
 292         Exception remote;
 293 
 294         if (separateServerThread) {
 295             remote = serverException;
 296             local = clientException;
 297         } else {
 298             remote = clientException;
 299             local = serverException;
 300         }
 301 
 302         Exception exception = null;
 303 
 304         /*
 305          * Check various exception conditions.
 306          */
 307         if ((local != null) && (remote != null)) {
 308             // If both failed, return the curthread's exception.
 309             local.initCause(remote);
 310             exception = local;
 311         } else if (local != null) {
 312             exception = local;
 313         } else if (remote != null) {
 314             exception = remote;
 315         } else if (startException != null) {
 316             exception = startException;
 317         }
 318 
 319         /*
 320          * If there was an exception *AND* a startException,
 321          * output it.
 322          */
 323         if (exception != null) {
 324             if (exception != startException && startException != null) {
 325                 exception.addSuppressed(startException);
 326             }
 327             throw exception;
 328         }
 329 
 330         // Fall-through: no exception to throw!
 331     }
 332 
 333     void startServer(boolean newThread) throws Exception {
 334         if (newThread) {
 335             serverThread = new Thread() {
 336                 @Override
 337                 public void run() {
 338                     try {
 339                         doServerSide();
 340                     } catch (Exception e) {
 341                         /*
 342                          * Our server thread just died.
 343                          *
 344                          * Release the client, if not active already...
 345                          */
 346                         System.err.println("Server died...");
 347                         serverReady = true;
 348                         serverException = e;
 349                     }
 350                 }
 351             };
 352             serverThread.start();
 353         } else {
 354             try {
 355                 doServerSide();
 356             } catch (Exception e) {
 357                 serverException = e;
 358             } finally {
 359                 serverReady = true;
 360             }
 361         }
 362     }
 363 
 364     void startClient(boolean newThread) throws Exception {
 365         if (newThread) {
 366             clientThread = new Thread() {
 367                 @Override
 368                 public void run() {
 369                     try {
 370                         doClientSide();
 371                     } catch (Exception e) {
 372                         /*
 373                          * Our client thread just died.
 374                          */
 375                         System.err.println("Client died...");
 376                         clientException = e;
 377                     }
 378                 }
 379             };
 380             clientThread.start();
 381         } else {
 382             try {
 383                 doClientSide();
 384             } catch (Exception e) {
 385                 clientException = e;
 386             }
 387         }
 388     }
 389 }