List of usage examples for javax.net.ssl SSLSocket getInputStream
public InputStream getInputStream() throws IOException
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {//from ww w . jav a 2 s .co 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 (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 {//from w w w .jav a 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) { } } 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:ch.cyberduck.core.ftp.FTPClient.java
@Override protected void sslNegotiation() throws IOException { if (protocol.isSecure()) { final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(_socket_, _socket_.getInetAddress().getHostAddress(), _socket_.getPort(), false); socket.setEnableSessionCreation(true); socket.setUseClientMode(true);// w w w. j a va 2s . c om socket.startHandshake(); _socket_ = socket; _controlInput_ = new BufferedReader( new InputStreamReader(socket.getInputStream(), getControlEncoding())); _controlOutput_ = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), getControlEncoding())); } }
From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java
@Override public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) throw new NullPointerException("host to verify is null"); SSLSession session = ssl.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 = ssl.getInputStream(); in.available();/*from w ww .j av a 2s. co m*/ /* * If you're looking at the 2 lines of code above because you're * running into a problem, you probably have two options: * * #1. Clean up the certificate chain that your server is presenting * (e.g. edit "/etc/apache2/server.crt" or wherever it is your * server's certificate chain is defined). * * OR * * #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a * non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); }
From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java
private SSLServerConnection handleNewConn(SSLSocket sock) throws AgentConnectionException, SocketTimeoutException { SSLServerConnection res;//from w w w . j a v a 2s . c om InetAddress remoteAddr; TokenData token; String authToken; boolean doSave; remoteAddr = sock.getInetAddress(); this.log.debug("Handling SSL connection from " + remoteAddr); res = new SSLServerConnection(sock); // Validate the actual auth token which is sent try { DataInputStream dIs; dIs = new DataInputStream(sock.getInputStream()); this.log.debug("Starting to read authToken for SSL connection"); authToken = dIs.readUTF(); this.log.debug("Finished reading authToken for SSL connection"); } catch (SocketTimeoutException exc) { throw exc; } catch (IOException exc) { throw new AgentConnectionException("Error negotiating auth: " + exc.getMessage(), exc); } // Set the token from pending to locked, if need be doSave = false; try { token = this.tokenManager.getToken(authToken); } catch (TokenNotFoundException exc) { this.log.error( "Rejecting client from " + remoteAddr + ": Passed an invalid auth token (" + authToken + ")", exc); // Due to 20 second expiration, the tokens in the manager // may not match what is in the tokendata. List l = this.tokenManager.getTokens(); for (Iterator i = l.iterator(); i.hasNext();) { TokenData data = (TokenData) i.next(); this.log.debug("Token: " + data.getToken() + ":" + data.getCreateTime() + ":" + (data.isLocked() ? "locked" : "pending")); } try { res.readCommand(); res.sendErrorResponse("Unauthorized"); } catch (AgentConnectionException iExc) { log.debug(iExc, iExc); } catch (EOFException e) { log.debug(e, e); } throw new AgentConnectionException("Client from " + remoteAddr + " unauthorized"); } if (!token.isLocked()) { try { this.log.info("Locking auth token"); this.tokenManager.setTokenLocked(token, true); doSave = true; } catch (TokenNotFoundException exc) { // This should never occur this.log.error("Error setting token '" + token + "' to " + "locked state -- it no longer exists"); } } // If set the token, re-store the data. if (doSave) { try { this.tokenManager.store(); } catch (IOException exc) { this.log.error("Error storing token data: " + exc.getMessage()); } } this.log.debug("Done connecting SSL"); return res; }
From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java
public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) { throw new NullPointerException("host to verify is null"); }/*from w ww . j av a2 s . c om*/ SSLSession session = ssl.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 = ssl.getInputStream(); in.available(); /* If you're looking at the 2 lines of code above because you're running into a problem, you probably have two options: #1. Clean up the certificate chain that your server is presenting (e.g. edit "/etc/apache2/server.crt" or wherever it is your server's certificate chain is defined). OR #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); }
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 {/* w w w. ja v a 2 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; } }
From source file:com.isecpartners.gizmo.HttpRequest.java
private boolean handle_connect_protocol() { try {//ww w . j a v a 2s .c om isSSL = true; /* if (Configuration.getConfiguration().useProxy()) { outboundSock = new Socket(Configuration.getConfiguration().proxyHost(), Configuration.getConfiguration().proxyPort()); out = outboundSock.getOutputStream(); out.write(workingContents.toString().getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(outboundSock.getInputStream())); in.readLine(); while (in.ready()) { in.readLine(); } }*/ host = getHostFromHeader(mk_header(workingContents)); port = getPortFromHeader(mk_header(workingContents)); if (this.sock.isClosed()) { return false; } this.sock.getOutputStream().write("HTTP/1.0 200 Connection established\r\n\r\n".getBytes()); if (!GizmoView.getView().config().terminateSSL()) { return false; } SSLSocket sslSock = negotiateSSL(this.sock, host); if (!cached) { workingContents = readMessage(sslSock.getInputStream()); this.header = mk_header(workingContents); removeLine("accept-encoding", workingContents); } this.sock = sslSock; } catch (NoCertException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (KeyManagementException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (KeyStoreException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (CertificateException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (UnrecoverableKeyException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (InvalidKeyException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (SignatureException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchProviderException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } this.connect_protocol_handled = true; return true; }
From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {//ww w. ja 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) { } } */ 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:net.jmhertlein.mcanalytics.console.gui.LoginPane.java
@FXML public void onLoginButtonPressed(ActionEvent event) { HostEntry selected = hostList.getSelectionModel().getSelectedItem(); if (selected == null) return;//from w ww. j av a 2s . co m try { SSLContext ctx = SSLUtil.buildClientContext(trust); SSLSocket raw = (SSLSocket) ctx.getSocketFactory().createSocket(selected.getUrl(), selected.getPort()); raw.setWantClientAuth(true); try { System.out.println("Starting handshake..."); raw.startHandshake(); } catch (SSLException ssle) { if (ssle.getCause() instanceof UntrustedCertificateException) { System.out.println("Got the correct exception"); UntrustedCertificateException uce = (UntrustedCertificateException) ssle.getCause(); CertTrustPromptDialog dlg = new CertTrustPromptDialog(trust, (X509Certificate) uce.getChain()[0]); dlg.showAndWait(); System.out.println("DIALOG RETURNED"); } return; } PrintWriter out = new PrintWriter(raw.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(raw.getInputStream())); APISocket sock = new APISocket(out, in); app.setAPISocket(sock); sock.startListener(); //handle authentication boolean hasCert = false; FutureRequest<AuthenticationResult> login; if (trust.isCertificateEntry(selected.getUrl())) { try { ((X509Certificate) trust.getCertificate(selected.getUrl())).checkValidity(); hasCert = true; } catch (CertificateExpiredException | CertificateNotYetValidException ex) { Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Has cert: " + hasCert); KeyPair newPair = null; String username; if (hasCert) { username = SSLUtil.getCNs((X509Certificate) trust.getCertificate(selected.getUrl())).iterator() .next(); login = sock.submit(new AuthenticationRequest(username)); System.out.println("Logging in w/ cert. CN: " + username + ", URL: " + selected.getUrl()); } else if (rememberLoginBox.isSelected()) { newPair = SSLUtil.newECDSAKeyPair(); username = usernameField.getText(); PKCS10CertificationRequest csr = SSLUtil.newCertificateRequest( SSLUtil.newX500Name(username, selected.getUrl(), "mcanalytics"), newPair); login = sock .submit(new AuthenticationRequest(usernameField.getText(), passwordField.getText(), csr)); System.out.println("Logging in with: " + usernameField.getText() + " + " + passwordField.getText() + " and requesting a cert."); } else { username = usernameField.getText(); login = sock.submit(new AuthenticationRequest(username, passwordField.getText())); System.out.println("Logging in with: " + username + " + " + passwordField.getText()); } try { boolean success = login.get().getSuccess(); if (success) { System.out.println("Login successful"); if (login.get().hasCertificate()) { trust.setCertificateEntry(selected.getUrl(), login.get().getCert()); trust.setKeyEntry(selected.getUrl() + "-private", newPair.getPrivate(), new char[0], new Certificate[] { login.get().getCert(), login.get().getCA() }); System.out.println("Stored a trusted cert from server."); } } else { System.out.println("Login failed."); Dialog dlg = new Dialog(); dlg.setTitle("Login Failed"); dlg.setContentText("Could not login- invalid login credentials."); dlg.showAndWait(); return; } } catch (InterruptedException | ExecutionException | KeyStoreException ex) { Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex); Dialogs.showMessage("Connection Error", "Connection Error", ex.getMessage(), ex.toString()); System.out.println("Login error."); return; } //auth done Stage window = (Stage) loginButton.getScene().getWindow(); window.setScene(new Scene(new ChartPane(username, sock))); window.show(); } catch (IOException | KeyStoreException ex) { Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex); Dialog dlg = new Dialog(); dlg.setTitle("Connection Error"); dlg.setContentText(ex.getMessage()); dlg.showAndWait(); System.out.println("Login error."); return; } }