List of usage examples for javax.net.ssl SSLSocket close
public synchronized void close() throws IOException
From source file:info.guardianproject.net.ModSSLSocketFactory.java
public Socket connectSocket(final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); }// w w w . jav a 2 s . co m if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } //Socket underlying = (Socket) // ((sock != null) ? sock : createSocket()); Socket underlying = sock; if (underlying == null) underlying = new Socket(); mSocksSocketFactory.connectSocket(underlying, host, port, localAddress, localPort, params); SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(underlying, host, port, true); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } // int connTimeout = HttpConnectionParams.getConnectionTimeout(params); // int soTimeout = HttpConnectionParams.getSoTimeout(params); // // InetSocketAddress remoteAddress; // if (this.nameResolver != null) { // remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); // } else { // remoteAddress = new InetSocketAddress(host, port); // } // // //sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(0); try { hostnameVerifier.verify(host, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } return sslsock; }
From source file:iracing.webapi.IracingWebApi.java
private void installCerts() throws Exception { String host = "members.iracing.com"; int port = 443; char[] password = CERT_STORE_PASSWORD.toCharArray(); File file = new File("jssecacerts"); if (!file.isFile()) { char seperator = File.separatorChar; File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security"); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); }//from ww w.j a va 2s . c om } KeyStore ks; InputStream in = new FileInputStream(file); ks = KeyStore.getInstance(KeyStore.getDefaultType()); try { ks.load(in, password); } catch (Exception e) { } in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); SSLSocket socket = null; try { socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); socket.startHandshake(); } catch (Exception e) { //e.printStackTrace(); } finally { if (socket != null) socket.close(); } X509Certificate[] chain = tm.chain; if (chain == null) return; MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); } for (int count = 0; count < chain.length; count++) { X509Certificate cert = chain[count]; String alias = host + "-" + (count + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); try { ks.store(out, password); } finally { out.close(); } } }
From source file:com.android.emailcommon.utility.SSLSocketFactory.java
@Override public Socket connectSocket(final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); }//from w w w. j a v a 2 s . com if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress; if (nameResolver != null) { remoteAddress = new InetSocketAddress(nameResolver.resolve(host), port); } else { remoteAddress = new InetSocketAddress(host, port); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); // Set Server Name Indication if is available for this socket setSocketHostname(sslsock, host); // Start handshake prior to hostname verification to ensure // handshake exceptions do not get silenced by hostname verification. sslsock.startHandshake(); try { hostnameVerifier.verify(host, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } return sslsock; }
From source file:org.lockss.protocol.BlockingStreamComm.java
protected void handshake(SSLSocket s) throws SSLPeerUnverifiedException { long oldTimeout = -2; try {/*from ww w.ja v a 2s . c o m*/ oldTimeout = s.getSoTimeout(); if (absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) { s.setSoTimeout((int) paramSslHandshakeTimeout); } } catch (SocketException e) { log.warning("Couldn't save/set socket timeout before handshake", e); } try { SSLSession session = s.getSession(); java.security.cert.Certificate[] certs = session.getPeerCertificates(); log.debug(session.getPeerHost() + " via " + session.getProtocol() + " verified"); } catch (SSLPeerUnverifiedException ex) { log.error(s.getInetAddress() + ":" + s.getPort() + " not verified"); try { s.close(); } catch (IOException ex2) { log.error("Socket close threw " + ex2); } throw ex; } finally { if (!s.isClosed() && absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) { try { s.setSoTimeout((int) oldTimeout); } catch (SocketException e) { log.warning("Couldn't restore socket timeout after handshake", e); } } } }
From source file:org.kuali.mobility.push.dao.DeviceFeedbackMonitor.java
/** * This is a private method that checks Apple's feedback service for devices that need to be removed. * //from w w w . j a va 2 s . com */ private void checkiOSDeviceFeedback() { LOG.info("Checking iOS Device Feedback"); final int cFEEDBACKTUPLESIZE = 38; final int cBLOCKSIZE = 1024; final int cBYTEMASK = 0x000000FF; // SSLSocket feedbackSocket = openAppleSocket(feedbackHost, feedbackPort); SSLSocket feedbackSocket = null; try { feedbackSocket = iOSFeedbackConnectionPool.borrowObject(); } catch (Exception e) { LOG.info("Was unable to borrow SSQLSocket from Pool"); } if (null == feedbackSocket) { LOG.info("APNS Feedback Socket is NOT connected."); } else { LOG.info("APNS Feedback Socket is connected. Checking Feedback."); try { InputStream in = feedbackSocket.getInputStream(); // Read bytes byte[] b = new byte[cBLOCKSIZE]; ByteArrayOutputStream message = new ByteArrayOutputStream(); int nbBytes = 0; // socketStream.available can return 0 // http://forums.sun.com/thread.jspa?threadID=5428561 while ((nbBytes = in.read(b, 0, cBLOCKSIZE)) != -1) { message.write(b, 0, nbBytes); } byte[] listOfDevices = message.toByteArray(); int nbDevices = listOfDevices.length / cFEEDBACKTUPLESIZE; LOG.info(nbDevices + " devices had feedback."); for (int j = 0; j < nbDevices; j++) { int offset = j * cFEEDBACKTUPLESIZE; // Build date int index = 0; int firstByte = 0; int secondByte = 0; int thirdByte = 0; int fourthByte = 0; long anUnsignedInt = 0; firstByte = (cBYTEMASK & ((int) listOfDevices[offset])); secondByte = (cBYTEMASK & ((int) listOfDevices[offset + 1])); thirdByte = (cBYTEMASK); fourthByte = (cBYTEMASK & ((int) listOfDevices[offset + 3])); index = index + 4; anUnsignedInt = ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL; Timestamp timestamp = new Timestamp(anUnsignedInt * 1000); // Build device token length int deviceTokenLength = listOfDevices[offset + 4] << 8 | listOfDevices[offset + 5]; // Build device token String deviceToken = ""; int octet = 0; for (int k = 0; k < 32; k++) { octet = (cBYTEMASK & ((int) listOfDevices[offset + 6 + k])); deviceToken = deviceToken.concat(String.format("%02x", octet)); } LOG.info(timestamp); LOG.info(deviceToken); Device dtoDelete = deviceService.findDeviceByRegId(deviceToken); if (deviceService.removeDevice(dtoDelete)) { LOG.info("Deleted " + dtoDelete.getDeviceName()); } } } catch (Exception e) { } finally { try { feedbackSocket.close(); } catch (Exception e) { } } } }
From source file:spade.resolver.Recursive.java
/** * Computes a result, or throws an exception if unable to do so. * * @return computed result//from w w w . jav a 2 s . c om * @throws Exception if unable to compute a result */ @Override public Graph call() throws Exception { Graph resultGraph = null; try { // Establish a connection to the remote host String host = networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_ADDRESS); int port = Integer.parseInt(Settings.getProperty("commandline_query_port")); logger.log(Level.INFO, "network Vertex: " + networkVertex); SSLSocket remoteSocket = (SSLSocket) Kernel.sslSocketFactory.createSocket(); int connectTimeOut = 5000; // 5 sec remoteSocket.connect(new InetSocketAddress(host, port), connectTimeOut); // SSLSocket remoteSocket = (SSLSocket) Kernel.sslSocketFactory.createSocket(host, port); OutputStream outStream = remoteSocket.getOutputStream(); InputStream inStream = remoteSocket.getInputStream(); ObjectInputStream graphInputStream = new ObjectInputStream(inStream); PrintWriter remoteSocketOut = new PrintWriter(outStream, true); String networkVertexQuery = "GetVertex(" + OPMConstants.ARTIFACT_LOCAL_ADDRESS + AbstractQuery.OPERATORS.EQUALS + networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_ADDRESS) + " AND " + OPMConstants.ARTIFACT_LOCAL_PORT + AbstractQuery.OPERATORS.EQUALS + networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_PORT) + " AND " + OPMConstants.ARTIFACT_REMOTE_ADDRESS + AbstractQuery.OPERATORS.EQUALS + networkVertex.getAnnotation(OPMConstants.ARTIFACT_LOCAL_ADDRESS) + " AND " + OPMConstants.ARTIFACT_REMOTE_PORT + AbstractQuery.OPERATORS.EQUALS + networkVertex.getAnnotation(OPMConstants.ARTIFACT_LOCAL_PORT) + " AND " + OPMConstants.SOURCE + AbstractQuery.OPERATORS.EQUALS + OPMConstants.SOURCE_AUDIT_NETFILTER + ")"; remoteSocketOut.println(networkVertexQuery); logger.log(Level.INFO, "remote vertex query: " + networkVertexQuery); String returnType = (String) graphInputStream.readObject(); // Check whether the remote query server returned a vertex set in response Set<AbstractVertex> vertexSet; if (returnType.equals(Set.class.getName())) { vertexSet = (Set<AbstractVertex>) graphInputStream.readObject(); } else { logger.log(Level.INFO, "Return type not Set!"); return null; } AbstractVertex targetNetworkVertex; if (!CollectionUtils.isEmpty(vertexSet)) { targetNetworkVertex = vertexSet.iterator().next(); } else { logger.log(Level.INFO, "TargetNetworkVertex empty!"); return null; } String targetNetworkVertexHash = targetNetworkVertex.bigHashCode(); String lineageQuery = "GetLineage(" + PRIMARY_KEY + AbstractQuery.OPERATORS.EQUALS + targetNetworkVertexHash + ", " + depth + ", " + direction + ")"; remoteSocketOut.println(lineageQuery); logger.log(Level.INFO, "remote lineage query: " + lineageQuery); returnType = (String) graphInputStream.readObject(); if (returnType.equals(Graph.class.getName())) { AbstractEdge localToRemoteEdge = new Edge(networkVertex, targetNetworkVertex); localToRemoteEdge.addAnnotation("type", "WasDerivedFrom"); AbstractEdge remoteToLocalEdge = new Edge(targetNetworkVertex, networkVertex); remoteToLocalEdge.addAnnotation("type", "WasDerivedFrom"); resultGraph = (Graph) graphInputStream.readObject(); resultGraph.putVertex(networkVertex); resultGraph.putEdge(localToRemoteEdge); resultGraph.putEdge(remoteToLocalEdge); } else { logger.log(Level.INFO, "Return type not Graph!"); } remoteSocketOut.println("exit"); remoteSocketOut.close(); graphInputStream.close(); inStream.close(); outStream.close(); remoteSocket.close(); } catch (NumberFormatException | IOException | ClassNotFoundException exception) { logger.log(Level.SEVERE, "Remote resolution unsuccessful!", exception); return null; } logger.log(Level.INFO, "Remote resolution successful!"); return resultGraph; }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {//from w w w .ja v a 2s .com SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Secure session established"); LOGGER.debug(" negotiated protocol: {}", session.getProtocol()); LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); LOGGER.debug(" peer principal: {}", peer); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" peer alternative names: {}", altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); LOGGER.debug(" issuer principal: {}", issuer); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" issuer alternative names: {}", altNames); } } catch (Exception ignore) { } } if (!this.hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (RuntimeException | IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { iox.addSuppressed(x); } throw iox; } }
From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {/*w w w . j a v a 2s.c o m*/ SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" issuer alternative names: " + altNames); } } catch (Exception ignore) { } } HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier; if (!hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }
From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {// ww w. j a va 2 s . c o m SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" issuer alternative names: " + altNames); } } catch (Exception ignore) { } } if (!this.hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }
From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {// w ww . j av a2 s .c om SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } /* if (this.log.isDebugEnabled()) { this.log.debug("Secure session established"); this.log.debug(" negotiated protocol: " + session.getProtocol()); this.log.debug(" negotiated cipher suite: " + session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); this.log.debug(" peer principal: " + peer.toString()); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" peer alternative names: " + altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); this.log.debug(" issuer principal: " + issuer.toString()); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<String>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } this.log.debug(" issuer alternative names: " + altNames); } } catch (Exception ignore) { } } */ if (!this.hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (final IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { /*ignore*/ } throw iox; } }