コード例 #1
0
ファイル: SSLServer.java プロジェクト: CarlousF/sslsocket
  public static void main(String[] args) throws IOException {

    System.out.println("opening a secure socket");

    SSLServerSocketFactory secSocketFactory =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket secSocket = (SSLServerSocket) secSocketFactory.createServerSocket(portNo);

    String[] enabledCipherSuites = {"SSL_DH_anon_WITH_RC4_128_MD5"};
    secSocket.setEnabledCipherSuites(enabledCipherSuites);

    System.out.println("Listening on port no: " + portNo);
    SSLSocket socket = (SSLSocket) secSocket.accept();

    System.out.println("Got a connection from: " + socket.getInetAddress().toString());
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String line = in.readLine();
    while (line != null) {
      System.out.println(line);
      line = in.readLine();
    }

    out.close();
    in.close();
    socket.close();
    secSocket.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);

    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();
  }
コード例 #3
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();
  }
コード例 #4
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;
    }
  }
コード例 #5
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();
    }
  }
  /*
   * 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();
  }
コード例 #7
0
ファイル: InstallCert.java プロジェクト: eusoulevi/adsdk
  public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
      String[] c = args[0].split(":");
      host = c[0];
      port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
      String p = (args.length == 1) ? "changeit" : args[1];
      passphrase = p.toCharArray();
    } else {
      System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
      return;
    }

    File file = new File("jssecacerts");
    if (file.isFile() == false) {
      char SEP = File.separatorChar;
      File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
      file = new File(dir, "jssecacerts");
      if (file.isFile() == false) {
        file = new File(dir, "cacerts");
      }
    }
    System.out.println("Loading KeyStore " + file + "...");
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
      System.out.println("Starting SSL handshake...");
      socket.startHandshake();
      socket.close();
      System.out.println();
      System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
      System.out.println();
      e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
      System.out.println("Could not obtain server certificate chain");
      return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
      X509Certificate cert = chain[i];
      System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
      System.out.println("   Issuer  " + cert.getIssuerDN());
      sha1.update(cert.getEncoded());
      System.out.println("   sha1    " + toHexString(sha1.digest()));
      md5.update(cert.getEncoded());
      System.out.println("   md5     " + toHexString(md5.digest()));
      System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
      k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
      System.out.println("KeyStore not changed");
      return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
  }
コード例 #8
0
ファイル: client.java プロジェクト: initiumSrc/EIT060
  public static void main(String[] args) throws Exception {
    String host = null;
    int port = -1;
    for (int i = 0; i < args.length; i++) {
      System.out.println("args[" + i + "] = " + args[i]);
    }
    if (args.length < 2) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }
    try {
        /* get input parameters */
      host = args[0];
      port = Integer.parseInt(args[1]);
    } catch (IllegalArgumentException e) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }

    try {
        /* set up a key manager for client authentication */
      SSLSocketFactory factory = null;
      try {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        SSLContext ctx = SSLContext.getInstance("TLS");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keystore: ");
        String keystoreName = br.readLine();
        Console cons = System.console();

        if (cons != null) {
          password = cons.readPassword("%s", "Password: "******"Cannot find a console to read password from. Eclipse CANNOT fork a terminal child process.");
        }

        ks.load(new FileInputStream("keystores/" + keystoreName), password); // keystore
        // password
        // (storepass)
        char[] cliTrustPW = "password".toCharArray();
        ts.load(new FileInputStream("clienttruststore"), cliTrustPW); // truststore
        // password
        // (storepass);
        kmf.init(ks, password); // user password (keypass)
        tmf.init(ts); // keystore can be used as truststore here
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        factory = ctx.getSocketFactory();
      } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      }

      SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
      System.out.println("Handshake socket: " + socket + "\n");

      /*
       * send http request
       *
       * See SSLSocketClient.java for more information about why there is
       * a forced handshake here when using PrintWriters.
       */
      socket.startHandshake();

      SSLSession session = socket.getSession();
      X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0];
      System.out.println("Server DN: " + cert.getSubjectDN().getName());
      System.out.println("Handshake socket: " + socket);
      System.out.println("Secure connection.");
      System.out.println("Issuer DN: " + cert.getIssuerDN().getName());
      System.out.println("Serial N: " + cert.getSerialNumber().toString());

      read = new BufferedReader(new InputStreamReader(System.in));
      serverMsg = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      ois = new ObjectInputStream(socket.getInputStream());
      records = new ArrayList<Record>();

      boolean isLoggedIn = false;
      boolean isDone = false;

      isLoggedIn = waitForLoginData();

      if (!isLoggedIn) {
        System.out.println(
            "This certificate does not have a user. \n Press the RETURN key to exit.");
        System.console().readLine();

        out.close();
        read.close();
        socket.close();
        return;
      }

      boolean accessDenied = false;

      while (!isDone) {

        if (accessDenied) {
          System.out.println(
              "Access denied, or no such record exists! \n Type 'help' for commands.");
        }

        System.out.print(user.getUsername() + " commands>");
        msg = read.readLine();
        fetchRecords();
        splitMsg = msg.split("\\s+");

        try {
          if (msg.equalsIgnoreCase("quit")) {
            break;
          } else if (msg.equalsIgnoreCase("help")) {
            printHelp();
          } else if (splitMsg[0].equalsIgnoreCase("records")) {
            printRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("edit") && (accessDenied = hasPermissions(msg))) {
            editRecord(splitMsg[1]);
            fetchRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("read") && (accessDenied = hasPermissions(msg))) {
            printRecord(splitMsg[1]);
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("delete")
              && (accessDenied = hasPermissions(msg))) {
            for (Record r : records) {
              if (r.getId() == Long.parseLong(splitMsg[1])) {
                r.delete(user);
                accessDenied = false;
              }
            }
            fetchRecords();
          } else if (splitMsg[0].equalsIgnoreCase("create")
              && (accessDenied = hasPermissions(msg))) {
            createRecord();
            fetchRecords();
            accessDenied = false;
          } else {
            accessDenied = true;
          }
        } catch (Exception e) {
          accessDenied = true;
        }
      }

      ois.close();
      out.close();
      read.close();
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #9
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();
  }
コード例 #10
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());
    }
  }