List of usage examples for javax.net.ssl SSLSession getPeerCertificates
public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException;
From source file:org.lizardirc.beancounter.security.FingerprintingSslSocketFactory.java
private void verify(SSLSocket socket) throws SSLException { SSLSession session = socket.getSession(); Certificate cert = session.getPeerCertificates()[0]; byte[] encoded; try {/* w ww .ja v a2 s. c o m*/ encoded = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new SSLProtocolException("Invalid certificate encoding"); } boolean match = Stream.<Function<byte[], String>>of(DigestUtils::md5Hex, DigestUtils::sha1Hex, DigestUtils::sha256Hex, DigestUtils::sha512Hex).map(f -> f.apply(encoded)) .anyMatch(fingerprints::contains); if (!match) { System.err.println("Rejecting; fingerprint not matched"); throw new SSLPeerUnverifiedException("Failed to verify: certificate fingerprint mismatch"); } }
From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java
/** * Retrieves certificate chain of specified host:port using direct socket connection. * * @param host to get certificate chain from (cannot be null) * @param port of host to connect to//from www . ja v a 2 s . c o m * @return certificate chain * @throws Exception Re-thrown from accessing the remote host */ public Certificate[] retrieveCertificates(final String host, final int port) throws Exception { checkNotNull(host); log.info("Retrieving certificate from {}:{} using direct socket connection", host, port); SSLSocket socket = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null); javax.net.ssl.SSLSocketFactory sslSocketFactory = sc.getSocketFactory(); socket = (SSLSocket) sslSocketFactory.createSocket(host, port); socket.startHandshake(); SSLSession session = socket.getSession(); return session.getPeerCertificates(); } finally { if (socket != null) { socket.close(); } } }
From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java
private void connectToSSLSocket(Socket plainSocket) throws IOException { SSLSocketFactory factory = Networks.getSocketFactory(context); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); if (plainSocket != null) { socket = (SSLSocket) factory.createSocket(plainSocket, host, port, true); }// www . j av a 2s. c o m if (serverType == ServerType.SMTP) { socket.setUseClientMode(true); socket.setNeedClientAuth(true); } socket.setSoTimeout(5000); LOG.debug("Starting handshake..."); socket.startHandshake(); SSLSession session = socket.getSession(); Certificate[] servercerts = session.getPeerCertificates(); }
From source file:io.crate.operation.auth.HostBasedAuthenticationTest.java
@Test public void testHttpSSLOption() throws Exception { Map<String, String> baseConfig = new HashMap<>(); baseConfig.putAll(HBA_1);//from www .j a v a 2 s .c om baseConfig.put(HostBasedAuthentication.KEY_PROTOCOL, "http"); SSLSession sslSession = Mockito.mock(SSLSession.class); when(sslSession.getPeerCertificates()).thenReturn(new Certificate[0]); ConnectionProperties sslConnProperties = new ConnectionProperties(LOCALHOST, Protocol.HTTP, sslSession); ConnectionProperties noSslConnProperties = new ConnectionProperties(LOCALHOST, Protocol.HTTP, null); Map<String, String> sslConfig; sslConfig = ImmutableMap.<String, String>builder().putAll(baseConfig) .put(HostBasedAuthentication.SSL_OPTIONS.KEY, HostBasedAuthentication.SSL_OPTIONS.OPTIONAL.VALUE) .build(); authService.updateHbaConfig(createHbaConf(sslConfig)); assertThat(authService.getEntry("crate", noSslConnProperties), not(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), not(Optional.empty())); sslConfig = ImmutableMap.<String, String>builder().putAll(baseConfig) .put(HostBasedAuthentication.SSL_OPTIONS.KEY, HostBasedAuthentication.SSL_OPTIONS.REQUIRED.VALUE) .build(); authService.updateHbaConfig(createHbaConf(sslConfig)); assertThat(authService.getEntry("crate", noSslConnProperties), is(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), not(Optional.empty())); sslConfig = ImmutableMap.<String, String>builder().putAll(baseConfig) .put(HostBasedAuthentication.SSL_OPTIONS.KEY, HostBasedAuthentication.SSL_OPTIONS.NEVER.VALUE) .build(); authService.updateHbaConfig(createHbaConf(sslConfig)); assertThat(authService.getEntry("crate", noSslConnProperties), not(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), is(Optional.empty())); }
From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java
/** * Retrieves certificate chain of specified host:port using https protocol. * * @param host to get certificate chain from (cannot be null) * @param port of host to connect to/* w w w. j a va 2 s .c om*/ * @return certificate chain * @throws Exception Re-thrown from accessing the remote host */ public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception { checkNotNull(host); log.info("Retrieving certificate from https://{}:{}", host, port); // setup custom connection manager so we can configure SSL to trust-all SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory()) .register(HttpSchemes.HTTPS, sslSocketFactory).build(); final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); try { final AtomicReference<Certificate[]> certificates = new AtomicReference<>(); HttpClient httpClient = httpClientManager.create(new Customizer() { @Override public void customize(final HttpClientPlan plan) { // replace connection-manager with customized version needed to fetch SSL certificates plan.getClient().setConnectionManager(connectionManager); // add interceptor to grab peer-certificates plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { ManagedHttpClientConnection connection = HttpCoreContext.adapt(context) .getConnection(ManagedHttpClientConnection.class); // grab the peer-certificates from the session if (connection != null) { SSLSession session = connection.getSSLSession(); if (session != null) { certificates.set(session.getPeerCertificates()); } } } }); } }); httpClient.execute(new HttpGet("https://" + host + ":" + port)); return certificates.get(); } finally { // shutdown single-use connection manager connectionManager.shutdown(); } }
From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.DefaultHostnameVerifier.java
@Override public final boolean verify(final String host, final SSLSession session) { try {//from www. j a va 2 s . com final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch (final SSLException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } return false; } }
From source file:io.crate.auth.HostBasedAuthenticationTest.java
@Test public void testHttpSSLOption() throws Exception { Settings baseConfig = Settings.builder().put(HBA_1) .put("auth.host_based.config.1." + HostBasedAuthentication.KEY_PROTOCOL, "http").build(); SSLSession sslSession = Mockito.mock(SSLSession.class); when(sslSession.getPeerCertificates()).thenReturn(new Certificate[0]); ConnectionProperties sslConnProperties = new ConnectionProperties(LOCALHOST, Protocol.HTTP, sslSession); ConnectionProperties noSslConnProperties = new ConnectionProperties(LOCALHOST, Protocol.HTTP, null); Settings sslConfig;/*www .jav a 2 s .co m*/ HostBasedAuthentication authService; sslConfig = Settings.builder().put(baseConfig) .put("auth.host_based.config.1." + HostBasedAuthentication.SSL.KEY, HostBasedAuthentication.SSL.OPTIONAL.VALUE) .build(); authService = new HostBasedAuthentication(sslConfig, null); assertThat(authService.getEntry("crate", noSslConnProperties), not(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), not(Optional.empty())); sslConfig = Settings.builder().put(baseConfig) .put("auth.host_based.config.1." + HostBasedAuthentication.SSL.KEY, HostBasedAuthentication.SSL.REQUIRED.VALUE) .build(); authService = new HostBasedAuthentication(sslConfig, null); assertThat(authService.getEntry("crate", noSslConnProperties), is(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), not(Optional.empty())); sslConfig = Settings.builder().put(baseConfig) .put("auth.host_based.config.1." + HostBasedAuthentication.SSL.KEY, HostBasedAuthentication.SSL.NEVER.VALUE) .build(); authService = new HostBasedAuthentication(sslConfig, null); assertThat(authService.getEntry("crate", noSslConnProperties), not(Optional.empty())); assertThat(authService.getEntry("crate", sslConnProperties), is(Optional.empty())); }
From source file:org.opensaml.security.httpclient.impl.SecurityEnhancedTLSSocketFactory.java
/** * Extract the server TLS {@link X509Credential} from the supplied {@link SSLSocket}. * //from www .j a va 2 s .c om * @param sslSocket the SSL socket instance to process * @return an X509Credential representing the server TLS entity certificate as well as the * supplied supporting intermediate certificate chain (if any) * @throws IOException if credential data can not be extracted from the socket */ @Nonnull protected X509Credential extractCredential(@Nonnull final SSLSocket sslSocket) throws IOException { SSLSession session = sslSocket.getSession(); final Certificate[] peerCertificates = session.getPeerCertificates(); if (peerCertificates == null || peerCertificates.length < 1) { throw new SSLPeerUnverifiedException("SSLSession peer certificates array was null or empty"); } ArrayList<X509Certificate> certChain = new ArrayList<>(); for (Certificate cert : peerCertificates) { certChain.add((X509Certificate) cert); } final X509Certificate entityCert = certChain.get(0); BasicX509Credential credential = new BasicX509Credential(entityCert); credential.setEntityCertificateChain(certChain); return credential; }
From source file:org.dcache.ftp.client.extended.GridFTPControlChannel.java
/** * Performs authentication with specified user credentials and * a specific username (assuming the user dn maps to the passed username). * * @throws IOException on i/o error/*from w w w. j a va 2s .c o m*/ * @throws ServerException on server refusal or faulty server behavior */ private DssContext authenticate(DssContextFactory factory, String expectedHostName) throws IOException, ServerException { DssContext context; try { try { Reply reply = inner.exchange(new Command("AUTH", "GSSAPI")); if (!Reply.isPositiveIntermediate(reply)) { throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply), "Server refused GSSAPI authentication."); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe, "Received faulty reply to AUTH GSSAPI."); } context = factory.create(inner.getRemoteAddress(), inner.getLocalAddress()); Reply reply; byte[] inToken = new byte[0]; do { byte[] outToken = context.init(inToken); reply = inner.exchange(new Command("ADAT", BaseEncoding.base64().encode(outToken != null ? outToken : new byte[0]))); if (reply.getMessage().startsWith("ADAT=")) { inToken = BaseEncoding.base64().decode(reply.getMessage().substring(5)); } else { inToken = new byte[0]; } } while (Reply.isPositiveIntermediate(reply) && !context.isEstablished()); if (!Reply.isPositiveCompletion(reply)) { throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply), "Server failed GSI handshake."); } if (inToken.length > 0 || !context.isEstablished()) { byte[] outToken = context.init(inToken); if (outToken != null || !context.isEstablished()) { throw new ServerException(ServerException.WRONG_PROTOCOL, "Unexpected GSI handshake completion."); } } SSLSession session = ((SslEngineDssContext) context).getSSLSession(); if (!this.hostnameVerifier.verify(expectedHostName, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + expectedHostName + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } } catch (FTPReplyParseException e) { throw ServerException.embedFTPReplyParseException(e, "Received faulty reply to ADAT."); } return context; }
From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java
@Override public final boolean verify(final String host, final SSLSession session) { try {/*from ww w .ja v a2s . c om*/ final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch (final SSLException e) { return false; } }