public static Handshake get(SSLSession session) throws IOException { String cipherSuiteString = session.getCipherSuite(); if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null"); if ("SSL_NULL_WITH_NULL_NULL".equals(cipherSuiteString)) { throw new IOException("cipherSuite == SSL_NULL_WITH_NULL_NULL"); } CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString); String tlsVersionString = session.getProtocol(); if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null"); if ("NONE".equals(tlsVersionString)) throw new IOException("tlsVersion == NONE"); TlsVersion tlsVersion = TlsVersion.forJavaName(tlsVersionString); Certificate[] peerCertificates; try { peerCertificates = session.getPeerCertificates(); } catch (SSLPeerUnverifiedException ignored) { peerCertificates = null; } List<Certificate> peerCertificatesList = peerCertificates != null ? Util.immutableList(peerCertificates) : Collections.emptyList(); Certificate[] localCertificates = session.getLocalCertificates(); List<Certificate> localCertificatesList = localCertificates != null ? Util.immutableList(localCertificates) : Collections.emptyList(); return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList); }
public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean client) throws IOException { if (!socketChannel.isConnected()) { throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel"); } this.channel = socketChannel; this.socketAddress = socketChannel.getRemoteAddress(); final Socket socket = socketChannel.socket(); this.hostname = socket.getInetAddress().getHostName(); this.port = socket.getPort(); this.engine = sslContext.createSSLEngine(); this.engine.setUseClientMode(client); this.engine.setNeedClientAuth(true); streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize())); }
public static X509Certificate[] getCertsFromChannel(Channel channel) { X509Certificate[] certificates = null; ChannelHandler channelHandler = channel.pipeline().get("ssl"); if (channelHandler != null && channelHandler instanceof SslHandler) { SslHandler sslHandler = (SslHandler) channelHandler; try { certificates = sslHandler.engine().getSession().getPeerCertificateChain(); } catch (SSLPeerUnverifiedException e) { // ignore } } return certificates; } }
private SSLConfigValidatorEngine(SslFactory sslFactory, SSLContext sslContext, Mode mode) { this.sslEngine = sslFactory.createSslEngine(sslContext, "localhost", 0); // these hints are not used for validation sslEngine.setUseClientMode(mode == Mode.CLIENT); appBuffer = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize()); netBuffer = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize()); }
/** * Allocate application buffer. */ private ByteBuffer allocateAppBuff() { int netBufSize = sslEngine.getSession().getPacketBufferSize() + 50; int appBufSize = Math.max(sslEngine.getSession().getApplicationBufferSize() + 50, netBufSize * 2); ByteBuffer buf = ByteBuffer.allocate(appBufSize); buf.order(order); return buf; }
protected void accept() { try(SSLSocket client_sock=(SSLSocket)srv_sock.accept()) { client_sock.setEnabledCipherSuites(client_sock.getSupportedCipherSuites()); client_sock.startHandshake(); SSLSession sslSession=client_sock.getSession(); local_addr, client_sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); DataOutput out=new DataOutputStream(client_sock.getOutputStream()); byte ordinal=(byte)in.read(); Type req=Type.values()[ordinal]; if(req != Type.SECRET_KEY_REQ)
SSLSession session = ssl.getSession(); if (session == null) { InputStream in = ssl.getInputStream(); in.available(); session = ssl.getSession(); if (session == null) { certs = session.getPeerCertificates(); } catch (SSLPeerUnverifiedException spue) { InputStream in = ssl.getInputStream(); in.available();
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSession session = sslsock.getSession(); X509Certificate cert; try { cert = (X509Certificate) session.getPeerCertificates()[0]; } catch (SSLPeerUnverifiedException e) { System.err.println(session.getPeerHost() + " did not present a valid cert."); return; PrintWriter out = new PrintWriter(sslsock.getOutputStream()); out.write("GET " + args[1] + " HTTP/1.0\r\n\r\n"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream())); String line; String regExp = ".*<a href=\"(.*)\">.*"; sslsock.close();
/** * @param host the host * @param port the port * * @return array with all server-side certificates obtained from direct socket connection */ public static synchronized Certificate[] getCertificatesFromSocket( String host, String port ) { TrustManager[] trustAllCerts = new TrustManager[]{ new DefaultTrustManager() {} }; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, Integer.valueOf(port)); sslSocket.startHandshake(); return sslSocket.getSession().getPeerCertificates(); } catch (Exception e) { throw new RuntimeException("Could not get certificate of secure socket to " + host + ":" + port + ".!", e); } }
final int port = siteUrl.getPort() == -1 ? siteUrl.getDefaultPort() : siteUrl.getPort(); SSLContext sslContext = SSLUtil.tryGetSSLContext(); sslContext.init(new KeyManager[0], new TrustManager[]{new AlwaysTrustManager()}, null); try (SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket()) socket.setSoTimeout(_readTimeout); socket.connect(new InetSocketAddress(siteUrl.getHost(), port), _connectTimeout); socket.startHandshake(); final Certificate[] certificateChain = socket.getSession().getPeerCertificates(); if (certificateChain != null && certificateChain.length != 0 x509Certificate.getSubjectDN(), url); return x509Certificate;
@Override protected void connect(CoapReceiver coapReceiver) throws IOException { SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(destination.getAddress(), destination.getPort()); sslSocket.addHandshakeCompletedListener(handshakeCompletedEvent -> { try { LOGGER.debug("Connected [" + handshakeCompletedEvent.getSource() + ", " + sslSocket.getSession().getPeerCertificateChain()[0].getSubjectDN() + "]"); } catch (SSLPeerUnverifiedException e) { LOGGER.warn(e.getMessage(), e); } coapReceiver.onConnected((InetSocketAddress) socket.getRemoteSocketAddress()); } ); sslSocket.startHandshake(); this.socket = sslSocket; synchronized (this) { outputStream = new BufferedOutputStream(socket.getOutputStream()); } inputStream = new BufferedInputStream(socket.getInputStream(), 1024); }
@Test public void main() throws NoSuchAlgorithmException, KeyManagementException, IOException { SSLContext sc = JavaPinning.forPin("SHA256:a4bd7ea9bf474cc459266b82fdb07f648f5ddf4d8162baea895b91c96f831ab5"); Socket socket = new Socket("github.com", 443); SSLSocket sslSocket = (SSLSocket) sc.getSocketFactory().createSocket(socket, "github.com", 443, true); sslSocket.startHandshake(); String name = sslSocket.getSession().getPeerPrincipal().getName(); // CHECKSTYLE:OFF System.out.println(name); // CHECKSTYLE:ON OutputStream os = sslSocket.getOutputStream(); os.write("GET /".getBytes()); os.flush(); } }
NIOOutputStream outputStream = null; try { channel = socket.getChannel(); channel.configureBlocking(false); sslContext = SSLContext.getDefault(); sslEngine = sslContext.createSSLEngine(remoteHost, remotePort); } else { sslEngine = sslContext.createSSLEngine(); SSLParameters sslParams = new SSLParameters(); sslParams.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParams); sslEngine.setUseClientMode(false); if (enabledCipherSuites != null) { sslEngine.setEnabledCipherSuites(enabledCipherSuites); sslSession = sslEngine.getSession(); inputBuffer = ByteBuffer.allocate(sslSession.getPacketBufferSize()); inputBuffer.clear();
protected SSLSocket createSocketTo(Address target) throws Exception { SSLContext ctx=getContext(); SSLSocketFactory sslSocketFactory=ctx.getSocketFactory(); IpAddress dest=(IpAddress)down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, target)); SSLSocket sock=null; for(int i=0; i < port_range; i++) { try { sock=(SSLSocket)sslSocketFactory.createSocket(dest.getIpAddress(), port+i); sock.setSoTimeout(socket_timeout); sock.setEnabledCipherSuites(sock.getSupportedCipherSuites()); sock.startHandshake(); SSLSession sslSession=sock.getSession(); log.debug("%s: created SSL connection to %s (%s); protocol: %s, cipher suite: %s", local_addr, target, sock.getRemoteSocketAddress(), sslSession.getProtocol(), sslSession.getCipherSuite()); if(session_verifier != null) session_verifier.verify(sslSession); return sock; } catch(SecurityException sec_ex) { throw sec_ex; } catch(Throwable t) { } } throw new IllegalStateException(String.format("failed connecting to %s (port range [%d - %d])", dest.getIpAddress(), port, port+port_range)); }
SSLSocket sslSocket = (SSLSocket)socket; try { sslSocket.startHandshake(); if (log != null) { // fix this to be logwriter level... SSLSession session = sslSocket.getSession(); Certificate[] peer = session.getPeerCertificates(); log.info(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0, ((X509Certificate)peer[0]).getSubjectDN()); if (log != null) log.severe(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort())}, ex ); throw ex; if (log != null) log.severe(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1, new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort())}, ex ); throw ex;
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException { if (!socketChannel.isConnected()) { throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel"); } this.channel = socketChannel; this.socketAddress = socketChannel.getRemoteAddress(); final Socket socket = socketChannel.socket(); this.hostname = socket.getInetAddress().getHostName(); this.port = socket.getPort(); // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it this.engine = sslEngine; streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize())); }
//nopackage DThompson 2012.08.13b import java.net.InetSocketAddress; import java.net.Socket; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class JustBConnectSSL { /* (optionally bind and) just make SSL connection, for testing reach and trust * uses default providers, truststore (normally JRE/lib/security/[jsse]cacerts), * and keystore (normally none), override with -Djavax.net.ssl.{trust,key}Store* */ public static void main (String[] args) throws Exception { if( args.length < 2 ){ System.out.println ("Usage: tohost port [fromaddr [fromport]]"); return; } Socket sock = SSLSocketFactory.getDefault().createSocket(); if( args.length > 2 ) sock.bind (new InetSocketAddress (args[2], args.length>3? Integer.parseInt(args[3]): 0)); sock.connect (new InetSocketAddress (args[0], Integer.parseInt(args[1]))); System.out.println (sock.getInetAddress().getHostName() + " = " + sock.getInetAddress().getHostAddress()); ((SSLSocket)sock).startHandshake(); System.out.println ("connect okay " + ((SSLSocket)sock).getSession().getCipherSuite()); } }
// Open SSLSocket directly to gmail.com SocketFactory sf = SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket) sf.createSocket("gmail.com", 443); HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); SSLSession s = socket.getSession(); // Verify that the certicate hostname is for mail.google.com // This is due to lack of SNI support in the current SSLSocket. if (!hv.verify("mail.google.com", s)) { throw new SSLHandshakeException("Expected mail.google.com, " "found " + s.getPeerPrincipal()); } // At this point SSLSocket performed certificate verificaiton and // we have performed hostname verification, so it is safe to proceed. // ... use socket ... socket.close();
private void createIoFilter(SocketChannel channel, boolean clientSocket) throws IOException { if (getConduit().useSSL() && channel != null) { InetSocketAddress address = (InetSocketAddress) channel.getRemoteAddress(); SSLEngine engine = getConduit().getSocketCreator().createSSLEngine(address.getHostName(), address.getPort()); if (!clientSocket) { engine.setWantClientAuth(true); engine.setNeedClientAuth(true); } int packetBufferSize = engine.getSession().getPacketBufferSize(); if (inputBuffer == null || (inputBuffer.capacity() < packetBufferSize)) { // TLS has a minimum input buffer size constraint if (inputBuffer != null) { Buffers.releaseReceiveBuffer(inputBuffer, getConduit().getStats()); } inputBuffer = Buffers.acquireReceiveBuffer(packetBufferSize, getConduit().getStats()); } if (channel.socket().getReceiveBufferSize() < packetBufferSize) { channel.socket().setReceiveBufferSize(packetBufferSize); } if (channel.socket().getSendBufferSize() < packetBufferSize) { channel.socket().setSendBufferSize(packetBufferSize); } ioFilter = getConduit().getSocketCreator().handshakeSSLSocketChannel(channel, engine, getConduit().idleConnectionTimeout, clientSocket, inputBuffer, getConduit().getStats()); } else { ioFilter = new NioPlainEngine(); } }
public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException { this.socketAddress = new InetSocketAddress(hostname, port); this.channel = SocketChannel.open(); if (localAddress != null) { final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0); this.channel.bind(localSocketAddress); } this.hostname = hostname; this.port = port; this.engine = sslContext.createSSLEngine(); this.engine.setUseClientMode(client); engine.setNeedClientAuth(true); streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize())); appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize())); }