Java Code Examples for javax.net.ssl.HostnameVerifier#verify()

The following examples show how to use javax.net.ssl.HostnameVerifier#verify() . 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: OkHttpTlsUpgrader.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: OkHttpTlsUpgrader.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Upgrades given Socket to be an 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;
}
 
Example 3
Source File: AbstractRestClient.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(String hostname, SSLSession session) {
    if (!this.url.isEmpty() && this.url.endsWith(hostname)) {
        return true;
    } else {
        HostnameVerifier verifier = HttpsURLConnection
                                    .getDefaultHostnameVerifier();
        return verifier.verify(hostname, session);
    }
}
 
Example 4
Source File: HttpsClientConfiguration.java    From pulsar-manager with Apache License 2.0 5 votes vote down vote up
@Bean
public CloseableHttpClient httpClient() throws Exception {
    if (tlsEnabled) {
        Resource resource = new FileSystemResource(tlsKeystore);
        File trustStoreFile = resource.getFile();
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStoreFile, tlsKeystorePassword.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = (s, sslSession) -> {
            // Custom logic to verify host name, tlsHostnameVerifier is false for test
            if (!tlsHostnameVerifier) {
                return true;
            } else {
                HostnameVerifier hv= HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify(s, sslSession);
            }
        };

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                hostnameVerifier);

        return HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
    }
    return HttpClients.custom().build();
}
 
Example 5
Source File: HttpsUtils.java    From af-pay with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verify(String hostname, SSLSession session) {
    System.out.println("verify " + hostname);
    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
    return hv.verify(hostname, session);
}
 
Example 6
Source File: HttpsUtils.java    From AndroidModulePattern with Apache License 2.0 5 votes vote down vote up
/**
 * 主机名校验方法,请把”192.168.0.10”换成你们公司的主机IP:
 */
public static HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if ("192.168.0.10".equals(hostname)) {
                return true;
            } else {
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify(hostname, session);
            }
        }
    };
}
 
Example 7
Source File: MutualSSLClient.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify(hostname, session);
        }
    };
}
 
Example 8
Source File: OAuthSSLClient.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify(hostname, session);
        }
    };
}
 
Example 9
Source File: MutualSSLClient.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify(hostname, session);
        }
    };
}
 
Example 10
Source File: OAuthSSLClient.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify(hostname, session);
        }
    };
}
 
Example 11
Source File: AsyncHTTPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected HttpsURLConnectionInfo getHttpsURLConnectionInfo() throws IOException {
    if ("http".equals(outMessage.get("http.scheme"))) {
        return null;
    }
    connect(true);
    synchronized (sessionLock) {
        if (session == null) {
            try {
                sessionLock.wait(csPolicy.getConnectionTimeout());
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
        }
        if (session == null) {
            throw new IOException("No SSLSession detected");
        }
    }
    HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils
        .getHostnameVerifier(tlsClientParameters);
    if (!verifier.verify(url.getHost(), session)) {
        throw new IOException("Could not verify host " + url.getHost());
    }

    String method = (String)outMessage.get(Message.HTTP_REQUEST_METHOD);
    String cipherSuite = null;
    Certificate[] localCerts = null;
    Principal principal = null;
    Certificate[] serverCerts = null;
    Principal peer = null;
    if (session != null) {
        cipherSuite = session.getCipherSuite();
        localCerts = session.getLocalCertificates();
        principal = session.getLocalPrincipal();
        serverCerts = session.getPeerCertificates();
        peer = session.getPeerPrincipal();
    }

    return new HttpsURLConnectionInfo(url, method, cipherSuite, localCerts, principal, serverCerts, peer);
}
 
Example 12
Source File: NettyHttpConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpsURLConnectionInfo getHttpsURLConnectionInfo() throws IOException {
    if ("http".equals(outMessage.get("http.scheme"))) {
        return null;
    }
    connect(true);

    HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils
        .getHostnameVerifier(findTLSClientParameters());

    if (!verifier.verify(url.getHost(), session)) {
        throw new IOException("Could not verify host " + url.getHost());
    }

    String method = (String)outMessage.get(Message.HTTP_REQUEST_METHOD);
    String cipherSuite = null;
    Certificate[] localCerts = null;
    Principal principal = null;
    Certificate[] serverCerts = null;
    Principal peer = null;
    if (session != null) {
        cipherSuite = session.getCipherSuite();
        localCerts = session.getLocalCertificates();
        principal = session.getLocalPrincipal();
        serverCerts = session.getPeerCertificates();
        peer = session.getPeerPrincipal();
    }

    return new HttpsURLConnectionInfo(url, method, cipherSuite, localCerts, principal, serverCerts, peer);
}
 
Example 13
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occurred while securing the connection.
 * @throws IOException if an I/O error occurred.
 * @throws SecurityNotPossibleException if TLS is not possible.
 * @throws CertificateException if there is an issue with the certificate.
 */
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws IOException, SecurityNotPossibleException, CertificateException {
    SmackTlsContext smackTlsContext = getSmackTlsContext();

    Socket plain = socket;
    // Secure the plain connection
    socket = smackTlsContext.sslContext.getSocketFactory().createSocket(plain,
            config.getXMPPServiceDomain().toString(), plain.getPort(), true);

    final SSLSocket sslSocket = (SSLSocket) socket;
    // Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
    // important (at least on certain platforms) and it seems to be a good idea anyways to
    // prevent an accidental implicit handshake.
    TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());

    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();

    // Proceed to do the handshake
    sslSocket.startHandshake();

    if (smackTlsContext.daneVerifier != null) {
        smackTlsContext.daneVerifier.finish(sslSocket.getSession());
    }

    final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
    if (verifier == null) {
            throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
    }

    final String verifierHostname;
    {
        DnsName xmppServiceDomainDnsName = getConfiguration().getXmppServiceDomainAsDnsNameIfPossible();
        // Try to convert the XMPP service domain, which potentially includes Unicode characters, into ASCII
        // Compatible Encoding (ACE) to match RFC3280 dNSname IA5String constraint.
        // See also: https://bugzilla.mozilla.org/show_bug.cgi?id=280839#c1
        if (xmppServiceDomainDnsName != null) {
            verifierHostname = xmppServiceDomainDnsName.ace;
        }
        else {
            LOGGER.log(Level.WARNING, "XMPP service domain name '" + getXMPPServiceDomain()
                            + "' can not be represented as DNS name. TLS X.509 certificate validiation may fail.");
            verifierHostname = getXMPPServiceDomain().toString();
        }
    }

    final boolean verificationSuccessful;
    // Verify the TLS session.
    verificationSuccessful = verifier.verify(verifierHostname, sslSocket.getSession());
    if (!verificationSuccessful) {
        throw new CertificateException(
                        "Hostname verification of certificate failed. Certificate does not authenticate "
                                        + getXMPPServiceDomain());
    }

    // Set that TLS was successful
    secureSocket = sslSocket;
}