/*
   * 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();
  }
コード例 #2
0
  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);
  }
コード例 #3
0
ファイル: CipherTest.java プロジェクト: OzkanCiftci/jdk7u-jdk
  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();
  }
コード例 #4
0
 public Socket createSocket(String host, int port) throws IOException {
   Socket s = this.factory.createSocket(host, port);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setEnabledCipherSuites(this.getNoAuthCiperSuites(ssl.getSupportedCipherSuites()));
   }
   return s;
 }
コード例 #5
0
 public Socket createSocket(String host, int port) throws IOException {
   Socket s = this.factory.createSocket(host, port);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setUseClientMode(false); // client offers to authenticate itself
     ssl.setNeedClientAuth(true);
   }
   return s;
 }
コード例 #6
0
 public Socket createSocket(
     InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException {
   Socket s = this.factory.createSocket(address, port, clientAddress, clientPort);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setEnabledCipherSuites(this.getNoAuthCiperSuites(ssl.getSupportedCipherSuites()));
   }
   return s;
 }
コード例 #7
0
 public Socket createSocket(
     InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException {
   Socket s = this.factory.createSocket(address, port, clientAddress, clientPort);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setUseClientMode(false); // client offers to authenticate itself
     ssl.setNeedClientAuth(true);
   }
   return s;
 }
コード例 #8
0
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
コード例 #9
0
  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) {
        }
      }
    }
  }
コード例 #10
0
ファイル: POPConsole.java プロジェクト: MKotlik/GioMhail
 private static void printConnectionInfo(SSLSocket s) {
   SSLSession currentSession = s.getSession();
   System.out.println("Protocol: " + currentSession.getProtocol());
   System.out.println("Cipher Suite: " + currentSession.getCipherSuite());
   System.out.println("Host: " + currentSession.getPeerHost());
   System.out.println("Host Port: " + currentSession.getPeerPort());
 }
コード例 #11
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    DataOutputStream out = new DataOutputStream(sslSocket.getOutputStream());

    try {
      // get path to class file from header
      DataInputStream in = new DataInputStream(sslSocket.getInputStream());
      String path = getPath(in);
      // retrieve bytecodes
      byte[] bytecodes = getBytes(path);
      // send bytecodes in response (assumes HTTP/1.0 or later)
      try {
        out.writeBytes("HTTP/1.0 200 OK\r\n");
        out.writeBytes("Content-Length: " + bytecodes.length + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.write(bytecodes);
        out.flush();
      } catch (IOException ie) {
        ie.printStackTrace();
        return;
      }

    } catch (Exception e) {
      e.printStackTrace();
      // write out error response
      out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
      out.writeBytes("Content-Type: text/html\r\n\r\n");
      out.flush();
    } finally {
      // close the socket
      System.out.println("Server closing socket");
      sslSocket.close();
      serverReady = false;
    }
  }
コード例 #12
0
ファイル: POPConsole.java プロジェクト: MKotlik/GioMhail
 private static void printSocketInfo(SSLSocket s) {
   System.out.println("Socket class: " + s.getClass());
   System.out.println("   Remote address = " + s.getInetAddress().toString());
   System.out.println("   Remote port = " + s.getPort());
   System.out.println("   Local socket address = " + s.getLocalSocketAddress().toString());
   System.out.println("   Local address = " + s.getLocalAddress().toString());
   System.out.println("   Local port = " + s.getLocalPort());
   System.out.println("   Need client authentication = " + s.getNeedClientAuth());
   SSLSession ss = s.getSession();
   System.out.println("   Cipher suite = " + ss.getCipherSuite());
   System.out.println("   Protocol = " + ss.getProtocol());
 }
コード例 #13
0
ファイル: JSSEServer.java プロジェクト: jjjunior/jdk7u-jdk
 public void run() {
   System.out.println("JSSE Server listening on port " + cipherTest.serverPort);
   Executor exec = Executors.newFixedThreadPool(cipherTest.THREADS, DaemonThreadFactory.INSTANCE);
   try {
     while (true) {
       final SSLSocket socket = (SSLSocket) serverSocket.accept();
       socket.setSoTimeout(cipherTest.TIMEOUT);
       Runnable r =
           new Runnable() {
             public void run() {
               try {
                 InputStream in = socket.getInputStream();
                 OutputStream out = socket.getOutputStream();
                 handleRequest(in, out);
                 out.flush();
                 socket.close();
                 socket.getSession().invalidate();
               } catch (IOException e) {
                 cipherTest.setFailed();
                 e.printStackTrace();
               } finally {
                 if (socket != null) {
                   try {
                     socket.close();
                   } catch (IOException e) {
                     cipherTest.setFailed();
                     System.out.println("Exception closing socket on server side:");
                     e.printStackTrace();
                   }
                 }
               }
             }
           };
       exec.execute(r);
     }
   } catch (IOException e) {
     cipherTest.setFailed();
     e.printStackTrace();
     //
   }
 }
コード例 #14
0
  /*
   * 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();
    try {
      InputStream sslIS = sslSocket.getInputStream();
      OutputStream sslOS = sslSocket.getOutputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(sslIS));
      PrintStream ps = new PrintStream(sslOS);

      // process HTTP POST request from client
      System.out.println("status line: " + br.readLine());
      String msg = null;
      while ((msg = br.readLine()) != null && msg.length() > 0) ;

      msg = br.readLine();
      if (msg.equals(postMsg)) {
        ps.println("HTTP/1.1 200 OK\n\n");
      } else {
        ps.println("HTTP/1.1 500 Not OK\n\n");
      }
      ps.flush();

      // close the socket
      while (!closeReady) {
        Thread.sleep(50);
      }
    } finally {
      sslSocket.close();
      sslServerSocket.close();
    }
  }
コード例 #15
0
ファイル: TcpSocketPeer.java プロジェクト: SlimerDude/f4
  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);
    }
  }
コード例 #16
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslSocket.addHandshakeCompletedListener(this);
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

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

    System.out.println("invalidating");
    sslSocket.getSession().invalidate();
    System.out.println("starting new handshake");
    sslSocket.startHandshake();

    for (int i = 0; i < 10; i++) {
      System.out.println("sending/receiving data, iteration: " + i);
      sslIS.read();
      sslOS.write(85);
      sslOS.flush();
    }

    sslSocket.close();
  }
コード例 #17
0
  /*
   * 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 {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

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

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

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

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

    kmf1.init(ks, cpasswd);

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

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

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

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
コード例 #18
0
ファイル: POPConsole.java プロジェクト: MKotlik/GioMhail
  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());
    }
  }