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(); } }
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 call() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = System.out; SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault(); try { SSLSocket c = (SSLSocket) f.createSocket("localhost", 8888); printSocketInfo(c); c.startHandshake(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream())); BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream())); String m = null; while ((m = r.readLine()) != null) { out.println(m); m = in.readLine(); w.write(m, 0, m.length()); w.newLine(); w.flush(); } w.close(); r.close(); c.close(); } catch (IOException e) { System.err.println(e.toString()); } }
public HTTPSConnectSocket(String host, int port, String urlString) throws IOException { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException me) { System.out.println("Malformed url"); System.exit(1); } SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); ssl = (SSLSocket) ssf.createSocket(host, port); ssl.startHandshake(); // Send the CONNECT request ssl.getOutputStream().write(("CONNECT " + url.getFile() + " HTTP/1.0\r\n\r\n").getBytes()); // Read the first line of the response DataInputStream is = new DataInputStream(ssl.getInputStream()); String str = is.readLine(); // Check the HTTP error code -- it should be "200" on success if (!str.startsWith("HTTP/1.1 200 ")) { if (str.startsWith("HTTP/1.1 ")) str = str.substring(9); throw new IOException("Proxy reports \"" + str + "\""); } // Success -- skip remaining HTTP headers do { str = is.readLine(); } while (str.length() != 0); }
private void connect() throws IOException { Socket tmp = null; try { tmp = socketFactory.createSocket(); tmp.setTcpNoDelay(tcpNoDelay); if (sendBuffer > 0) tmp.setSendBufferSize(sendBuffer); tmp.bind(bindaddr); if (tmp instanceof SSLSocket) { SSLSocket sslsock = (SSLSocket) tmp; sslsock.setEnabledProtocols(new String[] {tlsProtocol}); sslsock.setEnabledCipherSuites(tlsCiphers); } tmp.connect(addr, tcpConnectTimeout); if (tmp instanceof SSLSocket) { SSLSocket sslsock = (SSLSocket) tmp; sslsock.startHandshake(); } sockout = new BufferedOutputStream(tmp.getOutputStream()); sock = tmp; tmp = null; } finally { if (tmp != null) try { tmp.close(); } catch (Exception ignore) { } } }
/** * SSL/TLS negotiation. Acquires an SSL socket of a control connection and carries out handshake * processing. * * @throws IOException If server negotiation fails */ protected void sslNegotiation() throws IOException { plainSocket = _socket_; initSslContext(); SSLSocketFactory ssf = context.getSocketFactory(); String ip = _socket_.getInetAddress().getHostAddress(); int port = _socket_.getPort(); SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, ip, port, false); socket.setEnableSessionCreation(isCreation); socket.setUseClientMode(isClientMode); // server mode if (!isClientMode) { socket.setNeedClientAuth(isNeedClientAuth); socket.setWantClientAuth(isWantClientAuth); } if (protocols != null) { socket.setEnabledProtocols(protocols); } if (suites != null) { socket.setEnabledCipherSuites(suites); } socket.startHandshake(); _socket_ = socket; _controlInput_ = new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding())); _controlOutput_ = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getControlEncoding())); }
/** * Returns a socket of the data connection. Wrapped as an {@link SSLSocket}, which carries out * handshake processing. * * @param command The textual representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is set to null, then the command * is sent with no arguments. * @return corresponding to the established data connection. Null is returned if an FTP protocol * error is reported at any point during the establishment and initialization of the * connection. * @throws IOException If there is any problem with the connection. * @see FTPClient#_openDataConnection_(int, String) * @since 3.2 */ @Override protected Socket _openDataConnection_(String command, String arg) throws IOException { Socket socket = super._openDataConnection_(command, arg); _prepareDataSocket_(socket); if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslSocket.setUseClientMode(isClientMode); sslSocket.setEnableSessionCreation(isCreation); // server mode if (!isClientMode) { sslSocket.setNeedClientAuth(isNeedClientAuth); sslSocket.setWantClientAuth(isWantClientAuth); } if (suites != null) { sslSocket.setEnabledCipherSuites(suites); } if (protocols != null) { sslSocket.setEnabledProtocols(protocols); } sslSocket.startHandshake(); } return socket; }
/** * Generates an SSL-enabled socket. * * @return the new socket * @throws GeneralSecurityException on error building the socket * @throws IOException on error loading the KeyStore */ private SSLSocket getSslSocket(RemoteDevice target) throws GeneralSecurityException, IOException { // Build a new key store based on the key store manager. KeyManager[] keyManagers = coreService.getKeyStoreManager().getKeyManagers(); TrustManager[] trustManagers = coreService.getKeyStoreManager().getTrustManagers(); if (keyManagers.length == 0) { throw new IllegalStateException("No key managers"); } // Create a new SSLContext, using the new KeyManagers and TrustManagers // as the sources of keys and trust decisions, respectively. SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); // Finally, build a new SSLSocketFactory from the SSLContext, and // then generate a new SSLSocket from it. SSLSocketFactory factory = sslContext.getSocketFactory(); SSLSocket sock = (SSLSocket) factory.createSocket(); sock.setNeedClientAuth(true); sock.setUseClientMode(true); sock.setKeepAlive(true); sock.setTcpNoDelay(true); InetSocketAddress fullAddr = new InetSocketAddress(target.getAddress(), target.getPort()); sock.connect(fullAddr, SOCKET_CREATION_TIMEOUT_MS); sock.startHandshake(); return sock; }
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(); } }
/** * @param p_serverSocket * @return * @exception IOException */ protected Socket accept(ServerSocket p_serverSocket) throws IOException { try { SSLSocket s = (SSLSocket) p_serverSocket.accept(); if (getMaxIdleTimeMs() > 0) s.setSoTimeout(getMaxIdleTimeMs()); s.startHandshake(); // block until SSL handshaking is done return s; } catch (SSLException e) { log.warn(LogSupport.EXCEPTION, e); throw new IOException(e.getMessage()); } }
public void handShake() throws IOException, RemoteException { try { if (ssl.getWantClientAuth()) { log.debug(sm.getString("jsseSupport.noCertWant")); } else { ssl.setNeedClientAuth(true); } if (ssl.getEnabledCipherSuites().length == 0) { // Handshake is never going to be successful. // Assume this is because handshakes are disabled log.warn(sm.getString("jsseSupport.serverRenegDisabled")); session.invalidate(); ssl.close(); return; } InputStream in = ssl.getInputStream(); int oldTimeout = ssl.getSoTimeout(); ssl.setSoTimeout(1000); byte[] b = new byte[1]; listener.reset(); ssl.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (log.isTraceEnabled()) log.trace("Reading for try #" + i); try { int read = in.read(b); if (read > 0) { // Shouldn't happen as all input should have been swallowed // before trying to do the handshake. If it does, something // went wrong so lets bomb out now. throw new SSLException(sm.getString("jsseSupport.unexpectedData")); } } catch (SSLException sslex) { log.info(sm.getString("jsseSupport.clientCertError"), sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.isCompleted()) { break; } } ssl.setSoTimeout(oldTimeout); if (listener.isCompleted() == false) { throw new SocketException("SSL Cert handshake timeout"); } } catch (Exception excp) { excp.printStackTrace(); } }
/** * Create a SSLsocket using an existing connected socket. It can be used such as a tunneled SSL * proxy socket (eg when a CONNECT request is received). This SSLSocket will start server side * handshake immediately. * * @param targethost the host where you want to connect to * @param socket * @return * @throws IOException */ public Socket createTunnelServerSocket(String targethost, Socket socket) throws IOException { // ZAP: added host name parameter SSLSocket s = (SSLSocket) getTunnelSSLSocketFactory(targethost) .createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); s.setUseClientMode(false); s.startHandshake(); return s; }
public static SSLSocket wrapSocket(Socket socket) throws Exception { // ssl socket factory SSLSocketFactory sslSocketFactory = sslContext().getSocketFactory(); // ssl socket SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true); sslSocket.setUseClientMode(true); sslSocket.startHandshake(); return sslSocket; }
public SSLSocket client(String hostName, int hostPort, boolean useClientCert) throws IOException { SSLSocket socket = null; socket = clientNoHandshake(hostName, hostPort, useClientCert); // socket.setEnabledProtocols(new String[] {"SSLv3"}); // socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_DES_CBC_SHA"}); socket.startHandshake(); return socket; }
// 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"); } } }
/** * checks if a certificate is installed for given host:port * * @param context * @param host * @param port * @return */ public IOException checkCertificate() { SSLSocketFactory factory = context.getSocketFactory(); // System.out.println("Opening connection to " + host + ":" + port + "..."); try { SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); socket.startHandshake(); socket.close(); return null; } catch (IOException e) { return e; } }
private void processHandshakeFailure(Socket raw) throws Exception { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom()); SSLSocketFactory sslSocketFactory = context.getSocketFactory(); SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); try { socket.startHandshake(); // we're testing a handshake failure throw new AssertionError(); } catch (IOException expected) { } socket.close(); }
/** Create an {@code SSLSocket} and perform the TLS handshake and certificate validation. */ private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException { Platform platform = Platform.get(); // Make an SSL Tunnel on the first message pair of each SSL + proxy connection. if (requiresTunnel()) { makeTunnel(tunnelRequest); } // Create the wrapper over connected socket. socket = route.address.sslSocketFactory.createSocket( socket, route.address.uriHost, route.address.uriPort, true /* autoClose */); SSLSocket sslSocket = (SSLSocket) socket; if (route.modernTls) { platform.enableTlsExtensions(sslSocket, route.address.uriHost); } else { platform.supportTlsIntolerantServer(sslSocket); } boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3"); if (useNpn) { platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS); } // Force handshake. This can throw! sslSocket.startHandshake(); // Verify that the socket's certificates are acceptable for the target host. if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) { throw new IOException("Hostname '" + route.address.uriHost + "' was not verified"); } out = sslSocket.getOutputStream(); in = sslSocket.getInputStream(); byte[] selectedProtocol; if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) { if (Arrays.equals(selectedProtocol, SPDY3)) { sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream. spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out).build(); spdyConnection.sendConnectionHeader(); } else if (!Arrays.equals(selectedProtocol, HTTP_11)) { throw new IOException( "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1")); } } }
public void connect() throws UnknownHostException, IOException { if (ssl_choice) { if (http_choice) { SSLSocket s = (SSLSocket) ssl_factory.createSocket(getAddress(), getPort()); s.setTcpNoDelay(true); s.startHandshake(); socket = s; } else { socket = SSLSocketFactory.getDefault().createSocket(getAddress(), getPort()); } } else { socket = new Socket(getAddress(), getPort()); } this.stream = socket.getOutputStream(); }
public SimpleRawTcpClient(String hostname, int port, boolean useSsl, int bufferSize) throws IOException { addr = InetAddress.getByName(hostname); responseBuffer = new byte[bufferSize]; if (useSsl) { SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault(); conn = f.createSocket(addr, port); SSLSocket c = (SSLSocket) conn; printSocketInfo(c); c.startHandshake(); SSLSession session = c.getSession(); SessionInfo.logSessionInfo(session, "Server"); } else { conn = new Socket(addr, port); } }
public final void verify(String s, SSLSocket sslsocket) throws IOException { if (s == null) { throw new NullPointerException("host to verify is null"); } SSLSession sslsession1 = sslsocket.getSession(); SSLSession sslsession = sslsession1; if (sslsession1 == null) { sslsocket.getInputStream().available(); SSLSession sslsession2 = sslsocket.getSession(); sslsession = sslsession2; if (sslsession2 == null) { sslsocket.startHandshake(); sslsession = sslsocket.getSession(); } } verify(s, (X509Certificate) sslsession.getPeerCertificates()[0]); }
/** * Lightweight version of SSLCertificateSocketFactory.verifyHostname, which provides this service * but is not in the public API. * * <p>Verify the hostname of the certificate used by the other end of a connected socket. You MUST * call this if you did not supply a hostname to SSLCertificateSocketFactory.createSocket(). It is * harmless to call this method redundantly if the hostname has already been verified. * * <p>Wildcard certificates are allowed to verify any matching hostname, so "foo.bar.example.com" * is verified if the peer has a certificate for "*.example.com". * * @param socket An SSL socket which has been connected to a server * @param hostname The expected hostname of the remote server * @throws IOException if something goes wrong handshaking with the server * @throws SSLPeerUnverifiedException if the server cannot prove its identity */ private static void verifyHostname(Socket socket, String hostname) throws IOException { // The code at the start of OpenSSLSocketImpl.startHandshake() // ensures that the call is idempotent, so we can safely call it. SSLSocket ssl = (SSLSocket) socket; ssl.startHandshake(); SSLSession session = ssl.getSession(); if (session == null) { throw new SSLException("Cannot verify SSL socket without session"); } // TODO: Instead of reporting the name of the server we think we're connecting to, // we should be reporting the bad name in the certificate. Unfortunately this is buried // in the verifier code and is not available in the verifier API, and extracting the // CN & alts is beyond the scope of this patch. if (!HOSTNAME_VERIFIER.verify(hostname, session)) { throw new SSLPeerUnverifiedException( "Certificate hostname not useable for server: " + hostname); } }
@Override public void execute(String commandString, Session sess) throws IOException { if (!commandString.trim().toUpperCase().equals(this.getName())) { sess.sendResponse("501 Syntax error (no parameters allowed)"); return; } try { Socket socket = sess.getSocket(); if (socket instanceof SSLSocket) { sess.sendResponse("454 TLS not available due to temporary reason: TLS already active"); return; } sess.sendResponse("220 Ready to start TLS"); InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); SSLSocketFactory sf = ((SSLSocketFactory) SSLSocketFactory.getDefault()); SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true)); // we are a server s.setUseClientMode(false); // allow all supported cipher suites s.setEnabledCipherSuites(s.getSupportedCipherSuites()); s.startHandshake(); sess.setSocket(s); sess.resetMessageState(); // clean slate } catch (SSLHandshakeException ex) { // "no cipher suites in common" is common and puts a lot of crap in the logs. // This will at least limit it to a single WARN line and not a whole stacktrace. // Unfortunately it might catch some other types of SSLHandshakeException (if // in fact other types exist), but oh well. log.warn("startTLS() failed: " + ex); } catch (IOException ex) { log.warn("startTLS() failed: " + ex.getMessage(), ex); } }
/** * Create an {@code SSLSocket} and perform the SSL handshake (performing certificate validation. * * @param sslSocketFactory Source of new {@code SSLSocket} instances. * @param tlsTolerant If true, assume server can handle common TLS extensions and SSL deflate * compression. If false, use an SSL3 only fallback mode without compression. */ public void setupSecureSocket(SSLSocketFactory sslSocketFactory, boolean tlsTolerant) throws IOException { // create the wrapper over connected socket unverifiedSocket = (SSLSocket) sslSocketFactory.createSocket( socket, address.uriHost, address.uriPort, true /* autoClose */); // tlsTolerant mimics Chrome's behavior if (tlsTolerant && unverifiedSocket instanceof OpenSSLSocketImpl) { OpenSSLSocketImpl openSslSocket = (OpenSSLSocketImpl) unverifiedSocket; openSslSocket.setEnabledCompressionMethods(new String[] {"ZLIB"}); openSslSocket.setUseSessionTickets(true); openSslSocket.setHostname(address.socketHost); // use SSLSocketFactory default enabled protocols } else { unverifiedSocket.setEnabledProtocols(new String[] {"SSLv3"}); } // force handshake, which can throw unverifiedSocket.startHandshake(); }
/** * Verify the hostname of the certificate used by the other end of a connected socket. You MUST * call this if you did not supply a hostname to {@link #createSocket()}. It is harmless to call * this method redundantly if the hostname has already been verified. * * <p>Wildcard certificates are allowed to verify any matching hostname, so "foo.bar.example.com" * is verified if the peer has a certificate for "*.example.com". * * @param socket An SSL socket which has been connected to a server * @param hostname The expected hostname of the remote server * @throws IOException if something goes wrong handshaking with the server * @throws SSLPeerUnverifiedException if the server cannot prove its identity * @hide */ public static void verifyHostname(Socket socket, String hostname) throws IOException { if (!(socket instanceof SSLSocket)) { throw new IllegalArgumentException("Attempt to verify non-SSL socket"); } if (!isSslCheckRelaxed()) { // The code at the start of OpenSSLSocketImpl.startHandshake() // ensures that the call is idempotent, so we can safely call it. SSLSocket ssl = (SSLSocket) socket; ssl.startHandshake(); SSLSession session = ssl.getSession(); if (session == null) { throw new SSLException("Cannot verify SSL socket without session"); } if (!HOSTNAME_VERIFIER.verify(hostname, session)) { throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname); } } }
/** * Wraps an ssl socket over an existing socket and compares the host name from the address to the * common name in the server certificate. * * @param bareSocket plain socket connected to the server * @param address destination of the <tt>bareSocket</tt> * @param port destination of the <tt>bareSocket</tt> * @return SSL socket wrapped around original socket with server identity verified */ private SSLSocket sslWrap(Socket bareSocket, InetAddress address, int port) throws IOException { final String hostName = address.getHostName(); final SSLSocket sslSocket = (SSLSocket) m_factory.createSocket(bareSocket, hostName, port, true); sslSocket.startHandshake(); final SSLSession session = sslSocket.getSession(); final String DN = session.getPeerCertificateChain()[0].getSubjectDN().getName(); final String CN = getCN(DN); if (!hostName.equals(CN)) { final String message = "Host name mismatch, expected '" + hostName + "' recevied DN is " + DN; throw new IOException(message); } if (getLogger().isDebugEnabled()) { final String message = "DN of the server " + DN; getLogger().debug(message); final String message2 = "Session id " + bytesToString(session.getId()); getLogger().debug(message2); } return sslSocket; }
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); } }
/** * The server has indicated that TLS negotiation can start. We now need to secure the existing * plain connection and perform a handshake. This method won't return until the connection has * finished the handshake or an error occured while securing the connection. * * @throws Exception if an exception occurs. */ void proceedTLSReceived() throws Exception { enableEncryption(true); // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Proceed to do the handshake ((SSLSocket) socket).startHandshake(); // if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println("Connection wants client auth"); // } // else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println("Connection needs client auth"); // } // else { // System.err.println("Connection does not require client auth"); // } // Set that TLS was successful usingTLS = true; // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); }
/** * Establishes and verifies a TLS connection to a (TCP-)connected SSLSocket: - set TLS parameters * like allowed protocols and ciphers - set SNI host name - verify host name - verify certificate * * @param socket unconnected SSLSocket * @param host host name for SNI * @throws java.io.IOException if the connection could not be established. */ private void establishAndVerify(SSLSocket socket, String host) throws IOException { setTlsParameters(socket); setSniHostname(socket, host); // TLS handshake, throws an exception for untrusted certificates socket.startHandshake(); // verify hostname and certificate SSLSession session = socket.getSession(); if (!hostnameVerifier.verify(host, session)) { // throw exception for invalid host names throw new SSLPeerUnverifiedException(host); } Log.i( TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using " + session.getCipherSuite()); }
/* * 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(); }