Пример #1
0
  /**
   * 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);
    }
  }
Пример #2
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());
 }
Пример #3
0
  public void afterConnect() throws IOException, UnknownHostException {
    if (!isCachedConnection()) {
      SSLSocket s = null;
      SSLSocketFactory factory;
      factory = sslSocketFactory;
      try {
        if (!(serverSocket instanceof SSLSocket)) {
          s = (SSLSocket) factory.createSocket(serverSocket, host, port, true);
        } else {
          s = (SSLSocket) serverSocket;
        }
      } catch (IOException ex) {
        // If we fail to connect through the tunnel, try it
        // locally, as a last resort.  If this doesn't work,
        // throw the original exception.
        try {
          s = (SSLSocket) factory.createSocket(host, port);
        } catch (IOException ignored) {
          throw ex;
        }
      }

      SSLSocketFactoryImpl.checkCreate(s);

      //
      // Force handshaking, so that we get any authentication.
      // Register a handshake callback so our session state tracks any
      // later session renegotiations.
      //
      String[] protocols = getProtocols();
      String[] ciphers = getCipherSuites();
      if (protocols != null) s.setEnabledProtocols(protocols);
      if (ciphers != null) s.setEnabledCipherSuites(ciphers);
      s.addHandshakeCompletedListener(this);
      s.startHandshake();
      session = s.getSession();
      // change the serverSocket and serverOutput
      serverSocket = s;
      try {
        serverOutput =
            new PrintStream(
                new BufferedOutputStream(serverSocket.getOutputStream()), false, encoding);
      } catch (UnsupportedEncodingException e) {
        throw new InternalError(encoding + " encoding not found");
      }

      // check URL spoofing
      checkURLSpoofing(hv);
    } else {
      // if we are reusing a cached https session,
      // we don't need to do handshaking etc. But we do need to
      // set the ssl session
      session = ((SSLSocket) serverSocket).getSession();
    }
  }
Пример #4
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());
 }
  /*
   * 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();
  }
Пример #6
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();
    }
  }