public HTTPSConnectSocket(String host, int port, String urlString) throws IOException {

    URL url = null;
    try {
      url = new URL(urlString);
    } catch (MalformedURLException me) {
      System.out.println("Malformed url");
      System.exit(1);
    }

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ssl = (SSLSocket) ssf.createSocket(host, port);
    ssl.startHandshake();

    // Send the CONNECT request
    ssl.getOutputStream().write(("CONNECT " + url.getFile() + " HTTP/1.0\r\n\r\n").getBytes());

    // Read the first line of the response
    DataInputStream is = new DataInputStream(ssl.getInputStream());
    String str = is.readLine();

    // Check the HTTP error code -- it should be "200" on success
    if (!str.startsWith("HTTP/1.1 200 ")) {
      if (str.startsWith("HTTP/1.1 ")) str = str.substring(9);
      throw new IOException("Proxy reports \"" + str + "\"");
    }

    // Success -- skip remaining HTTP headers
    do {
      str = is.readLine();
    } while (str.length() != 0);
  }
Example #2
0
  private CipherTest(PeerFactory peerFactory) throws IOException {
    THREADS = Integer.parseInt(System.getProperty("numThreads", "4"));
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket();
    String[] cipherSuites = socket.getSupportedCipherSuites();
    String[] protocols = socket.getSupportedProtocols();
    //      String[] clientAuths = {null, "RSA", "DSA"};
    String[] clientAuths = {null};
    tests =
        new ArrayList<TestParameters>(cipherSuites.length * protocols.length * clientAuths.length);
    for (int i = 0; i < cipherSuites.length; i++) {
      String cipherSuite = cipherSuites[i];

      for (int j = 0; j < protocols.length; j++) {
        String protocol = protocols[j];

        if (!peerFactory.isSupported(cipherSuite, protocol)) {
          continue;
        }

        for (int k = 0; k < clientAuths.length; k++) {
          String clientAuth = clientAuths[k];
          if ((clientAuth != null) && (cipherSuite.indexOf("DH_anon") != -1)) {
            // no client with anonymous ciphersuites
            continue;
          }
          tests.add(new TestParameters(cipherSuite, protocol, clientAuth));
        }
      }
    }
    testIterator = tests.iterator();
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    sslSocket.close();
  }
Example #4
0
  public static void main(String args[]) throws Exception {
    //        System.setProperty("javax.net.ssl.trustStore",
    //                   "clienttrust");

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.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);
    }

    /*
     * See if an unknown keystore actually gets checked ok.
     */
    System.out.println("==============");
    System.out.println("Starting test0");
    KeyStore uks = KeyStore.getInstance("JKS");
    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    uks.load(new FileInputStream(unknownFilename), cpasswd);
    kmf.init(uks, cpasswd);

    TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory();

    System.out.println("Trying first socket " + serverPort);
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    doTest(sslSocket);

    /*
     * Now try the other way.
     */
    com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf1 =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
    kmf1.init(uks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms1 =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslsf = (SSLSocketFactory) ctx1.getSocketFactory();

    System.out.println("Trying second socket " + serverPort1);
    sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1);

    doTest(sslSocket);
    System.out.println("Completed test1");
  }
  public Socket createSocket(String host, int port, String proxyHost, String proxyPortStr)
      throws IOException {

    int proxyPort = 0;
    if (proxyPortStr != null) {
      try {
        proxyPort = Integer.parseInt(proxyPortStr);
      } catch (NumberFormatException e) {
      }
    }

    if (proxyHost == null || proxyPort == 0) {
      System.out.println("Incomplete parameter list for HTTPSConnectSSLSocket");
      SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
      return (SSLSocket) sf.createSocket(host, port);
    }

    System.out.println("HTTPS CONNECT via proxy " + proxyHost + " port " + proxyPort);
    return HTTPSConnectSSLSocket.connectSSLSocket(host, port, proxyHost, proxyPort);
  }
Example #7
0
  public static TcpSocket makeTls(TcpSocket upgrade) {
    try {
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, null, null);

      // get SSL factory because Java loves factories!
      SSLSocketFactory factory = sslContext.getSocketFactory();

      // create new SSL socket
      SSLSocket socket;
      if (upgrade == null) {
        socket = (SSLSocket) factory.createSocket();
      }

      // upgrade an existing socket
      else {
        socket =
            (SSLSocket)
                factory.createSocket(
                    upgrade.peer.socket,
                    upgrade.peer.socket.getInetAddress().getHostAddress(),
                    upgrade.peer.socket.getPort(),
                    false);
        socket.setUseClientMode(true);
        socket.startHandshake();
      }

      // create the new TcpSocket instance
      TcpSocket self = new TcpSocket();
      self.peer = new TcpSocketPeer(socket);

      // if upgrade, then initialize socket as already connected
      if (upgrade != null) self.peer.connected(self);

      return self;
    } catch (Exception e) {
      throw IOErr.make(e);
    }
  }
  public static void main(String[] args) throws Exception {
    try {
      Class.forName("javax.security.auth.kerberos.KerberosPrincipal");
      System.out.println("Kerberos is present, nothing to test");
      return;
    } catch (ClassNotFoundException okay) {
    }

    // test SSLSocket
    try (Socket s = SSLSocketFactory.getDefault().createSocket()) {
      SSLSocket sslSocket = (SSLSocket) s;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }

    // test SSLServerSocket
    try (ServerSocket ss = SSLServerSocketFactory.getDefault().createServerSocket()) {
      SSLServerSocket sslSocket = (SSLServerSocket) ss;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }
  }
 @Override
 public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
     throws IOException {
   return applySettings(sslSocketFactory.createSocket(host, port, localHost, localPort));
 }
 @Override
 public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
     throws IOException {
   return applySettings(sslSocketFactory.createSocket(address, port, localAddress, localPort));
 }
 @Override
 public Socket createSocket(InetAddress host, int port) throws IOException {
   return applySettings(sslSocketFactory.createSocket(host, port));
 }
 @Override
 public Socket createSocket() throws IOException {
   return applySettings(sslSocketFactory.createSocket());
 }
 public String[] getDefaultCipherSuites() {
   return factory.getDefaultCipherSuites();
 }
 public String[] getSupportedCipherSuites() {
   return factory.getSupportedCipherSuites();
 }
Example #15
0
  public static void main(String[] args) {
    BufferedReader sysIn =
        new BufferedReader(new InputStreamReader(System.in)); // Read from console
    PrintStream sysOut = System.out; // Print to console
    SSLSocketFactory mainFactory =
        (SSLSocketFactory) SSLSocketFactory.getDefault(); // Get default SSL socket factory
    try {
      SSLSocket clientSocket =
          (SSLSocket)
              mainFactory.createSocket(
                  "pop.mail.yahoo.com", 995); // create, connect, start handshake
      printSocketInfo(clientSocket); // Print connection info
      BufferedWriter serverWriter =
          new BufferedWriter(
              new OutputStreamWriter(clientSocket.getOutputStream())); // Write to server
      BufferedReader serverReader =
          new BufferedReader(
              new InputStreamReader(clientSocket.getInputStream())); // Read from server

      String serverInput = null; // Stores latest line from server
      String userInput = ""; // Stores lastest input line from user
      boolean tryRead =
          true; // Whether to read next line from serverReader (prevents blocking on multiline SMTP
                // responses)

      // The below booleans, used to successully close the connection, might be unnecessary
      boolean quitUser = false; // Whether the user has entered quit, might be unnecessary
      boolean openRead = true; // Whether serverReader is still open (serverInput != null)
      boolean openSocket = true; // Whether clientSocket is still open (clientSocket != null)

      // SMTP input variables
      boolean sendingData = false;
      boolean multi = false;

      // Main connection loop
      while (openSocket && openRead && !quitUser) {
        if (clientSocket == null) { // Break if socket is closed
          openSocket = false;
          break;
        }
        // Display server response/message
        if (multi) {
          while (tryRead) {
            serverInput = serverReader.readLine();
            if (serverInput == null) { // If serverReader gets closed/connection broken
              openRead = false;
              tryRead = false;
              break;
            }
            sysOut.println(serverInput);
            // Check for multiline response or error
            if (serverInput.equals(".")
                || (serverInput.length() >= 4 && serverInput.startsWith("-ERR"))) {
              tryRead = false;
            } else {
              tryRead = true;
            }
          }
        } else {
          serverInput = serverReader.readLine();
          if (serverInput == null) { // If serverReader gets closed/connection broken
            openRead = false;
            tryRead = false;
            break;
          }
          sysOut.println(serverInput);
        }
        multi = false;
        // Exit client if connection lost/closed prematurely
        if (openSocket == false || openRead == false) {
          break;
        }
        // If user previously entered quit
        if (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("quit")) {
          quitUser = true;
          break;
        }
        // Get user input
        userInput = ""; // Reset userInput to show prompt
        // Read user input, display prompt if blank enter, otherwise send to server
        while (userInput.equals("")) {
          sysOut.print("C: ");
          userInput = sysIn.readLine();
        }
        serverWriter.write(userInput, 0, userInput.length()); // Writing to server
        serverWriter.newLine();
        serverWriter.flush();
        tryRead = true;
        // Prepare for multi-line response if list, uidl, retr, or top
        if (userInput.equalsIgnoreCase("list")
            || userInput.equalsIgnoreCase("uidl")
            || userInput.equalsIgnoreCase("auth")
            || (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("capa"))
            || (userInput.length() >= 4 && userInput.substring(0, 4).equalsIgnoreCase("retr"))
            || (userInput.length() >= 4 && userInput.substring(0, 3).equalsIgnoreCase("top"))) {
          multi = true;
        }
      }
      // Clean up all connection objects
      serverWriter.close();
      serverReader.close();
      clientSocket.close();
      sysIn.close();
      sysOut.close();
    } catch (IOException e) {
      System.err.println(e.toString());
    }
  }