// ========================================================================================================= // 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); } }
public KeyManagerFactory getKeyManagerFactory(KeyStore keystore, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException { char[] passphrase = password == null ? null : password.toCharArray(); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(Configuration.getSSLAlgorithm()); keyManagerFactory.init(keystore, passphrase); return keyManagerFactory; }
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); } }
/** * Get the KeyManagers for the the specified keystore * * @param ksFile The keystore to manager * @param ksPass The keystore password * @return KeyManagers that can manage the keystore * @throws Exception */ protected KeyManager[] getKeyManagers(String ksFile, String ksPass) throws Exception { if (HttpMessageContext.emptyString(ksFile)) { ksFile = System.getProperty("javax.net.ssl.keyStore"); } if (HttpMessageContext.emptyString(ksPass)) { ksPass = System.getProperty("javax.net.ssl.keyStorePassword", "changeit"); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(ksFile), ksPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, ksPass.toCharArray()); return kmf.getKeyManagers(); }
// An X.509 key manager for a KeyStore public static KeyManager keyManager(final KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { final KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509", "SunJSSE"); synchronized (factory) { factory.init(keyStore, keyStorePassword); for (KeyManager km : factory.getKeyManagers()) { if (km instanceof X509KeyManager) { return km; } } return null; } }
/* * 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); }
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; }
private HttpServer httpsServer(InetSocketAddress address) throws IOException, GeneralSecurityException { // Initialize the keystore char[] password = "******".toCharArray(); ks = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream("UMS.jks")) { ks.load(fis, password); } // Setup the key manager factory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); // Setup the trust manager factory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); HttpsServer server = HttpsServer.create(address, 0); sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); server.setHttpsConfigurator( new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { try { // initialise the SSL context SSLContext c = SSLContext.getDefault(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(true); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); // get the default parameters SSLParameters defaultSSLParameters = c.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (Exception e) { LOGGER.debug("https configure error " + e); } } }); return server; }
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)"); }
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; } }
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)); } }
private KeyManagerFactory getKeyManagerFactory(JolokiaServerConfig pConfig) throws NoSuchAlgorithmException { String algo = pConfig.getKeyManagerAlgorithm(); return KeyManagerFactory.getInstance( algo != null ? algo : KeyManagerFactory.getDefaultAlgorithm()); }
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(); } }
/* * 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(); }