Esempio n. 1
0
  // =========================================================================================================
  // HTTPS handling
  private HttpServer createHttpsServer(
      InetSocketAddress pSocketAddress, JolokiaServerConfig pConfig) {
    // initialise the HTTPS server
    try {
      HttpsServer server = HttpsServer.create(pSocketAddress, pConfig.getBacklog());
      SSLContext sslContext = SSLContext.getInstance(pConfig.getSecureSocketProtocol());

      // initialise the keystore
      KeyStore ks = getKeyStore(pConfig);

      // setup the key manager factory
      KeyManagerFactory kmf = getKeyManagerFactory(pConfig);
      kmf.init(ks, pConfig.getKeystorePassword());

      // setup the trust manager factory
      TrustManagerFactory tmf = getTrustManagerFactory(pConfig);
      tmf.init(ks);

      // setup the HTTPS context and parameters
      sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

      // Update the config to filter out bad protocols or ciphers
      pConfig.updateHTTPSSettingsFromContext(sslContext);

      server.setHttpsConfigurator(new JolokiaHttpsConfigurator(sslContext, pConfig));
      return server;
    } catch (GeneralSecurityException e) {
      throw new IllegalStateException("Cannot use keystore for https communication: " + e, e);
    } catch (IOException e) {
      throw new IllegalStateException("Cannot open keystore for https communication: " + e, e);
    }
  }
Esempio n. 2
0
 private SSLSocketFactory createSocketFactory(String domain) throws Exception {
   SSLSocketFactory factory;
   KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystore, KEYSTORE_PASSWORD);
   SSLContext sslContext = SSLContext.getInstance("TLS");
   KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
   keyManagers = wrapKeyManagers(keyManagers, domain);
   sslContext.init(keyManagers, getAllTrustingManager(), secureRandom);
   factory = sslContext.getSocketFactory();
   return factory;
 }
  /*
   * 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 static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
Esempio n. 5
0
 void main1() throws SQLException, IOException, KeyManagementException, NoSuchAlgorithmException {
   netNodeTable.connectToFedAll();
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(
       defaultKmf.getKeyManagers(), new TrustManager[] {new AnyClientTrustManager()}, null);
   SSLServerSocket serverSocket =
       (SSLServerSocket) context.getServerSocketFactory().createServerSocket(port);
   serverSocket.setNeedClientAuth(true);
   userInputThread.start();
   while (true) {
     SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
     fingTable.addAndStart(new FingThread(myDb.create(), netNodeTable, fingTable, clientSocket));
   }
 }
Esempio n. 6
0
  JSSEServer(CipherTest cipherTest) throws Exception {
    super(cipherTest);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(
        new KeyManager[] {cipherTest.keyManager},
        new TrustManager[] {cipherTest.trustManager},
        cipherTest.secureRandom);

    SSLServerSocketFactory factory =
        (SSLServerSocketFactory) serverContext.getServerSocketFactory();
    serverSocket = (SSLServerSocket) factory.createServerSocket(cipherTest.serverPort);
    cipherTest.serverPort = serverSocket.getLocalPort();
    serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites());
    serverSocket.setWantClientAuth(true);
  }
Esempio n. 7
0
  /*
   * Using the SSLContext created during object creation,
   * create/configure the SSLEngines we'll use for this test.
   */
  private void createSSLEngines() throws Exception {
    /*
     * Configure the serverEngine to act as a server in the SSL/TLS
     * handshake.  Also, require SSL client authentication.
     */
    serverEngine = sslc.createSSLEngine();
    serverEngine.setUseClientMode(false);
    serverEngine.setNeedClientAuth(true);

    /*
     * Similar to above, but using client mode instead.
     */
    clientEngine = sslc.createSSLEngine("client", 80);
    clientEngine.setUseClientMode(true);
  }
Esempio n. 8
0
  /*
   * If this is a secure server, we now setup the SSLContext we'll
   * use for creating the SSLEngines throughout the lifetime of
   * this process.
   */
  private void createSSLContext() throws Exception {

    char[] passphrase = "passphrase".toCharArray();

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("testkeys"), passphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, passphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
  }
Esempio n. 9
0
  public static SSLContext sslContext() throws Exception {
    // trust manager
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(buildKeyStore());

    // key manager
    KeyManagerFactory keyManagerFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(buildKeyStore(), KEY_STORE_PASSWORD.toCharArray());

    // ssl context
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(
        keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    return sslContext;
  }
  public static SSLContext createSSLContext(AtomicBoolean trust) {
    try {
      KeyManager[] keyManagers = createKeyManagers();
      TrustManager[] trustManagers =
          new TrustManager[] {
            dummyTrustManager(trust, (X509TrustManager) createTrustManagers()[0])
          };
      SecureRandom secureRandom = new SecureRandom();

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(keyManagers, trustManagers, secureRandom);

      return sslContext;
    } catch (Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext", e);
    }
  }
Esempio n. 11
0
 private Socket secureConnect() throws IOException {
   if (socket_factory == null) {
     try {
       SSLContext context = SSLContext.getInstance("TLS");
       context.init(getKeyManagers(config.getCertFile(), config.getCertPhrase()), null, sec_rnd);
       socket_factory = context.getSocketFactory();
     } catch (GeneralSecurityException security_exception) {
       throw new IOException("Failed to create SSL socket factory.");
     } catch (IOException io_exception) {
       throw new IOException("Failed to read APNS certificate.");
     }
   }
   SSLSocket ssl_socket = null;
   ssl_socket =
       (SSLSocket)
           socket_factory.createSocket(config.getHostname(service), config.getPort(service));
   ssl_socket.setUseClientMode(true);
   return ssl_socket;
 }
Esempio n. 12
0
 private void preSetup() throws SocketException, IOException {
   SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
   serverSocket = serverSocketFactory.createServerSocket(port);
   serverSocket.setReuseAddress(true);
   // if (cipherSuites != null) {
   // ((SSLServerSocket)
   // serverSocket).setEnabledCipherSuites(cipherSuites);
   // }
   LOGGER.debug("|| presetup successful");
 }
Esempio n. 13
0
  public static void main(PeerFactory peerFactory, KeyStore keyStore, String[] args)
      throws Exception {

    long time = System.currentTimeMillis();
    String relPath;
    if ((args != null) && (args.length > 0) && args[0].equals("sh")) {
      relPath = pathToStoresSH;
    } else {
      relPath = pathToStores;
    }
    PATH = new File(System.getProperty("test.src", "."), relPath);
    CipherTest.peerFactory = peerFactory;
    System.out.print("Initializing test '" + peerFactory.getName() + "'...");
    //      secureRandom = new SecureRandom();
    //      secureRandom.nextInt();
    //      trustStore = readKeyStore(trustStoreFile);
    CipherTest.keyStore = keyStore;
    //      keyStore = readKeyStore(keyStoreFile);
    KeyManagerFactory keyFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore, "test12".toCharArray());
    keyManager = (X509ExtendedKeyManager) keyFactory.getKeyManagers()[0];

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    trustManager = (X509TrustManager) tmf.getTrustManagers()[0];

    //      trustManager = new AlwaysTrustManager();
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null);
    SSLContext.setDefault(context);

    CipherTest cipherTest = new CipherTest(peerFactory);
    Thread serverThread = new Thread(peerFactory.newServer(cipherTest), "Server");
    serverThread.setDaemon(true);
    serverThread.start();
    System.out.println("Done");
    cipherTest.run();
    time = System.currentTimeMillis() - time;
    System.out.println("Done. (" + time + " ms)");
  }
Esempio n. 14
0
    /** {@inheritDoc} */
    public void configure(HttpsParameters params) {
      // initialise the SSL context
      SSLEngine engine = context.createSSLEngine();
      // get the default parameters
      SSLParameters defaultSSLParameters = context.getDefaultSSLParameters();

      // Cert authentication is delayed later to the ClientCertAuthenticator
      params.setWantClientAuth(serverConfig.useSslClientAuthentication());
      defaultSSLParameters.setWantClientAuth(serverConfig.useSslClientAuthentication());

      // Cipher Suites
      params.setCipherSuites(serverConfig.getSSLCipherSuites());
      defaultSSLParameters.setCipherSuites(serverConfig.getSSLCipherSuites());

      // Protocols
      params.setProtocols(serverConfig.getSSLProtocols());
      defaultSSLParameters.setProtocols(serverConfig.getSSLProtocols());

      params.setSSLParameters(defaultSSLParameters);
    }
Esempio n. 15
0
  public TLSServer(KeyStore keyStore, String password, String protocol, int port)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          UnrecoverableKeyException, KeyManagementException {

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, password.toCharArray());
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagers, trustManagers, null);

    cipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Provider: " + sslContext.getProvider());
      LOGGER.debug(
          "Supported cipher suites ("
              + sslContext.getServerSocketFactory().getSupportedCipherSuites().length
              + ")");
      for (String c : sslContext.getServerSocketFactory().getSupportedCipherSuites()) {
        LOGGER.debug(" " + c);
      }
    }

    this.port = port;
    LOGGER.info("SSL Server successfully initialized!");
  }
Esempio n. 16
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);
    }
  }
Esempio n. 17
0
  private void initGlobal() {
    boolean globalInitDone = false;

    if (!globalInitDone) {
      try {
        ctx = SSLContext.getInstance("TLS");
      } catch (NoSuchAlgorithmException e) {
        throw new Exception(e.toString());
      }

      globalInitDone = true;
    }
  }
Esempio n. 18
0
  static {
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      KeyStore ts = KeyStore.getInstance("JKS");

      char[] passphrase = "passphrase".toCharArray();

      ks.load(new FileInputStream(keyFilename), passphrase);
      ts.load(new FileInputStream(trustFilename), passphrase);

      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, passphrase);

      TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
      tmf.init(ts);

      SSLContext sslCtx = SSLContext.getInstance("TLS");
      sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
      sslc = sslCtx;
    } catch (Exception e) {
      loadException = e;
    }
  }
Esempio n. 19
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
  /*
   * 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();
  }