public static void main(String[] args) throws Exception { SSLContext sslContext = createSSLContext(); SSLServerSocketFactory fact = sslContext.getServerSocketFactory(); SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(Utils.PORT_NO); // client authenticate where possible sSock.setWantClientAuth(true); for (; ; ) { SSLSocket sslSock = (SSLSocket) sSock.accept(); try { sslSock.startHandshake(); } catch (IOException e) { continue; } readRequest(sslSock.getInputStream()); SSLSession session = sslSock.getSession(); try { Principal clientID = session.getPeerPrincipal(); System.out.println("client identified as: " + clientID); } catch (SSLPeerUnverifiedException e) { System.out.println("client not authenticated"); } sendResponse(sslSock.getOutputStream()); sslSock.close(); } }
public void testSetEnabledProtocolsAffectsGetter() throws Exception { SSLServerSocket socket = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(); String[] protocols = new String[] {socket.getSupportedProtocols()[0]}; socket.setEnabledProtocols(protocols); assertEquals(Arrays.asList(protocols), Arrays.asList(socket.getEnabledProtocols())); }
// Method for creating a socket private static SSLServerSocket createSecureSocket() throws Exception { // Generate a generic server SSLServerSocket server = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(2877); // Enable ciphers server.setEnabledCipherSuites(server.getSupportedCipherSuites()); // Return the socket return server; /*//Key password and file char[] keyPass = "******".toCharArray(); InputStream keyStream = HID.class.getResourceAsStream( "/com/arkazex/frc2877/signin/ssl.key"); //Load the key store KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keyStream, keyPass); //Initialize the key manager factory KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyPass); //Get the key managers KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); //Initialize the SSL context SSLContext sslContext = SSLContext.getDefault(); sslContext.init(keyManagers, null, new SecureRandom()); //Get the socket factory SSLServerSocketFactory factory = sslContext.getServerSocketFactory(); //Get the socket return (SSLServerSocket) factory.createServerSocket(2877); */ }
public static void main(String[] args) throws Exception { Properties properties = new Properties(); FileInputStream propFile = new FileInputStream("store.properties"); properties.load(propFile); final String id = properties.getProperty("ID"); final String placeForFiles = properties.getProperty("FilePlace"); int servicePort = Integer.parseInt(properties.getProperty("ServicePort")); int tcpPort = Integer.parseInt(properties.getProperty("TCPPort")); String ksName = properties.getProperty("KeyStore"); KeyStore ks = KeyStore.getInstance(properties.getProperty("KeyStoreType")); char[] password = properties.getProperty("Password").toCharArray(); char[] passwordForKey = properties.getProperty("PasswordForKey").toCharArray(); ks.load(new FileInputStream(ksName), password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passwordForKey); SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), null, null); SSLServerSocketFactory ssf = context.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(tcpPort); ServiceThread serviceThread = new ServiceThread(servicePort, id); serviceThread.start(); while (!serverSocket.isClosed()) { ClientThread client = new ClientThread(placeForFiles); SSLSocket socket = (SSLSocket) serverSocket.accept(); socket.startHandshake(); client.setSocket(socket); client.start(); } }
protected ServerSocket createSocket(URI uri) throws IOException, NoSuchAlgorithmException, KeyManagementException { SslConnector cnn = null; ServerSocketFactory ssf = null; cnn = (SslConnector) connector; // An SSLContext is an environment for implementing JSSE // It is used to create a ServerSocketFactory SSLContext sslc = SSLContext.getInstance(cnn.getProtocol().toLowerCase()); // Initialize the SSLContext to work with our key managers sslc.init(cnn.getKeyManagerFactory().getKeyManagers(), null, null); ssf = sslc.getServerSocketFactory(); String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost"); int backlog = cnn.getBacklog(); SSLServerSocket serverSocket = null; InetAddress inetAddress = InetAddress.getByName(host); if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress() || host.trim().equals("localhost")) { serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog); } else { serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog, inetAddress); } // Authenticate the client? serverSocket.setNeedClientAuth(cnn.isRequireClientAuthentication()); return serverSocket; }
/** * Configure Client authentication for this version of JSSE. The JSSE included in Java 1.4 * supports the 'want' value. Prior versions of JSSE will treat 'want' as 'false'. * * @param socket the SSLServerSocket */ protected void configureClientAuth(SSLServerSocket socket) { if (wantClientAuth) { socket.setWantClientAuth(wantClientAuth); } else { socket.setNeedClientAuth(requireClientAuth); } }
/** * @param p_address * @param p_acceptQueueSize * @return * @exception IOException */ protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize) throws IOException { SSLServerSocketFactory factory = null; SSLServerSocket socket = null; try { factory = createFactory(); if (p_address == null) { socket = (SSLServerSocket) factory.createServerSocket(0, p_acceptQueueSize); } else { socket = (SSLServerSocket) factory.createServerSocket( p_address.getPort(), p_acceptQueueSize, p_address.getInetAddress()); } socket.setNeedClientAuth(_needClientAuth); log.info("JsseListener.needClientAuth=" + _needClientAuth); } catch (IOException e) { throw e; } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); throw new IOException("Could not create JsseListener: " + e.toString()); } return socket; }
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(); }
/** * Create an SSL server socket at the specified InetSocketAddress. If the type is SSL_MUTUALAUTH * then SSL client authentication is requested. */ private ServerSocket createSSLServerSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { if (inetSocketAddress == null) { throw new IOException(getFormatMessage("iiop.invalid_sslserverport", new Object[] {null})); } int port = inetSocketAddress.getPort(); Integer iport = new Integer(port); SSLInfo sslInfo = (SSLInfo) portToSSLInfo.get(iport); if (sslInfo == null) { throw new IOException(getFormatMessage("iiop.invalid_sslserverport", new Object[] {iport})); } SSLServerSocketFactory ssf = sslInfo.getContext().getServerSocketFactory(); String[] ssl3TlsCiphers = sslInfo.getSsl3TlsCiphers(); String[] ssl2Ciphers = sslInfo.getSsl2Ciphers(); String[] ciphers = null; if (ssl3TlsCiphers != null || ssl2Ciphers != null) { String[] socketCiphers = ssf.getDefaultCipherSuites(); ciphers = mergeCiphers(socketCiphers, ssl3TlsCiphers, ssl2Ciphers); } String cs[] = null; if (_logger.isLoggable(Level.FINE)) { cs = ssf.getSupportedCipherSuites(); for (int i = 0; i < cs.length; ++i) { _logger.log(Level.FINE, "Cipher Suite: " + cs[i]); } } ServerSocket ss = null; try { // bugfix for 6349541 // specify the ip address to bind to, 50 is the default used // by the ssf implementation when only the port is specified ss = ssf.createServerSocket(port, BACKLOG, inetSocketAddress.getAddress()); if (ciphers != null) { ((SSLServerSocket) ss).setEnabledCipherSuites(ciphers); } } catch (IOException e) { _logger.log( Level.SEVERE, "iiop.createsocket_exception", new Object[] {type, String.valueOf(port)}); _logger.log(Level.SEVERE, "", e); throw e; } try { if (type.equals(SSL_MUTUALAUTH)) { _logger.log(Level.FINE, "Setting Mutual auth"); ((SSLServerSocket) ss).setNeedClientAuth(true); } } catch (Exception e) { _logger.log(Level.SEVERE, "iiop.cipher_exception", e); throw new IOException(e.getMessage()); } if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, "Created server socket:" + ss); } return ss; }
public void testPropertyPlaceholders() throws Exception { CamelContext camelContext = this.createPropertiesPlaceholderAwareContext(); KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setCamelContext(camelContext); ksp.setType("{{keyStoreParameters.type}}"); ksp.setProvider("{{keyStoreParameters.provider}}"); ksp.setResource("{{keyStoreParameters.resource}}"); ksp.setPassword("{{keyStoreParamerers.password}}"); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setCamelContext(camelContext); kmp.setKeyStore(ksp); kmp.setKeyPassword("{{keyManagersParameters.keyPassword}}"); kmp.setAlgorithm("{{keyManagersParameters.algorithm}}"); kmp.setProvider("{{keyManagersParameters.provider}}"); TrustManagersParameters tmp = new TrustManagersParameters(); tmp.setCamelContext(camelContext); tmp.setKeyStore(ksp); tmp.setAlgorithm("{{trustManagersParameters.algorithm}}"); tmp.setProvider("{{trustManagersParameters.provider}}"); CipherSuitesParameters csp = new CipherSuitesParameters(); csp.getCipherSuite().add("{{cipherSuite.0}}"); SecureSocketProtocolsParameters sspp = new SecureSocketProtocolsParameters(); sspp.getSecureSocketProtocol().add("{{secureSocketProtocol.0}}"); SSLContextServerParameters scsp = new SSLContextServerParameters(); scsp.setCamelContext(camelContext); scsp.setClientAuthentication("{{sslContextServerParameters.clientAuthentication}}"); SSLContextParameters scp = new SSLContextParameters(); scp.setCamelContext(camelContext); scp.setKeyManagers(kmp); scp.setTrustManagers(tmp); scp.setServerParameters(scsp); scp.setProvider("{{sslContextParameters.provider}}"); scp.setSecureSocketProtocol("{{sslContextParameters.protocol}}"); scp.setSessionTimeout("{{sslContextParameters.sessionTimeout}}"); scp.setCipherSuites(csp); scp.setSecureSocketProtocols(sspp); SSLContext context = scp.createSSLContext(); SSLServerSocket serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(); assertTrue(serverSocket.getNeedClientAuth()); context.getSocketFactory().createSocket(); context.createSSLEngine(); }
/** * Configures the given SSL server socket with the requested cipher suites, protocol versions, and * need for client authentication */ private void initServerSocket(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; socket.setEnabledCipherSuites(enabledCiphers); socket.setEnabledProtocols(enabledProtocols); // we don't know if client auth is needed - // after parsing the request we may re-handshake configureClientAuth(socket); configureUseServerCipherSuitesOrder(socket); }
public void go() throws Exception { // Create a SSLServerSocketFactory with configured Key Store SSLServerSocketFactory socketFac = createServerSocketFactory(); // Create a server socket to use SSLServerSocket serverSocket = (SSLServerSocket) socketFac.createServerSocket(0, 0); // Configure the server socket with a cipher suite (optional) serverSocket.setEnabledCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"}); // Wait for a connection from a client serverSocket.accept(); }
/** * Gets a server socket - this gets as SSL socket instead of the standard socket returned in the * base class. */ protected ServerSocket getServerSocket() throws IOException { // Just to make sure it's set before we start SSLContext context = getSSLContext(this.keystore, this.password); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket ss = (SSLServerSocket) (this.listenAddress == null ? factory.createServerSocket(this.listenPort, BACKLOG_COUNT) : factory.createServerSocket( this.listenPort, BACKLOG_COUNT, InetAddress.getByName(this.listenAddress))); ss.setEnableSessionCreation(true); ss.setWantClientAuth(true); return ss; }
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)); } }
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); }
public static void main(String[] args) throws Exception { try { Class.forName("javax.security.auth.kerberos.KerberosPrincipal"); System.out.println("Kerberos is present, nothing to test"); return; } catch (ClassNotFoundException okay) { } // test SSLSocket try (Socket s = SSLSocketFactory.getDefault().createSocket()) { SSLSocket sslSocket = (SSLSocket) s; checkNotSupported(sslSocket.getSupportedCipherSuites()); // attempt to enable each of the Kerberos cipher suites for (String kcs : KERBEROS_CIPHER_SUITES) { String[] suites = {kcs}; try { sslSocket.setEnabledCipherSuites(suites); throw new RuntimeException( "SSLSocket.setEnabledCipherSuitessuites allowed " + kcs + " but Kerberos not supported"); } catch (IllegalArgumentException expected) { } } } // test SSLServerSocket try (ServerSocket ss = SSLServerSocketFactory.getDefault().createServerSocket()) { SSLServerSocket sslSocket = (SSLServerSocket) ss; checkNotSupported(sslSocket.getSupportedCipherSuites()); // attempt to enable each of the Kerberos cipher suites for (String kcs : KERBEROS_CIPHER_SUITES) { String[] suites = {kcs}; try { sslSocket.setEnabledCipherSuites(suites); throw new RuntimeException( "SSLSocket.setEnabledCipherSuitessuites allowed " + kcs + " but Kerberos not supported"); } catch (IllegalArgumentException expected) { } } } }
public void close() { try { serverSocket.close(); } catch (Exception e) { throw new RuntimeException(e); } }
static void accept(KeyStore keyStore, char[] keyPassword, KeyStore trustStore, int port) throws GeneralSecurityException, IOException { SSLContext sslContext = SSLContexts.create(keyStore, keyPassword, trustStore); SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port); try { serverSocket.setNeedClientAuth(true); SSLSocket clientSocket = (SSLSocket) serverSocket.accept(); javax.security.cert.X509Certificate peer = clientSocket.getSession().getPeerCertificateChain()[0]; logger.info("peer: " + peer.getSubjectDN().getName()); ServerThread.handle(clientSocket); } finally { serverSocket.close(); } }
@Override public void run() { SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslserversocket; try { System.out.println("Desktop starting at port " + PORT); sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(); // certificate is made with: "keytool -genkey keystore -keyalg RSA" // this below is a 'hack' (the hack was adding all cipher suites, this is the only one we need sslserversocket.setEnabledCipherSuites(new String[] {"SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"}); sslserversocket.bind(new InetSocketAddress(localhost, PORT)); SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); InputStream inputstream = sslsocket.getInputStream(); OutputStream outputstream = sslsocket.getOutputStream(); outgoingSerial = new ObjectOutputStream(outputstream); incomingSerial = new ObjectInputStream(inputstream) { // @Override // public Object readObject(){ // // } }; } catch (IOException e) { e.printStackTrace(); } sendNewTicketType(); // executor.scheduleAtFixedRate(new Runnable() { // // @Override // public void run() { while (true) { waitForMessages(); } // System.out.println("are we finished?"); // // } // }, 0, 50, TimeUnit.MILLISECONDS); // in the rest of the lifetime... }
public static TServerSocket getServerSSLSocket( String hiveHost, int portNum, String keyStorePath, String keyStorePassWord, List<String> sslVersionBlacklist, int socketTimeout, boolean keepAlive) throws TTransportException, UnknownHostException { TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); params.setKeyStore(keyStorePath, keyStorePassWord); InetSocketAddress serverAddress; if (hiveHost == null || hiveHost.isEmpty()) { // Wildcard bind serverAddress = new InetSocketAddress(portNum); } else { serverAddress = new InetSocketAddress(hiveHost, portNum); } TServerSocket thriftServerSocket = TSSLTransportFactory.getServerSocket( portNum, socketTimeout, serverAddress.getAddress(), params); if (thriftServerSocket.getServerSocket() instanceof SSLServerSocket) { List<String> sslVersionBlacklistLocal = new ArrayList<String>(); for (String sslVersion : sslVersionBlacklist) { sslVersionBlacklistLocal.add(sslVersion.trim().toLowerCase()); } SSLServerSocket sslServerSocket = (SSLServerSocket) thriftServerSocket.getServerSocket(); List<String> enabledProtocols = new ArrayList<String>(); for (String protocol : sslServerSocket.getEnabledProtocols()) { if (sslVersionBlacklistLocal.contains(protocol.toLowerCase())) { LOG.debug("Disabling SSL Protocol: " + protocol); } else { enabledProtocols.add(protocol); } } sslServerSocket.setEnabledProtocols(enabledProtocols.toArray(new String[0])); LOG.info( "SSL Server Socket Enabled Protocols: " + Arrays.toString(sslServerSocket.getEnabledProtocols())); } if (keepAlive) { thriftServerSocket = new TServerSocketKeepAlive(thriftServerSocket.getServerSocket()); } return thriftServerSocket; }
/* * 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; } }
public Socket accept() throws IOException { SSLSocket secureSocket = (SSLSocket) s.accept(); // Do the commons-ssl usual housekeeping for every socket: ssl.doPreConnectSocketStuff(secureSocket); InetAddress addr = secureSocket.getInetAddress(); String hostName = addr.getHostName(); ssl.doPostConnectSocketStuff(secureSocket, hostName); return wf.wrap(secureSocket); }
/* * 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(); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); sslIS.read(); sslOS.write('A'); sslOS.flush(); sslSocket.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(); 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(); } }
// Server loop private static void serverLoop() throws Exception { // Check if client is connected if (hidOut == null && !busy) { // Busy busy = true; // Notify // System.out.println("Awaiting HID client..."); // No client is connected - accept connection SSLSocket client = (SSLSocket) server.accept(); // Require auth // client.setNeedClientAuth(true); // Enable ciphers client.setEnabledCipherSuites(client.getEnabledCipherSuites()); // Add a handshake listener client.addHandshakeCompletedListener( new HandshakeCompletedListener() { @Override public void handshakeCompleted(HandshakeCompletedEvent event) { handleClient(event); } }); // Start handshake client.startHandshake(); } else { // Check client status try { // System.out.print("Checking HID client status..."); if (!connected) { // System.out.println(Color.YELLOW + " Connecting..." + // Color.RESET); return; } // Send a ping to the client hidOut.write(0x01); // System.out.println(Color.GREEN + " Connected!" + Color.RESET); Thread.sleep(1000); } catch (Exception e) { // System.out.println(Color.RED + " Not Connected!" + Color.RESET); // Reset variables hidClient = null; hidOut = null; busy = false; connected = false; // Reset display Display.readyMessage = Display.defaultReadyMessage; Display.ready(); // Notify System.out.println(Color.BLUE + "NOTICE: " + Color.RESET + "HID client has disconnected"); } } }
/** TestSSLContext creation method that allows separate creation of client and server key store */ public static TestSSLContext create( KeyStore clientKeyStore, char[] clientStorePassword, KeyStore serverKeyStore, char[] serverStorePassword, KeyManager clientKeyManagers, KeyManager serverKeyManagers, TrustManager clientTrustManagers, TrustManager serverTrustManagers, SSLContext clientContext, SSLContext serverContext) { try { SSLServerSocket serverSocket = (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0); InetAddress host = InetAddress.getLocalHost(); int port = serverSocket.getLocalPort(); return new TestSSLContext( clientKeyStore, clientStorePassword, serverKeyStore, serverStorePassword, (X509ExtendedKeyManager) clientKeyManagers, (X509ExtendedKeyManager) serverKeyManagers, (X509TrustManager) clientTrustManagers, (X509TrustManager) serverTrustManagers, clientContext, serverContext, serverSocket, host, port); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
public void startListener() { try { String jksFile = "Key/plainserver.jks"; char clienttPass[] = "password".toCharArray(); // keys get stored in java keystore which is password protected char keyStorePass[] = "password".toCharArray(); KeyStore keyst = KeyStore.getInstance("JKS"); keyst.load(new FileInputStream(jksFile), keyStorePass); KeyManagerFactory keyMngFact = KeyManagerFactory.getInstance("SunX509"); keyMngFact.init(keyst, clienttPass); SSLContext sslcon = SSLContext.getInstance("TLS"); sslcon.init(keyMngFact.getKeyManagers(), null, null); SSLServerSocketFactory sslfact = sslcon.getServerSocketFactory(); SSLServerSocket mSock = (SSLServerSocket) sslfact.createServerSocket(8083); System.out.println("Server started:"); while (true) { try { SSLSocket clientSock = (SSLSocket) mSock.accept(); ConnectionHandler newCon = new ConnectionHandler(clientSock, webAppMap); newCon.run(); } catch (Exception e) { System.out.println("Hi"); // e.printStackTrace(); } } } 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 { 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(); }
public void run() { System.out.println("JSSE Server listening on port " + cipherTest.serverPort); Executor exec = Executors.newFixedThreadPool(cipherTest.THREADS, DaemonThreadFactory.INSTANCE); try { while (true) { final SSLSocket socket = (SSLSocket) serverSocket.accept(); socket.setSoTimeout(cipherTest.TIMEOUT); Runnable r = new Runnable() { public void run() { try { InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); handleRequest(in, out); out.flush(); socket.close(); socket.getSession().invalidate(); } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { cipherTest.setFailed(); System.out.println("Exception closing socket on server side:"); e.printStackTrace(); } } } } }; exec.execute(r); } } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); // } }
public void run() { try { store = provideKeys ? getKeyStore(keys) : null; KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null; TrustManager[] trustManagers = new TrustManager[] {trustManager}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); if (clientAuth == CLIENT_AUTH_WANTED) { serverSocket.setWantClientAuth(true); } else if (clientAuth == CLIENT_AUTH_NEEDED) { serverSocket.setNeedClientAuth(true); } else { serverSocket.setWantClientAuth(false); } serverSocket.bind(new InetSocketAddress(port)); SSLSocket clientSocket = (SSLSocket) serverSocket.accept(); InputStream istream = clientSocket.getInputStream(); byte[] buffer = new byte[1024]; istream.read(buffer); OutputStream ostream = clientSocket.getOutputStream(); ostream.write(testData.getBytes()); ostream.flush(); while (notFinished) { Thread.currentThread().sleep(500); } clientSocket.close(); serverSocket.close(); } catch (Exception ex) { exception = ex; } }