下面列出了怎么用javax.net.ssl.SSLPeerUnverifiedException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Upgrades given Socket to be a SSLSocket.
*
* @throws IOException if an IO error was encountered during the upgrade handshake.
* @throws RuntimeException if the upgrade negotiation failed.
*/
public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory,
HostnameVerifier hostnameVerifier, Socket socket, String host, int port,
ConnectionSpec spec) throws IOException {
Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory");
Preconditions.checkNotNull(socket, "socket");
Preconditions.checkNotNull(spec, "spec");
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
socket, host, port, true /* auto close */);
spec.apply(sslSocket, false);
String negotiatedProtocol = OkHttpProtocolNegotiator.get().negotiate(
sslSocket, host, spec.supportsTlsExtensions() ? TLS_PROTOCOLS : null);
Preconditions.checkState(
TLS_PROTOCOLS.contains(Protocol.get(negotiatedProtocol)),
"Only " + TLS_PROTOCOLS + " are supported, but negotiated protocol is %s",
negotiatedProtocol);
if (hostnameVerifier == null) {
hostnameVerifier = OkHostnameVerifier.INSTANCE;
}
if (!hostnameVerifier.verify(canonicalizeHost(host), sslSocket.getSession())) {
throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
}
return sslSocket;
}
/** Helper for asserting TLS info in SSLSession {@link io.grpc.ServerCall#getAttributes()} */
protected void assertX500SubjectDn(String tlsInfo) {
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(5, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
List<Certificate> certificates;
SSLSession sslSession =
serverCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
try {
certificates = Arrays.asList(sslSession.getPeerCertificates());
} catch (SSLPeerUnverifiedException e) {
// Should never happen
throw new AssertionError(e);
}
X509Certificate x509cert = (X509Certificate) certificates.get(0);
assertEquals(1, certificates.size());
assertEquals(tlsInfo, x509cert.getSubjectDN().toString());
}
@Test
public void wrongHostNameFailHostnameVerification() throws Exception {
ManagedChannel channel = createChannelBuilder()
.overrideAuthority(GrpcUtil.authorityFromHostAndPort(
BAD_HOSTNAME, getPort()))
.build();
TestServiceGrpc.TestServiceBlockingStub blockingStub =
TestServiceGrpc.newBlockingStub(channel);
Throwable actualThrown = null;
try {
blockingStub.emptyCall(Empty.getDefaultInstance());
} catch (Throwable t) {
actualThrown = t;
}
assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
Throwable cause = Throwables.getRootCause(actualThrown);
assertTrue(
"Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
channel.shutdown();
}
/**
* Return the cert chain presented by the peer in the
* java.security.cert format.
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return array of peer X.509 certs, with the peer's own cert
* first in the chain, and with the "root" CA last.
*/
@Override
public java.security.cert.Certificate[] getPeerCertificates()
throws SSLPeerUnverifiedException {
//
// clone to preserve integrity of session ... caller can't
// change record of peer identity even by accident, much
// less do it intentionally.
//
if ((cipherSuite.keyExchange == K_KRB5) ||
(cipherSuite.keyExchange == K_KRB5_EXPORT)) {
throw new SSLPeerUnverifiedException("no certificates expected"
+ " for Kerberos cipher suites");
}
if (peerCerts == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
}
// Certs are immutable objects, therefore we don't clone them.
// But do need to clone the array, so that nothing is inserted
// into peerCerts.
return (java.security.cert.Certificate[])peerCerts.clone();
}
@Override
public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException, RenegotiationRequiredException {
if (unverified != null) {
throw unverified;
}
if (renegotiationRequiredException != null) {
throw renegotiationRequiredException;
}
try {
return session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
// try {
// SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE);
// if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) {
// renegotiationRequiredException = RENEGOTIATION_REQUIRED_EXCEPTION;
// throw renegotiationRequiredException;
// }
// } catch (IOException e1) {
// //ignore, will not actually happen
// }
unverified = PEER_UNVERIFIED_EXCEPTION;
throw unverified;
}
}
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException, RenegotiationRequiredException {
if (unverified != null) {
throw unverified;
}
if (renegotiationRequiredException != null) {
throw renegotiationRequiredException;
}
try {
return session.getPeerCertificateChain();
} catch (SSLPeerUnverifiedException e) {
// try {
// SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE);
// if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) {
// renegotiationRequiredException = RENEGOTIATION_REQUIRED_EXCEPTION;
// throw renegotiationRequiredException;
// }
// } catch (IOException e1) {
// //ignore, will not actually happen
// }
unverified = PEER_UNVERIFIED_EXCEPTION;
throw unverified;
}
}
private PublicKey fetchCertificate(ChannelHandlerContext ctx)
throws SSLPeerUnverifiedException {
SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get(SslHandler.class);
logger.info(String.valueOf(ctx.channel().pipeline().names()));
X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0];
PublicKey publicKey = cert.getPublicKey();
Principal principal = cert.getSubjectDN();
logger.info(
" algorithm: {}, format: {}, class name: {}",
publicKey.getAlgorithm(),
publicKey.getFormat(),
publicKey.getClass().getName());
logger.info(
" encoded: {}, hex encoded: {}",
publicKey.getEncoded(),
bytesToHex(publicKey.getEncoded()));
logger.info(
" principal name: {} ,principal class name: {}",
principal.getName(),
principal.getClass().getName());
return publicKey;
}
private static void matchDns(String hostname, List<San> sans) throws SSLPeerUnverifiedException {
String host = hostname.toLowerCase(Locale.ROOT);
if (host.isEmpty() || host.charAt(0) == '.' || host.endsWith("..")) {
// Invalid hostname
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' cannot match the Subject Alternative Names because it is invalid name", hostname));
}
for (San san : sans) {
if (san.getType() == San.DNS && matchHost(host, san.getValue().toLowerCase(Locale.ROOT))) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by DNS name '{}' of the Subject Alternative Names", host, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", hostname, sans));
}
/**
* Returns the server's certificate chain, or throws
* SSLPeerUnverified Exception if
* the server did not authenticate.
*/
public java.security.cert.Certificate[] getServerCertificates()
throws SSLPeerUnverifiedException {
if (cachedResponse != null) {
List<java.security.cert.Certificate> l =
((SecureCacheResponse)cachedResponse)
.getServerCertificateChain();
if (l == null) {
return null;
} else {
return l.toArray(new java.security.cert.Certificate[0]);
}
}
if (http == null) {
throw new IllegalStateException("connection not yet open");
} else {
return (((HttpsClient)http).getServerCertificates ());
}
}
private Certificate[] getPeerCertificates(HttpServerExchange exchange, SSLSessionInfo sslSession, SecurityContext securityContext)
throws SSLPeerUnverifiedException {
try {
return sslSession.getPeerCertificates();
} catch (RenegotiationRequiredException e) {
// we only renegotiate if authentication is required
if (forceRenegotiation && securityContext.isAuthenticationRequired()) {
try {
sslSession.renegotiate(exchange, SslClientAuthMode.REQUESTED);
return sslSession.getPeerCertificates();
} catch (IOException | RenegotiationRequiredException e1) {
// ignore
}
}
}
throw new SSLPeerUnverifiedException("");
}
/**
* Return the cert chain presented by the peer in the
* java.security.cert format.
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return array of peer X.509 certs, with the peer's own cert
* first in the chain, and with the "root" CA last.
*/
@Override
public java.security.cert.Certificate[] getPeerCertificates()
throws SSLPeerUnverifiedException {
//
// clone to preserve integrity of session ... caller can't
// change record of peer identity even by accident, much
// less do it intentionally.
//
if ((cipherSuite.keyExchange == K_KRB5) ||
(cipherSuite.keyExchange == K_KRB5_EXPORT)) {
throw new SSLPeerUnverifiedException("no certificates expected"
+ " for Kerberos cipher suites");
}
if (peerCerts == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
}
// Certs are immutable objects, therefore we don't clone them.
// But do need to clone the array, so that nothing is inserted
// into peerCerts.
return (java.security.cert.Certificate[])peerCerts.clone();
}
private static void matchDns(String hostname, List<San> sans) throws SSLPeerUnverifiedException {
String host = hostname.toLowerCase(Locale.ROOT);
if (host.isEmpty() || host.charAt(0) == '.' || host.endsWith("..")) {
// Invalid hostname
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' cannot match the Subject Alternative Names because it is invalid name", hostname));
}
for (San san : sans) {
if (san.getType() == San.DNS && matchHost(host, san.getValue().toLowerCase(Locale.ROOT))) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by DNS name '{}' of the Subject Alternative Names", host, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", hostname, sans));
}
/**
* Returns the identity of the peer which was established as part of
* defining the session.
*
* @return the peer's principal. Returns an X500Principal of the
* end-entity certificate for X509-based cipher suites, and
* Principal for Kerberos cipher suites.
*
* @throws SSLPeerUnverifiedException if the peer's identity has not
* been verified
*/
@Override
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException
{
if ((cipherSuite.keyExchange == K_KRB5) ||
(cipherSuite.keyExchange == K_KRB5_EXPORT)) {
if (peerPrincipal == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
} else {
// Eliminate dependency on KerberosPrincipal
return peerPrincipal;
}
}
if (peerCerts == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
}
return peerCerts[0].getSubjectX500Principal();
}
/**
* Returns the server's certificate chain, or throws
* SSLPeerUnverified Exception if
* the server did not authenticate.
*/
public java.security.cert.Certificate[] getServerCertificates()
throws SSLPeerUnverifiedException {
if (cachedResponse != null) {
List<java.security.cert.Certificate> l = ((SecureCacheResponse)cachedResponse).getServerCertificateChain();
if (l == null) {
return null;
} else {
return l.toArray(new java.security.cert.Certificate[0]);
}
}
if (http == null) {
throw new IllegalStateException("connection not yet open");
} else {
return (((HttpsClient)http).getServerCertificates ());
}
}
protected void checkRequest(final RestRequest request, final RestChannel channel) {
if(SSLRequestHelper.containsBadHeader(threadContext, "_opendistro_security_ssl_")) {
final ElasticsearchException exception = ExceptionUtils.createBadHeaderException();
errorHandler.logError(exception, request, 1);
throw exception;
}
try {
if(SSLRequestHelper.getSSLInfo(settings, configPath, request, null) == null) {
logger.error("Not an SSL request");
throw new ElasticsearchSecurityException("Not an SSL request", RestStatus.INTERNAL_SERVER_ERROR);
}
} catch (SSLPeerUnverifiedException e) {
logger.error("No client certificates found but such are needed (Security 8).");
errorHandler.logError(e, request, 0);
throw ExceptionsHelper.convertToElastic(e);
}
}
/**
* Return the cert chain presented by the peer.
* Note: This method can be used only when using certificate-based
* cipher suites; using it with non-certificate-based cipher suites,
* such as Kerberos, will throw an SSLPeerUnverifiedException.
*
* @return array of peer X.509 certs, with the peer's own cert
* first in the chain, and with the "root" CA last.
*/
public X509Certificate[] getCertificateChain()
throws SSLPeerUnverifiedException {
/*
* clone to preserve integrity of session ... caller can't
* change record of peer identity even by accident, much
* less do it intentionally.
*/
if ((cipherSuite.keyExchange == K_KRB5) ||
(cipherSuite.keyExchange == K_KRB5_EXPORT)) {
throw new SSLPeerUnverifiedException("no certificates expected"
+ " for Kerberos cipher suites");
}
if (peerCerts != null) {
return peerCerts.clone();
} else {
throw new SSLPeerUnverifiedException("peer not authenticated");
}
}
/**
* Returns the identity of the peer which was established as part of
* defining the session.
*
* @return the peer's principal. Returns an X500Principal of the
* end-entity certificate for X509-based cipher suites, and
* Principal for Kerberos cipher suites.
*
* @throws SSLPeerUnverifiedException if the peer's identity has not
* been verified
*/
@Override
public Principal getPeerPrincipal()
throws SSLPeerUnverifiedException
{
if ((cipherSuite.keyExchange == K_KRB5) ||
(cipherSuite.keyExchange == K_KRB5_EXPORT)) {
if (peerPrincipal == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
} else {
// Eliminate dependency on KerberosPrincipal
return peerPrincipal;
}
}
if (peerCerts == null) {
throw new SSLPeerUnverifiedException("peer not authenticated");
}
return peerCerts[0].getSubjectX500Principal();
}
/**
* Returns the server's certificate chain, or throws
* SSLPeerUnverified Exception if
* the server did not authenticate.
*/
public java.security.cert.Certificate[] getServerCertificates()
throws SSLPeerUnverifiedException {
if (cachedResponse != null) {
List<java.security.cert.Certificate> l = ((SecureCacheResponse)cachedResponse).getServerCertificateChain();
if (l == null) {
return null;
} else {
return l.toArray(new java.security.cert.Certificate[0]);
}
}
if (http == null) {
throw new IllegalStateException("connection not yet open");
} else {
return (((HttpsClient)http).getServerCertificates ());
}
}
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager) {
HttpServerRequest request = context.request();
if (!request.isSSL()) {
return Uni.createFrom().nullItem();
}
Certificate certificate;
try {
certificate = request.sslSession().getPeerCertificates()[0];
} catch (SSLPeerUnverifiedException e) {
return Uni.createFrom().nullItem();
}
return identityProviderManager
.authenticate(new CertificateAuthenticationRequest(
new CertificateCredential(X509Certificate.class.cast(certificate))));
}
/**
* 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;
}
@Deprecated
@Override
public javax.security.cert.X509Certificate[] getPeerCertificateChain()
throws SSLPeerUnverifiedException {
// these are lazy created to reduce memory overhead
javax.security.cert.X509Certificate[] c = x509PeerCerts;
if (c == null) {
byte[][] chain;
synchronized (OpenSSLEngine.this) {
if (destroyed || SSL.isInInit(ssl) != 0) {
throw new SSLPeerUnverifiedException(sm.getString("engine.unverifiedPeer"));
}
chain = SSL.getPeerCertChain(ssl);
}
if (chain == null) {
throw new SSLPeerUnverifiedException(sm.getString("engine.unverifiedPeer"));
}
javax.security.cert.X509Certificate[] peerCerts =
new javax.security.cert.X509Certificate[chain.length];
for (int i = 0; i < peerCerts.length; i++) {
try {
peerCerts[i] = javax.security.cert.X509Certificate.getInstance(chain[i]);
} catch (javax.security.cert.CertificateException e) {
throw new IllegalStateException(e);
}
}
c = x509PeerCerts = peerCerts;
}
return c;
}
@Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
Certificate[] peer = getPeerCertificates();
if (peer == null || peer.length == 0) {
return null;
}
return principal(peer);
}
@Test
public void testPemHostnameVerificationFailure() throws Exception {
try (TestServer testServer = new TestServer("sslConfigurator/pem/truststore.jks",
"sslConfigurator/pem/node-wrong-hostname-keystore.jks", "secret", false)) {
Path rootCaPemPath = FileHelper.getAbsoluteFilePathFromClassPath("sslConfigurator/pem/root-ca.pem");
Settings settings = Settings.builder()
.put("prefix.pemtrustedcas_filepath", rootCaPemPath.getFileName().toString())
.put("prefix.enable_ssl", "true").put("prefix.verify_hostnames", "true")
.put("path.home", rootCaPemPath.getParent().toString()).build();
Path configPath = rootCaPemPath.getParent();
SettingsBasedSSLConfigurator sbsc = new SettingsBasedSSLConfigurator(settings, configPath, "prefix");
SSLConfig sslConfig = sbsc.buildSSLConfig();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory()).build()) {
thrown.expect(SSLPeerUnverifiedException.class);
try (CloseableHttpResponse response = httpClient.execute(new HttpGet(testServer.getUri()))) {
Assert.fail("Connection should have failed due to wrong hostname");
}
}
}
}
private X509Certificate getCertificateFromSession(SSLSession sslSession)
throws SSLPeerUnverifiedException {
Certificate[] peerCerts = sslSession.getPeerCertificates();
Certificate peerCert = peerCerts[0];
if (peerCert instanceof java.security.cert.X509Certificate) {
return (java.security.cert.X509Certificate) peerCert;
}
throw new IllegalStateException(
"Required java.security.cert.X509Certificate, found: "
+ peerCert);
}
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
SSLSessionInfo sslSession = exchange.getSslSessionInfo();
if (sslSession != null) {
try {
Certificate[] clientCerts = getPeerCertificates(exchange, sslSession, securityContext);
if (clientCerts[0] instanceof X509Certificate) {
Credential credential = new X509CertificateCredential((X509Certificate) clientCerts[0]);
IdentityManager idm = getIdentityManager(securityContext);
Account account = idm.verify(credential);
if (account != null) {
securityContext.authenticationComplete(account, name, false);
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
}
} catch (SSLPeerUnverifiedException e) {
// No action - this mechanism can not attempt authentication without peer certificates so allow it to drop out
// to NOT_ATTEMPTED.
}
}
/*
* For ClientCert we do not have a concept of a failed authentication, if the client did use a key then it was deemed
* acceptable for the connection to be established, this mechanism then just 'attempts' to use it for authentication but
* does not mandate success.
*/
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
@Override
public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
if (certificate == null) {
throw UndertowMessages.MESSAGES.peerUnverified();
}
return peerCertificate;
}
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
if (certificate == null) {
throw UndertowMessages.MESSAGES.peerUnverified();
}
return certificate;
}
/**
* get peer ip, port from channel connect context
*
* @param context
* @return
* @throws SSLPeerUnverifiedException
*/
public Node channelContext2Node(ChannelHandlerContext context)
throws SSLPeerUnverifiedException {
if (null == context) {
return null;
}
String nodeID = bytesToHex(fetchCertificate(context).getEncoded()).substring(48);
String host =
((SocketChannel) context.channel()).remoteAddress().getAddress().getHostAddress();
Integer port = ((SocketChannel) context.channel()).remoteAddress().getPort();
return new Node(nodeID, host, port);
}
public void onConnect(ChannelHandlerContext ctx, boolean connectToServer)
throws SSLPeerUnverifiedException {
Node node = channelContext2Node(ctx);
int hashCode = System.identityHashCode(ctx);
// set nodeID to channel attribute map
ctx.channel().attr(AttributeKey.valueOf("node")).set(node);
ctx.channel().attr(AttributeKey.valueOf("NodeID")).set(node.getNodeID());
logger.info("add new connections: {}, ctx: {}", node, hashCode);
getConnections().addChannelHandler(node, ctx, connectToServer);
logger.info(
" node {} connect success, nodeID: {}, ctx: {}",
node,
node.getNodeID(),
System.identityHashCode(ctx));
if (threadPool == null) {
callBack.onConnect(ctx, node);
} else {
try {
threadPool.execute(
new Runnable() {
@Override
public void run() {
callBack.onConnect(ctx, node);
}
});
} catch (TaskRejectedException e) {
logger.warn(" TaskRejectedException: {} ", e);
callBack.onConnect(ctx, node);
}
}
}
private static void matchIpv4(String ip, List<San> sans) throws SSLPeerUnverifiedException {
for (San san : sans) {
// IP must be case sensitive.
if (San.IP == san.getType() && ip.equals(san.getValue())) {
if (logger.isDebugEnabled()) {
logger.debug("Certificate for '{}' matched by IPv4 value '{}' of the Subject Alternative Names", ip, san.getValue());
}
return;
}
}
throw new SSLPeerUnverifiedException(String.format("Certificate for '%s' does not match any of the Subject Alternative Names: %s", ip, sans));
}