Search in sources :

Example 1 with StrictHostnameVerifier

use of org.apache.http.conn.ssl.StrictHostnameVerifier in project opennms by OpenNMS.

the class SSLCertMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for HTTP service availability.
 *
 * During the poll an attempt is made to connect on the specified port. If
 * the connection request is successful, check the X509Certificates provided
 * by our peer and check that our time is between the certificates start and
 * end time.
 * Provided that the interface's response is valid we set the service status to
 * SERVICE_AVAILABLE and return.
 */
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    if (port == DEFAULT_PORT) {
        throw new RuntimeException("Required parameter 'port' is not present in supplied properties.");
    }
    // Remaining days
    int validityDays = ParameterMap.getKeyedInteger(parameters, PARAMETER_DAYS, DEFAULT_DAYS);
    if (validityDays <= 0) {
        throw new RuntimeException("Required parameter 'days' must be a positive value.");
    }
    // Server name (optional)
    final String serverName = PropertiesUtils.substitute(ParameterMap.getKeyedString(parameters, PARAMETER_SERVER_NAME, ""), getServiceProperties(svc));
    // Calculate validity range
    Calendar calValid = this.getCalendarInstance();
    Calendar calCurrent = this.getCalendarInstance();
    calValid.setTimeInMillis(calCurrent.getTimeInMillis());
    calValid.add(Calendar.DAY_OF_MONTH, validityDays);
    Calendar calBefore = this.getCalendarInstance();
    Calendar calAfter = this.getCalendarInstance();
    // Get the address instance
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address={}, port={}, serverName={}, {}", hostAddress, port, serverName, tracker);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        try {
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Connected to host: {} on port: {}", ipAddr, port);
            SSLSocket sslSocket = SocketUtils.wrapSocketInSslContext(socket, null, null);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            // Use the server name as as SNI host name if available
            if (!Strings.isNullOrEmpty(serverName)) {
                final SSLParameters sslParameters = sslSocket.getSSLParameters();
                sslParameters.setServerNames(ImmutableList.of(new SNIHostName(serverName)));
                sslSocket.setSSLParameters(sslParameters);
                // Check certificates host name
                if (!new StrictHostnameVerifier().verify(serverName, sslSocket.getSession())) {
                    serviceStatus = PollStatus.unavailable("Host name verification failed - certificate common name is invalid");
                    continue;
                }
            }
            Certificate[] certs = sslSocket.getSession().getPeerCertificates();
            for (int i = 0; i < certs.length && !serviceStatus.isAvailable(); i++) {
                if (certs[i] instanceof X509Certificate) {
                    X509Certificate certx = (X509Certificate) certs[i];
                    LOG.debug("Checking validity against dates: [current: {}, valid: {}], NotBefore: {}, NotAfter: {}", calCurrent.getTime(), calValid.getTime(), certx.getNotBefore(), certx.getNotAfter());
                    calBefore.setTime(certx.getNotBefore());
                    calAfter.setTime(certx.getNotAfter());
                    if (calCurrent.before(calBefore)) {
                        LOG.debug("Certificate is invalid, current time is before start time");
                        serviceStatus = PollStatus.unavailable("Certificate is invalid, current time is before start time");
                        break;
                    } else if (calCurrent.before(calAfter)) {
                        if (calValid.before(calAfter)) {
                            LOG.debug("Certificate is valid, and does not expire before validity check date");
                            serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
                            break;
                        } else {
                            String reason = "Certificate is valid, but will expire in " + validityDays + " days.";
                            LOG.debug(reason);
                            serviceStatus = PollStatus.unavailable(reason);
                            break;
                        }
                    } else {
                        LOG.debug("Certificate has expired.");
                        serviceStatus = PollStatus.unavailable("Certificate has expired.");
                        break;
                    }
                }
            }
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            // Break out of for(;;)
            break;
        } catch (InterruptedIOException e) {
            String reason = "did not connect to host with " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            String reason = "Connection exception for address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.fillInStackTrace();
                LOG.debug("poll: Error closing socket.", e);
            }
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PollStatus(org.opennms.netmgt.poller.PollStatus) InetSocketAddress(java.net.InetSocketAddress) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) SSLSocket(javax.net.ssl.SSLSocket) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) NoRouteToHostException(java.net.NoRouteToHostException) X509Certificate(java.security.cert.X509Certificate) SSLParameters(javax.net.ssl.SSLParameters) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SNIHostName(javax.net.ssl.SNIHostName) InetAddress(java.net.InetAddress) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) ConnectException(java.net.ConnectException)

Example 2 with StrictHostnameVerifier

use of org.apache.http.conn.ssl.StrictHostnameVerifier in project AndroidAsync by koush.

the class AsyncSSLSocketWrapper method handleHandshakeStatus.

private void handleHandshakeStatus(HandshakeStatus status) {
    if (status == HandshakeStatus.NEED_TASK) {
        final Runnable task = engine.getDelegatedTask();
        task.run();
    }
    if (status == HandshakeStatus.NEED_WRAP) {
        write(writeList);
    }
    if (status == HandshakeStatus.NEED_UNWRAP) {
        dataCallback.onDataAvailable(this, new ByteBufferList());
    }
    try {
        if (!finishedHandshake && (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING || engine.getHandshakeStatus() == HandshakeStatus.FINISHED)) {
            if (clientMode) {
                Exception peerUnverifiedCause = null;
                boolean trusted = false;
                try {
                    peerCertificates = (X509Certificate[]) engine.getSession().getPeerCertificates();
                    if (mHost != null) {
                        if (hostnameVerifier == null) {
                            StrictHostnameVerifier verifier = new StrictHostnameVerifier();
                            verifier.verify(mHost, StrictHostnameVerifier.getCNs(peerCertificates[0]), StrictHostnameVerifier.getDNSSubjectAlts(peerCertificates[0]));
                        } else {
                            if (!hostnameVerifier.verify(mHost, engine.getSession())) {
                                throw new SSLException("hostname <" + mHost + "> has been denied");
                            }
                        }
                    }
                    trusted = true;
                } catch (SSLException ex) {
                    peerUnverifiedCause = ex;
                }
                finishedHandshake = true;
                if (!trusted) {
                    AsyncSSLException e = new AsyncSSLException(peerUnverifiedCause);
                    report(e);
                    if (!e.getIgnore())
                        throw e;
                }
            } else {
                finishedHandshake = true;
            }
            handshakeCallback.onHandshakeCompleted(null, this);
            handshakeCallback = null;
            mSocket.setClosedCallback(null);
            // handshake can complete during a wrap, so make sure that the call
            // stack and wrap flag is cleared before invoking writable
            getServer().post(new Runnable() {

                @Override
                public void run() {
                    if (mWriteableCallback != null)
                        mWriteableCallback.onWriteable();
                }
            });
            onDataAvailable();
        }
    } catch (Exception ex) {
        report(ex);
    }
}
Also used : StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SSLException(javax.net.ssl.SSLException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) GeneralSecurityException(java.security.GeneralSecurityException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 3 with StrictHostnameVerifier

use of org.apache.http.conn.ssl.StrictHostnameVerifier in project Conversations by siacs.

the class HttpConnectionManager method setupTrustManager.

public void setupTrustManager(final HttpsURLConnection connection, final boolean interactive) {
    final X509TrustManager trustManager;
    final HostnameVerifier hostnameVerifier;
    if (interactive) {
        trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive();
        hostnameVerifier = mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
    } else {
        trustManager = mXmppConnectionService.getMemorizingTrustManager().getNonInteractive();
        hostnameVerifier = mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifierNonInteractive(new StrictHostnameVerifier());
    }
    try {
        final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[] { trustManager }, mXmppConnectionService.getRNG());
        connection.setSSLSocketFactory(sf);
        connection.setHostnameVerifier(hostnameVerifier);
    } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
    }
}
Also used : StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) TLSSocketFactory(eu.siacs.conversations.utils.TLSSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyManagementException(java.security.KeyManagementException) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 4 with StrictHostnameVerifier

use of org.apache.http.conn.ssl.StrictHostnameVerifier in project Pix-Art-Messenger by kriztan.

the class HttpConnectionManager method setupTrustManager.

public void setupTrustManager(final HttpsURLConnection connection, final boolean interactive) {
    final X509TrustManager trustManager;
    final HostnameVerifier hostnameVerifier = mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier(), interactive);
    if (interactive) {
        trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive();
    } else {
        trustManager = mXmppConnectionService.getMemorizingTrustManager().getNonInteractive();
    }
    try {
        final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[] { trustManager }, mXmppConnectionService.getRNG());
        connection.setSSLSocketFactory(sf);
        connection.setHostnameVerifier(hostnameVerifier);
    } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
    }
}
Also used : StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) TLSSocketFactory(de.pixart.messenger.utils.TLSSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyManagementException(java.security.KeyManagementException) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 5 with StrictHostnameVerifier

use of org.apache.http.conn.ssl.StrictHostnameVerifier in project Smack by igniterealtime.

the class AndroidSmackInitializer method initialize.

@Override
public List<Exception> initialize() {
    SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier());
    Base64.setEncoder(AndroidBase64Encoder.INSTANCE);
    Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.INSTANCE);
    return null;
}
Also used : StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier)

Aggregations

StrictHostnameVerifier (org.apache.http.conn.ssl.StrictHostnameVerifier)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 KeyManagementException (java.security.KeyManagementException)3 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)3 X509TrustManager (javax.net.ssl.X509TrustManager)3 TLSSocketFactory (eu.siacs.conversations.utils.TLSSocketFactory)2 IOException (java.io.IOException)2 X509Certificate (java.security.cert.X509Certificate)2 HostnameVerifier (javax.net.ssl.HostnameVerifier)2 TLSSocketFactory (de.pixart.messenger.utils.TLSSocketFactory)1 InterruptedIOException (java.io.InterruptedIOException)1 ConnectException (java.net.ConnectException)1 InetAddress (java.net.InetAddress)1 InetSocketAddress (java.net.InetSocketAddress)1 NoRouteToHostException (java.net.NoRouteToHostException)1 Socket (java.net.Socket)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Certificate (java.security.cert.Certificate)1 CertificateException (java.security.cert.CertificateException)1 Calendar (java.util.Calendar)1