Java Code Examples for javax.net.ssl.SSLSession#getPeerCertificates()

The following examples show how to use javax.net.ssl.SSLSession#getPeerCertificates() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SslUtil.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
/**
 * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
 *
 * @param sslSession SSL session connected to upstream server
 * @return the X.509 certificate from the upstream server, or null if no certificate is available
 */
public static X509Certificate getServerCertificate(SSLSession sslSession) {
    Certificate[] peerCertificates;
    try {
        peerCertificates = sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        peerCertificates = null;
    }

    if (peerCertificates != null && peerCertificates.length > 0) {
        Certificate peerCertificate = peerCertificates[0];
        if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
            return (X509Certificate) peerCertificates[0];
        }
    }

    // no X.509 certificate was found for this server
    return null;
}
 
Example 2
Source File: Handshake.java    From AndroidProjects with MIT License 6 votes vote down vote up
public static Handshake get(SSLSession session) {
  String cipherSuiteString = session.getCipherSuite();
  if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null");
  CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);

  String tlsVersionString = session.getProtocol();
  if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null");
  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.<Certificate>emptyList();

  Certificate[] localCertificates = session.getLocalCertificates();
  List<Certificate> localCertificatesList = localCertificates != null
      ? Util.immutableList(localCertificates)
      : Collections.<Certificate>emptyList();

  return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList);
}
 
Example 3
Source File: SslUtil.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
 *
 * @param sslSession SSL session connected to upstream server
 * @return the X.509 certificate from the upstream server, or null if no certificate is available
 */
public static X509Certificate getServerCertificate(SSLSession sslSession) {
    Certificate[] peerCertificates;
    try {
        peerCertificates = sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        peerCertificates = null;
    }

    if (peerCertificates != null && peerCertificates.length > 0) {
        Certificate peerCertificate = peerCertificates[0];
        if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
            return (X509Certificate) peerCertificates[0];
        }
    }

    // no X.509 certificate was found for this server
    return null;
}
 
Example 4
Source File: DefaultSslInfo.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private static X509Certificate[] initCertificates(SSLSession session) {
	Certificate[] certificates;
	try {
		certificates = session.getPeerCertificates();
	}
	catch (Throwable ex) {
		return null;
	}

	List<X509Certificate> result = new ArrayList<>(certificates.length);
	for (Certificate certificate : certificates) {
		if (certificate instanceof X509Certificate) {
			result.add((X509Certificate) certificate);
		}
	}
	return (!result.isEmpty() ? result.toArray(new X509Certificate[0]) : null);
}
 
Example 5
Source File: InternalChannelz.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 */
public Tls(SSLSession session) {
  String cipherSuiteStandardName = session.getCipherSuite();
  Certificate localCert = null;
  Certificate remoteCert = null;
  Certificate[] localCerts = session.getLocalCertificates();
  if (localCerts != null) {
    localCert = localCerts[0];
  }
  try {
    Certificate[] peerCerts = session.getPeerCertificates();
    if (peerCerts != null) {
      // The javadoc of getPeerCertificate states that the peer's own certificate is the first
      // element of the list.
      remoteCert = peerCerts[0];
    }
  } catch (SSLPeerUnverifiedException e) {
    // peer cert is not available
    log.log(
        Level.FINE,
        String.format("Peer cert not available for peerHost=%s", session.getPeerHost()),
        e);
  }
  this.cipherSuiteStandardName = cipherSuiteStandardName;
  this.localCert = localCert;
  this.remoteCert = remoteCert;
}
 
Example 6
Source File: ClusterLoadBalanceAuthorizer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Set<String> getCertificateIdentities(final SSLSession sslSession) throws CertificateException, SSLPeerUnverifiedException {
    final Certificate[] certs = sslSession.getPeerCertificates();
    if (certs == null || certs.length == 0) {
        throw new SSLPeerUnverifiedException("No certificates found");
    }

    final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certs[0]);
    cert.checkValidity();

    final Set<String> identities = CertificateUtils.getSubjectAlternativeNames(cert).stream()
            .map(CertificateUtils::extractUsername)
            .collect(Collectors.toSet());

    return identities;
}
 
Example 7
Source File: SiteToSiteRestApiClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
    final HttpInetConnection conn = coreContext.getConnection(HttpInetConnection.class);
    if (!conn.isOpen()) {
        return;
    }

    final SSLSession sslSession;
    if (conn instanceof ManagedHttpClientConnection) {
        sslSession = ((ManagedHttpClientConnection) conn).getSSLSession();
    } else if (conn instanceof ManagedNHttpClientConnection) {
        sslSession = ((ManagedNHttpClientConnection) conn).getSSLSession();
    } else {
        throw new RuntimeException("Unexpected connection type was used, " + conn);
    }


    if (sslSession != null) {
        final Certificate[] certChain = sslSession.getPeerCertificates();
        if (certChain == null || certChain.length == 0) {
            throw new SSLPeerUnverifiedException("No certificates found");
        }

        try {
            final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certChain[0]);
            trustedPeerDn = cert.getSubjectDN().getName().trim();
        } catch (final CertificateException e) {
            final String msg = "Could not extract subject DN from SSL session peer certificate";
            logger.warn(msg);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
            throw new SSLPeerUnverifiedException(msg);
        }
    }
}
 
Example 8
Source File: MyTLSHostnameVerifier.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean verify(String hostname, SSLSession session) {
	try {
		Certificate[] cert = session.getPeerCertificates();
		int certs	= cert.length;
		for (int i = 0; i < certs; i++) {
			ApsSystemUtils.getLogger().trace("Reading certificate " + cert[i]);
		}
	} catch (SSLPeerUnverifiedException e) {
		return false;
	}
	return true;
}
 
Example 9
Source File: CertificateSniffingMitmManager.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
private X509Certificate getCertificateFromSession(SSLSession sslSession)
        throws SSLPeerUnverifiedException {
    Certificate[] peerCerts = sslSession.getPeerCertificates();
    Certificate peerCert = peerCerts[0];
    if (peerCert instanceof X509Certificate) {
        return (X509Certificate) peerCert;
    }
    throw new IllegalStateException(
            "Required java.security.cert.X509Certificate, found: "
                    + peerCert);
}
 
Example 10
Source File: OkHostnameVerifier.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean verify(String host, SSLSession session) {
    try {
        Certificate[] certificates = session.getPeerCertificates();
        return verify(host, (X509Certificate) certificates[0]);
    } catch (SSLException e) {
        return false;
    }
}
 
Example 11
Source File: OkHostnameVerifier.java    From styT with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(String host, SSLSession session) {
  try {
    Certificate[] certificates = session.getPeerCertificates();
    return verify(host, (X509Certificate) certificates[0]);
  } catch (SSLException e) {
    return false;
  }
}
 
Example 12
Source File: OkHostnameVerifier.java    From phonegapbootcampsite with MIT License 5 votes vote down vote up
public boolean verify(String host, SSLSession session) {
  try {
    Certificate[] certificates = session.getPeerCertificates();
    return verify(host, (X509Certificate) certificates[0]);
  } catch (SSLException e) {
    return false;
  }
}
 
Example 13
Source File: SslClientCertificateHandler.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {

    if (!(evt instanceof SslHandshakeCompletionEvent)) {
        super.userEventTriggered(ctx, evt);
        return;
    }

    final SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) evt;

    if (!sslHandshakeCompletionEvent.isSuccess()) {
        log.trace("Handshake failed", sslHandshakeCompletionEvent.cause());
        return;
    }

    final Channel channel = ctx.channel();

    try {
        final SslHandler sslHandler = (SslHandler) channel.pipeline().get(ChannelHandlerNames.SSL_HANDLER);

        final SSLSession session = sslHandler.engine().getSession();
        final Certificate[] peerCertificates = session.getPeerCertificates();
        final SslClientCertificate sslClientCertificate = new SslClientCertificateImpl(peerCertificates);
        channel.attr(ChannelAttributes.AUTH_CERTIFICATE).set(sslClientCertificate);

    } catch (final SSLPeerUnverifiedException e) {
        handleSslPeerUnverifiedException(channel, e);

    } catch (final ClassCastException e2) {
        eventLog.clientWasDisconnected(channel, "SSL handshake failed");
        channel.close();
        throw new RuntimeException("Not able to get SslHandler from pipeline", e2);
    }

    channel.pipeline().remove(this);

}
 
Example 14
Source File: InternalChannelz.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance.
 */
public Tls(SSLSession session) {
  String cipherSuiteStandardName = session.getCipherSuite();
  Certificate localCert = null;
  Certificate remoteCert = null;
  Certificate[] localCerts = session.getLocalCertificates();
  if (localCerts != null) {
    localCert = localCerts[0];
  }
  try {
    Certificate[] peerCerts = session.getPeerCertificates();
    if (peerCerts != null) {
      // The javadoc of getPeerCertificate states that the peer's own certificate is the first
      // element of the list.
      remoteCert = peerCerts[0];
    }
  } catch (SSLPeerUnverifiedException e) {
    // peer cert is not available
    log.log(
        Level.FINE,
        String.format("Peer cert not available for peerHost=%s", session.getPeerHost()),
        e);
  }
  this.cipherSuiteStandardName = cipherSuiteStandardName;
  this.localCert = localCert;
  this.remoteCert = remoteCert;
}
 
Example 15
Source File: ConfirmingHostnameVerifier.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void verify(String host, 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();
    // 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);
}
 
Example 16
Source File: XmppDomainVerifier.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean verify(String domain, String hostname, SSLSession sslSession) {
    try {
        Certificate[] chain = sslSession.getPeerCertificates();
        if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) {
            return false;
        }
        X509Certificate certificate = (X509Certificate) chain[0];
        final List<String> commonNames = getCommonNames(certificate);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isSelfSigned(certificate)) {
            if (commonNames.size() == 1 && matchDomain(domain, commonNames)) {
                Log.d(LOGTAG, "accepted CN in self signed cert as work around for " + domain);
                return true;
            }
        }
        Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
        List<String> xmppAddrs = new ArrayList<>();
        List<String> srvNames = new ArrayList<>();
        List<String> domains = new ArrayList<>();
        if (alternativeNames != null) {
            for (List<?> san : alternativeNames) {
                final Integer type = (Integer) san.get(0);
                if (type == 0) {
                    final Pair<String, String> otherName = parseOtherName((byte[]) san.get(1));
                    if (otherName != null && otherName.first != null && otherName.second != null) {
                        switch (otherName.first) {
                            case SRV_NAME:
                                srvNames.add(otherName.second.toLowerCase(Locale.US));
                                break;
                            case XMPP_ADDR:
                                xmppAddrs.add(otherName.second.toLowerCase(Locale.US));
                                break;
                            default:
                                Log.d(LOGTAG, "oid: " + otherName.first + " value: " + otherName.second);
                        }
                    }
                } else if (type == 2) {
                    final Object value = san.get(1);
                    if (value instanceof String) {
                        domains.add(((String) value).toLowerCase(Locale.US));
                    }
                }
            }
        }
        if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) {
            domains.addAll(commonNames);
        }
        Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains);
        if (hostname != null) {
            Log.d(LOGTAG, "also trying to verify hostname " + hostname);
        }
        return xmppAddrs.contains(domain)
                || srvNames.contains("_xmpp-client." + domain)
                || matchDomain(domain, domains)
                || (hostname != null && matchDomain(hostname, domains));
    } catch (Exception e) {
        return false;
    }
}
 
Example 17
Source File: SSLRequestHelper.java    From deprecated-security-ssl with Apache License 2.0 4 votes vote down vote up
public static SSLInfo getSSLInfo(final Settings settings, final Path configPath, final RestRequest request, PrincipalExtractor principalExtractor) throws SSLPeerUnverifiedException {

        if(request == null || !(request instanceof Netty4HttpRequest)) {
            return null;
        }
        
        final Netty4HttpRequest nettyHttpRequest = (Netty4HttpRequest) request;
        final SslHandler sslhandler = (SslHandler) nettyHttpRequest.getChannel().pipeline().get("ssl_http");
        
        if(sslhandler == null) {
            return null;
        }
        
        final SSLEngine engine = sslhandler.engine();
        final SSLSession session = engine.getSession();

        X509Certificate[] x509Certs = null;
        final String protocol = session.getProtocol();
        final String cipher = session.getCipherSuite();
        String principal = null;
        boolean validationFailure = false;

        if (engine.getNeedClientAuth() || engine.getWantClientAuth()) {

            try {
                final Certificate[] certs = session.getPeerCertificates();

                if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
                    x509Certs = Arrays.copyOf(certs, certs.length, X509Certificate[].class);
                    final X509Certificate[] x509CertsF = x509Certs;
                    
                    final SecurityManager sm = System.getSecurityManager();

                    if (sm != null) {
                        sm.checkPermission(new SpecialPermission());
                    }

                    validationFailure = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                        @Override
                        public Boolean run() {                        
                            return !validate(x509CertsF, settings, configPath);
                        }
                    });

                    if(validationFailure) {
                        throw new SSLPeerUnverifiedException("Unable to validate certificate (CRL)");
                    }
                    principal = principalExtractor == null?null: principalExtractor.extractPrincipal(x509Certs[0], Type.HTTP);
                } else if (engine.getNeedClientAuth()) {
                    final ElasticsearchException ex = new ElasticsearchException("No client certificates found but such are needed (Security 9).");
                    throw ex;
                }

            } catch (final SSLPeerUnverifiedException e) {
                if (engine.getNeedClientAuth() || validationFailure) {
                    throw e;
                }
            }
        }

        Certificate[] localCerts = session.getLocalCertificates();
        return new SSLInfo(x509Certs, principal, protocol, cipher, localCerts==null?null:Arrays.copyOf(localCerts, localCerts.length, X509Certificate[].class));
    }
 
Example 18
Source File: J_AbstractVerifier_V.java    From steady with Apache License 2.0 4 votes vote down vote up
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();
        /*
          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);
}
 
Example 19
Source File: SslIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doConnectionWithSslContextOverrideAndURIConfig(SSLContext clientContext, String expectedDN) throws Exception {
    TransportOptions serverSslOptions = new TransportOptions();
    serverSslOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
    serverSslOptions.setTrustStoreLocation(BROKER_JKS_TRUSTSTORE);
    serverSslOptions.setKeyStorePassword(PASSWORD);
    serverSslOptions.setTrustStorePassword(PASSWORD);
    serverSslOptions.setVerifyHost(false);

    SSLContext serverContext = TransportSupport.createJdkSslContext(serverSslOptions);

    try (TestAmqpPeer testPeer = new TestAmqpPeer(serverContext, true);) {
        String connOptions = "?transport.keyStoreLocation=" + CLIENT_JKS_KEYSTORE + "&" +
                "transport.keyStorePassword=" + PASSWORD + "&" +
                "transport.trustStoreLocation=" + CLIENT_JKS_TRUSTSTORE + "&" +
                "transport.trustStorePassword=" + PASSWORD;

        JmsConnectionFactory factory = new JmsConnectionFactory("amqps://localhost:" + testPeer.getServerPort() + connOptions);
        factory.setSslContext(clientContext);

        testPeer.expectSaslPlain("guest", "guest");
        testPeer.expectOpen();
        testPeer.expectBegin();

        Connection connection = factory.createConnection("guest", "guest");
        connection.start();

        Socket socket = testPeer.getClientSocket();
        assertTrue(socket instanceof SSLSocket);
        SSLSession session = ((SSLSocket) socket).getSession();

        Certificate[] peerCertificates = session.getPeerCertificates();
        assertNotNull(peerCertificates);

        Certificate cert = peerCertificates[0];
        assertTrue(cert instanceof X509Certificate);
        String dn = ((X509Certificate)cert).getSubjectX500Principal().getName();
        assertEquals("Unexpected certificate DN", expectedDN, dn);

        testPeer.expectClose();
        connection.close();
    }
}
 
Example 20
Source File: AbstractVerifierDef.java    From steady with Apache License 2.0 4 votes vote down vote up
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();
        /*
          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);
}