/** * Allow the Listener a chance to customise the request. before the server does its stuff. <br> * This allows the required attributes to be set for SSL requests. <br> * The requirements of the Servlet specs are: * * <ul> * <li>an attribute named "javax.servlet.request.cipher_suite" of type String. * <li>an attribute named "javax.servlet.request.key_size" of type Integer. * <li>an attribute named "javax.servlet.request.X509Certificate" of type * java.security.cert.X509Certificate[]. This is an array of objects of type * X509Certificate, the order of this array is defined as being in ascending order of trust. * The first certificate in the chain is the one set by the client, the next is the one used * to authenticate the first, and so on. * </ul> * * @param socket The Socket the request arrived on. This should be a javax.net.ssl.SSLSocket. * @param request HttpRequest to be customised. */ protected void customizeRequest(Socket socket, HttpRequest request) { super.customizeRequest(socket, request); if (!(socket instanceof javax.net.ssl.SSLSocket)) return; // I'm tempted to let it throw an exception... try { SSLSocket sslSocket = (SSLSocket) socket; SSLSession sslSession = sslSocket.getSession(); String cipherSuite = sslSession.getCipherSuite(); Integer keySize; X509Certificate[] certs; CachedInfo cachedInfo = (CachedInfo) sslSession.getValue(CACHED_INFO_ATTR); if (cachedInfo != null) { keySize = cachedInfo.getKeySize(); certs = cachedInfo.getCerts(); } else { keySize = new Integer(ServletSSL.deduceKeyLength(cipherSuite)); certs = getCertChain(sslSession); cachedInfo = new CachedInfo(keySize, certs); sslSession.putValue(CACHED_INFO_ATTR, cachedInfo); } if (certs != null) request.setAttribute("javax.servlet.request.X509Certificate", certs); else if (_needClientAuth) // Sanity check throw new HttpException(HttpResponse.__403_Forbidden); request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite); request.setAttribute("javax.servlet.request.key_size", keySize); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } }
private static void printConnectionInfo(SSLSocket s) { SSLSession currentSession = s.getSession(); System.out.println("Protocol: " + currentSession.getProtocol()); System.out.println("Cipher Suite: " + currentSession.getCipherSuite()); System.out.println("Host: " + currentSession.getPeerHost()); System.out.println("Host Port: " + currentSession.getPeerPort()); }
@Override public Object[] getPeerCertificateChain(boolean force) throws IOException, RemoteException { try { // Look up the current SSLSession if (session == null) return null; // Convert JSSE's certificate format to the ones we need X509Certificate[] jsseCerts = null; try { jsseCerts = session.getPeerCertificateChain(); } catch (Exception bex) { // ignore. } if (jsseCerts == null) jsseCerts = new X509Certificate[0]; if (jsseCerts.length <= 0 && force && ssl != null) { session.invalidate(); handShake(); session = ssl.getSession(); } return getX509Certificates(session); } catch (Exception excp) { excp.printStackTrace(); } return null; }
public void run() { try { store = provideKeys ? getKeyStore(keys) : null; KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null; TrustManager[] trustManagers = new TrustManager[] {trustManager}; clientSslContext = SSLContext.getInstance("TLS"); clientSslContext.init(keyManagers, trustManagers, null); SSLSocket socket = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); socket.connect(new InetSocketAddress(port)); OutputStream ostream = socket.getOutputStream(); ostream.write(testData.getBytes()); ostream.flush(); InputStream istream = socket.getInputStream(); byte[] buffer = new byte[1024]; istream.read(buffer); clientSession = socket.getSession(); while (notFinished) { Thread.currentThread().sleep(500); } socket.close(); } catch (Exception ex) { exception = ex; } }
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(); } }
/** * Return an {@code SSLSocket} that is not only connected but has also passed hostname * verification. * * @param hostnameVerifier Used to verify the hostname we connected to is an acceptable match for * the peer certificate chain of the SSLSession. */ public SSLSocket verifySecureSocketHostname(HostnameVerifier hostnameVerifier) throws IOException { if (!hostnameVerifier.verify(address.uriHost, unverifiedSocket.getSession())) { throw new IOException("Hostname '" + address.uriHost + "' was not verified"); } sslSocket = unverifiedSocket; return sslSocket; }
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]); }
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(); } }
private static void printSocketInfo(SSLSocket s) { LOGGER.info("Socket class: " + s.getClass()); LOGGER.info(" Remote address = " + s.getInetAddress().toString()); LOGGER.info(" Remote port = " + s.getPort()); LOGGER.info(" Local socket address = " + s.getLocalSocketAddress().toString()); LOGGER.info(" Local address = " + s.getLocalAddress().toString()); LOGGER.info(" Local port = " + s.getLocalPort()); LOGGER.info(" Need client authentication = " + s.getNeedClientAuth()); SSLSession ss = s.getSession(); LOGGER.info(" Cipher suite = " + ss.getCipherSuite()); LOGGER.info(" Protocol = " + ss.getProtocol()); }
@Override public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException { String peerHost = this.conn.getRequestProperty("Host"); if (peerHost == null) peerHost = host; Log.i(TAG, "customized createSocket. host: " + peerHost); InetAddress address = plainSocket.getInetAddress(); if (autoClose) { // we don't need the plainSocket plainSocket.close(); } // create and connect SSL socket, but don't do hostname/certificate verification yet SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0); SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port); // enable TLSv1.1/1.2 if available ssl.setEnabledProtocols(ssl.getSupportedProtocols()); // set up SNI before the handshake if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { Log.i(TAG, "Setting SNI hostname"); sslSocketFactory.setHostname(ssl, peerHost); } else { Log.d(TAG, "No documented SNI support on Android <4.2, trying with reflection"); try { java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(ssl, peerHost); } catch (Exception e) { Log.w(TAG, "SNI not useable", e); } } // verify hostname and certificate SSLSession session = ssl.getSession(); if (!hostnameVerifier.verify(peerHost, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost); Log.i( TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using " + session.getCipherSuite()); return ssl; }
/** 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")); } } }
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(); } }
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 static void logOutConnection(SSLSocket soc, String localId) throws SSLPeerUnverifiedException, CertificateException { String peerCN = getSubjectFromPrinciple(soc.getSession().getPeerPrincipal()); _log.info( "From: " + localId + " : " + soc.getInetAddress().toString() + ":" + soc.getPort() + "\n" + "To : " + peerCN + " : " + soc.getLocalAddress().toString() + ":" + soc.getLocalPort()); }
/** * 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); } }
/** * 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; }
/** * 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); } } }
@SuppressLint("NewApi") private Socket enableSNI(SSLSocket ssl, String host) throws SSLPeerUnverifiedException { // enable TLSv1.1/1.2 if available // (see https://github.com/rfc2822/davdroid/issues/229) ssl.setEnabledProtocols(ssl.getSupportedProtocols()); // set up SNI before the handshake if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { AppLog.i(T.API, "Setting SNI hostname"); mFactory.setHostname(ssl, host); } else { AppLog.i(T.API, "No documented SNI support on Android <4.2, trying with reflection"); try { java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(ssl, host); } catch (Exception e) { AppLog.e(T.API, "SNI not useable", e); } } // verify hostname and certificate SSLSession session = ssl.getSession(); if (!mHostnameVerifier.verify(host, session)) { throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); } AppLog.i( T.API, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() + " using " + session.getCipherSuite()); return ssl; }
/** * Extracts the relevant socket stuff and adds it to the request object. This method relies on the * base class for everything other than SSL related attributes */ protected void parseSocketInfo(Socket socket, WinstoneRequest req) throws IOException { super.parseSocketInfo(socket, req); if (socket instanceof SSLSocket) { SSLSocket s = (SSLSocket) socket; SSLSession ss = s.getSession(); if (ss != null) { Certificate certChain[] = null; try { certChain = ss.getPeerCertificates(); } catch (Throwable err) { /* do nothing */ } if (certChain != null) { req.setAttribute("javax.servlet.request.X509Certificate", certChain); req.setAttribute("javax.servlet.request.cipher_suite", ss.getCipherSuite()); req.setAttribute("javax.servlet.request.ssl_session", new String(ss.getId())); req.setAttribute("javax.servlet.request.key_size", getKeySize(ss.getCipherSuite())); } } req.setIsSecure(true); } }
/** * 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()); }
public boolean connect() throws IOException, NoSuchAlgorithmException, KeyManagementException { // try{ // Connect if (socket == null || socket.isClosed() || !socket.isConnected()) { if (socket != null && !socket.isClosed()) socket.close(); if (sslContext == null) { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, tm, new java.security.SecureRandom()); } SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, 443); socket.setSoTimeout(0); socket.setUseClientMode(true); connected = true; Log.i(getClass().toString(), "Connected."); } // Secure if (connected) { Log.i(getClass().toString(), "Securing..."); SSLSession session = socket.getSession(); secured = session.isValid(); if (secured) { Log.i(getClass().toString(), "Secured."); output = new BufferedOutputStream(socket.getOutputStream()); } else { Log.i(getClass().toString(), "Securing failed."); } } return connected; }
/* * 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(); }
static SSLSecurityInfoImpl create(SSLSocket socket) throws IOException { SSLSession session = socket.getSession(); java.security.cert.Certificate[] certs = session.getPeerCertificates(); CertificateImpl ci = null; if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) { // TODO: is this the right way? ci = new CertificateImpl((X509Certificate) certs[0]); } // parse protocol name and version final String protocol = session.getProtocol(); String protocolName = null; String protocolVersion = null; if (protocol.startsWith("TLS")) { protocolName = "TLS"; protocolVersion = "3.1"; } else if (protocol.startsWith("SSL")) { protocolName = "SSL"; protocolVersion = "3.0"; } return new SSLSecurityInfoImpl(session.getCipherSuite(), protocolName, protocolVersion, ci); }
private void m(Context context) { SSLSocket sslSocket = null; try { boolean connected = false; if (sslSocket == null || sslSocket.isClosed() || !sslSocket.isConnected()) { if (sslSocket != null && !sslSocket.isClosed()) { sslSocket.close(); } Log.i(getClass().toString(), "Connecting..."); // messages.getText().append("Connecting..."); final KeyStore keyStore = KeyStore.getInstance("BKS"); keyStore.load(context.getResources().openRawResource(R.raw.clientkey), null); final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); // keyManager.init(null, null); final TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(keyStore); sslContext = SSLContext.getInstance("TLS"); sslContext.init( keyManager.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom()); final SSLSocketFactory delegate = sslContext.getSocketFactory(); SocketFactory factory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket( String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket( InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; sslSocket = (SSLSocket) factory.createSocket("195.248.169.76", 4445); sslSocket.setSoTimeout(20000); sslSocket.setUseClientMode(true); connected = true; Log.i(getClass().toString(), "Connected."); // messages.getText().append("Connected."); } // Secure if (connected) { Log.i(getClass().toString(), "Securing..."); // messages.getText().append("Securing..."); SSLSession session = sslSocket.getSession(); boolean secured = session.isValid(); if (secured) { Log.i(getClass().toString(), "Secured."); // messages.getText().append("Secured."); } } } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public JSSESupport(SSLSocket sock) throws RemoteException { startManagers(); ssl = sock; session = sock.getSession(); sock.addHandshakeCompletedListener(listener); }
@Override public void verify(String host, SSLSocket ssl) throws IOException { if (!verifier.verify(host, ssl.getSession())) throw new SSLException("Hostname verification failure"); }
/** 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 && ( // Contains a spdy variant. route.address.protocols.contains(Protocol.HTTP_2) || route.address.protocols.contains(Protocol.SPDY_3)); if (useNpn) { if (route.address.protocols.contains(Protocol.HTTP_2) // Contains both spdy variants. && route.address.protocols.contains(Protocol.SPDY_3)) { platform.setNpnProtocols(sslSocket, Protocol.HTTP2_SPDY3_AND_HTTP); } else if (route.address.protocols.contains(Protocol.HTTP_2)) { platform.setNpnProtocols(sslSocket, Protocol.HTTP2_AND_HTTP_11); } else { platform.setNpnProtocols(sslSocket, Protocol.SPDY3_AND_HTTP11); } } // 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(); handshake = Handshake.get(sslSocket.getSession()); streamWrapper(); ByteString maybeProtocol; if (useNpn && (maybeProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) { Protocol selectedProtocol = Protocol.find(maybeProtocol); // Throws IOE on unknown. if (selectedProtocol.spdyVariant) { sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream. spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out) .protocol(selectedProtocol) .build(); spdyConnection.sendConnectionHeader(); } } }
/** * retrieve peer's public key from given SSLSocket instance * * @throws SSLPeerUnverifiedException */ public static PublicKey getPeerPubKey(SSLSocket soc) throws SSLPeerUnverifiedException { SSLSession session = soc.getSession(); return session.getPeerCertificateChain()[0].getPublicKey(); }
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(); } }
public SSLSession getSession() { return delegate.getSession(); }