/*
   * Create and size the buffers appropriately.
   */
  private void createBuffers() {

    /*
     * We'll assume the buffer sizes are the same
     * between client and server.
     */
    SSLSession session = clientEngine.getSession();
    int appBufferMax = session.getApplicationBufferSize();
    int netBufferMax = session.getPacketBufferSize();

    /*
     * We'll make the input buffers a bit bigger than the max needed
     * size, so that unwrap()s following a successful data transfer
     * won't generate BUFFER_OVERFLOWS.
     *
     * We'll use a mix of direct and indirect ByteBuffers for
     * tutorial purposes only.  In reality, only use direct
     * ByteBuffers when they give a clear performance enhancement.
     */
    clientIn = ByteBuffer.allocate(appBufferMax + 50);
    serverIn = ByteBuffer.allocate(appBufferMax + 50);

    cTOs = ByteBuffer.allocateDirect(netBufferMax);
    sTOc = ByteBuffer.allocateDirect(netBufferMax);

    clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
    serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
  }
  /**
   * Allow the Listener a chance to customise the request. before the server does its stuff. <br>
   * This allows the required attributes to be set for SSL requests. <br>
   * The requirements of the Servlet specs are:
   *
   * <ul>
   *   <li>an attribute named "javax.servlet.request.cipher_suite" of type String.
   *   <li>an attribute named "javax.servlet.request.key_size" of type Integer.
   *   <li>an attribute named "javax.servlet.request.X509Certificate" of type
   *       java.security.cert.X509Certificate[]. This is an array of objects of type
   *       X509Certificate, the order of this array is defined as being in ascending order of trust.
   *       The first certificate in the chain is the one set by the client, the next is the one used
   *       to authenticate the first, and so on.
   * </ul>
   *
   * @param socket The Socket the request arrived on. This should be a javax.net.ssl.SSLSocket.
   * @param request HttpRequest to be customised.
   */
  protected void customizeRequest(Socket socket, HttpRequest request) {
    super.customizeRequest(socket, request);

    if (!(socket instanceof javax.net.ssl.SSLSocket))
      return; // I'm tempted to let it throw an exception...

    try {
      SSLSocket sslSocket = (SSLSocket) socket;
      SSLSession sslSession = sslSocket.getSession();
      String cipherSuite = sslSession.getCipherSuite();
      Integer keySize;
      X509Certificate[] certs;

      CachedInfo cachedInfo = (CachedInfo) sslSession.getValue(CACHED_INFO_ATTR);
      if (cachedInfo != null) {
        keySize = cachedInfo.getKeySize();
        certs = cachedInfo.getCerts();
      } else {
        keySize = new Integer(ServletSSL.deduceKeyLength(cipherSuite));
        certs = getCertChain(sslSession);
        cachedInfo = new CachedInfo(keySize, certs);
        sslSession.putValue(CACHED_INFO_ATTR, cachedInfo);
      }

      if (certs != null) request.setAttribute("javax.servlet.request.X509Certificate", certs);
      else if (_needClientAuth) // Sanity check
      throw new HttpException(HttpResponse.__403_Forbidden);

      request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
      request.setAttribute("javax.servlet.request.key_size", keySize);
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
    }
  }
Beispiel #3
0
 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());
 }
  // Server identity checking is done according to RFC 2818: HTTP over TLS
  // Section 3.1 Server Identity
  private void checkURLSpoofing(HostnameVerifier hostnameVerifier) throws IOException {
    //
    // Get authenticated server name, if any
    //
    boolean done = false;
    String host = url.getHost();

    // if IPv6 strip off the "[]"
    if (host != null && host.startsWith("[") && host.endsWith("]")) {
      host = host.substring(1, host.length() - 1);
    }

    Certificate[] peerCerts = null;
    try {
      // get the subject's certificate
      peerCerts = session.getPeerCertificates();

      X509Certificate peerCert;
      if (peerCerts[0] instanceof java.security.cert.X509Certificate) {
        peerCert = (java.security.cert.X509Certificate) peerCerts[0];
      } else {
        throw new SSLPeerUnverifiedException("");
      }

      HostnameChecker checker = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS);

      checker.match(host, peerCert);

      // if it doesn't throw an exception, we passed. Return.
      return;

    } catch (SSLPeerUnverifiedException e) {

      //
      // client explicitly changed default policy and enabled
      // anonymous ciphers; we can't check the standard policy
      //
      // ignore
    } catch (java.security.cert.CertificateException cpe) {
      // ignore
    }

    // Assume the peerCerts are already cloned.
    String cipher = session.getCipherSuite();
    if ((cipher != null) && (cipher.indexOf("_anon_") != -1)) {
      return;
    } else if ((hostnameVerifier != null) && (hostnameVerifier.verify(host, session))) {
      return;
    }

    serverSocket.close();
    session.invalidate();

    throw new IOException("HTTPS hostname wrong:  should be <" + url.getHost() + ">");
  }
Beispiel #5
0
 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());
 }
 public SSLSocketChannelWrapper(SSLContext sslContext, SocketChannel sc, boolean client)
     throws Exception {
   super(sc);
   sslEngine = sslContext.createSSLEngine();
   sslEngine.setUseClientMode(client);
   sslEngine.setEnableSessionCreation(true);
   SSLSession session = sslEngine.getSession();
   in = ByteBuffer.allocate(64 * 1024);
   emptyBuffer = ByteBuffer.allocate(0);
   int netBufferMax = session.getPacketBufferSize();
   netOutBuffer = ByteBuffer.allocate(netBufferMax);
   netInBuffer = ByteBuffer.allocate(netBufferMax);
 }
  /**
   * Return the chain of X509 certificates used to negotiate the SSL Session.
   *
   * <p>Note: in order to do this we must convert a javax.security.cert.X509Certificate[], as used
   * by JSSE to a java.security.cert.X509Certificate[],as required by the Servlet specs.
   *
   * @param sslSession the javax.net.ssl.SSLSession to use as the source of the cert chain.
   * @return the chain of java.security.cert.X509Certificates used to negotiate the SSL connection.
   *     <br>
   *     Will be null if the chain is missing or empty.
   */
  private static X509Certificate[] getCertChain(SSLSession sslSession) {
    try {
      javax.security.cert.X509Certificate javaxCerts[] = sslSession.getPeerCertificateChain();
      if (javaxCerts == null || javaxCerts.length == 0) return null;

      int length = javaxCerts.length;
      X509Certificate[] javaCerts = new X509Certificate[length];

      java.security.cert.CertificateFactory cf =
          java.security.cert.CertificateFactory.getInstance("X.509");
      for (int i = 0; i < length; i++) {
        byte bytes[] = javaxCerts[i].getEncoded();
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        javaCerts[i] = (X509Certificate) cf.generateCertificate(stream);
      }

      return javaCerts;
    } catch (SSLPeerUnverifiedException pue) {
      return null;
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
      return null;
    }
  }
Beispiel #8
0
  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();
    }
  }
 /**
  * Returns the local certificates being used in this connection.
  *
  * @return The local certificates.
  */
 public Certificate[] getLocalCertificates() {
   if (session != null) return session.getLocalCertificates();
   return null;
 }
 /**
  * Returns the name of the cipher that was negotiated in this connection.
  *
  * @return The negotiated cipher name.
  */
 public String getCipherSuite() {
   if (session != null) return session.getCipherSuite();
   return null;
 }
 public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
   if (session != null) return session.getPeerCertificateChain();
   return null;
 }
 /**
  * Returns the X.509 certificate chain with which the server authenticated itself, or null if the
  * server did not authenticate.
  */
 javax.security.cert.X509Certificate[] getServerCertificateChain()
     throws SSLPeerUnverifiedException {
   return session.getPeerCertificateChain();
 }
 /**
  * Returns the certificate chain with which the server authenticated itself, or throw a
  * SSLPeerUnverifiedException if the server did not authenticate.
  */
 java.security.cert.Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
   return session.getPeerCertificates();
 }
 /**
  * Returns the certificate chain the client sent to the server, or null if the client did not
  * authenticate.
  */
 public java.security.cert.Certificate[] getLocalCertificates() {
   return session.getLocalCertificates();
 }
 /** Returns the cipher suite in use on this connection. */
 String getCipherSuite() {
   return session.getCipherSuite();
 }