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;
}
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);
}
}
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) {
}
}
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) {
}
}
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;
}
Aggregations