use of javax.net.ssl.SNIHostName in project qpid-broker-j by apache.
the class SNITest method performTest.
private void performTest(final boolean useMatching, final String defaultAlias, final String sniHostName, final KeyCertPair expectedCert) throws Exception {
if (SSLUtil.canGenerateCerts()) {
doBrokerStartup(useMatching, defaultAlias);
SSLContext context = SSLUtil.tryGetSSLContext();
context.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} }, null);
SSLSocketFactory socketFactory = context.getSocketFactory();
try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) {
SSLParameters parameters = socket.getSSLParameters();
if (sniHostName != null) {
parameters.setServerNames(Collections.singletonList(new SNIHostName(sniHostName)));
}
socket.setSSLParameters(parameters);
InetSocketAddress address = new InetSocketAddress("localhost", _boundPort);
socket.connect(address, SOCKET_TIMEOUT);
final Certificate[] certs = socket.getSession().getPeerCertificates();
assertEquals(1, certs.length);
assertEquals(expectedCert.getCertificate(), certs[0]);
}
}
}
use of javax.net.ssl.SNIHostName 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 javax.net.ssl.SNIHostName in project Bytecoder by mirkosertic.
the class HostnameChecker method matchDNS.
/**
* Check if the certificate allows use of the given DNS name.
*
* From RFC2818:
* If a subjectAltName extension of type dNSName is present, that MUST
* be used as the identity. Otherwise, the (most specific) Common Name
* field in the Subject field of the certificate MUST be used. Although
* the use of the Common Name is existing practice, it is deprecated and
* Certification Authorities are encouraged to use the dNSName instead.
*
* Matching is performed using the matching rules specified by
* [RFC5280]. If more than one identity of a given type is present in
* the certificate (e.g., more than one dNSName name, a match in any one
* of the set is considered acceptable.)
*/
private void matchDNS(String expectedName, X509Certificate cert, boolean chainsToPublicCA) throws CertificateException {
// Check that the expected name is a valid domain name.
try {
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(expectedName);
} catch (IllegalArgumentException iae) {
throw new CertificateException("Illegal given domain name: " + expectedName, iae);
}
Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();
if (subjAltNames != null) {
boolean foundDNS = false;
for (List<?> next : subjAltNames) {
if (((Integer) next.get(0)).intValue() == ALTNAME_DNS) {
foundDNS = true;
String dnsName = (String) next.get(1);
if (isMatched(expectedName, dnsName, chainsToPublicCA)) {
return;
}
}
}
if (foundDNS) {
// but none match, reject
throw new CertificateException("No subject alternative DNS " + "name matching " + expectedName + " found.");
}
}
X500Name subjectName = getSubjectX500Name(cert);
DerValue derValue = subjectName.findMostSpecificAttribute(X500Name.commonName_oid);
if (derValue != null) {
try {
if (isMatched(expectedName, derValue.getAsString(), chainsToPublicCA)) {
return;
}
} catch (IOException e) {
// ignore
}
}
String msg = "No name matching " + expectedName + " found";
throw new CertificateException(msg);
}
use of javax.net.ssl.SNIHostName in project photon-model by vmware.
the class CertificateUtil method resolveCertificate.
public static X509TrustManagerResolver resolveCertificate(URI uri, Proxy proxy, String proxyUsername, String proxyPassword, long timeoutMillis) {
logger.entering(logger.getName(), "resolveCertificate");
X509TrustManagerResolver trustManagerResolver = new X509TrustManagerResolver();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManagerResolver }, null);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.throwing(logger.getName(), "connect", e);
throw new LocalizableValidationException(e, "Failed to initialize SSL context.", "security.certificate.context.init.error");
}
String hostAddress = uri.getHost();
int port = uri.getPort() == -1 ? DEFAULT_SECURE_CONNECTION_PORT : uri.getPort();
String uriScheme = uri.getScheme();
String host = String.format("%s://%s:%d", uriScheme, hostAddress, port);
try {
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
if (proxy != null && proxy.type() == Type.HTTP && proxyUsername != null && UriUtils.HTTPS_SCHEME.equalsIgnoreCase(uriScheme)) {
URL url = uri.toURL();
handleCertForHttpsThroughHttpProxyWithAuth(url, proxy, proxyUsername, proxyPassword, timeoutMillis, sslSocketFactory);
} else {
SSLSocket sslSocket;
if (proxy != null) {
if (proxyUsername != null) {
throw new LocalizableValidationException("Proxy authentication supported " + "for HTTPS URI through HTTP Proxy only." + " URI: " + uri.toASCIIString() + ", Proxy: " + proxy.toString(), "security.certificate.proxy.authentication.not.supported.error", uri.toASCIIString(), proxy.toString());
}
Socket tunnel = new Socket(proxy);
tunnel.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
sslSocket = (SSLSocket) sslSocketFactory.createSocket(tunnel, hostAddress, port, true);
} else {
sslSocket = (SSLSocket) sslSocketFactory.createSocket();
if (SSL_CONNECT_USE_SNI) {
SNIHostName serverName = new SNIHostName(hostAddress);
List<SNIServerName> serverNames = new ArrayList<>(1);
serverNames.add(serverName);
SSLParameters params = sslSocket.getSSLParameters();
params.setServerNames(serverNames);
sslSocket.setSSLParameters(params);
}
sslSocket.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
}
SSLSession session = sslSocket.getSession();
session.invalidate();
}
} catch (IOException e) {
try {
if (trustManagerResolver.isCertsTrusted() || trustManagerResolver.getCertificateChain().length == 0) {
Utils.logWarning("Exception while resolving certificate for host: [%s]. Error: %s ", host, e.getMessage());
} else {
logger.throwing(logger.getName(), "connect", e);
throw new IllegalArgumentException(e.getMessage(), e);
}
} catch (IllegalStateException ise) {
throw new LocalizableValidationException(e, String.format("Cannot connect to host: [%s]. Error: %s", host, e.getMessage()), "security.certificate.connection.error", host, e.getMessage());
}
}
if (trustManagerResolver.getCertificateChain().length == 0) {
LocalizableValidationException e = new LocalizableValidationException("Check ssl certificate failed for server: " + host, "security.certificate.check.error", host);
logger.throwing(logger.getName(), "connect", e);
throw e;
}
logger.exiting(logger.getName(), "resolveCertificate");
return trustManagerResolver;
}
use of javax.net.ssl.SNIHostName in project netty by netty.
the class Java8SslUtils method checkSniHostnameMatch.
@SuppressWarnings("unchecked")
static boolean checkSniHostnameMatch(Collection<?> matchers, byte[] hostname) {
if (matchers != null && !matchers.isEmpty()) {
SNIHostName name = new SNIHostName(hostname);
Iterator<SNIMatcher> matcherIt = (Iterator<SNIMatcher>) matchers.iterator();
while (matcherIt.hasNext()) {
SNIMatcher matcher = matcherIt.next();
// type 0 is for hostname
if (matcher.getType() == 0 && matcher.matches(name)) {
return true;
}
}
return false;
}
return true;
}
Aggregations