use of javax.net.ssl.SSLParameters in project jdk8u_jdk by JetBrains.
the class SSLServerSocketImpl method getSSLParameters.
/**
* Returns the SSLParameters in effect for newly accepted connections.
*/
@Override
public synchronized SSLParameters getSSLParameters() {
SSLParameters params = super.getSSLParameters();
// the super implementation does not handle the following parameters
params.setEndpointIdentificationAlgorithm(identificationProtocol);
params.setAlgorithmConstraints(algorithmConstraints);
params.setSNIMatchers(sniMatchers);
params.setUseCipherSuitesOrder(preferLocalCipherSuites);
return params;
}
use of javax.net.ssl.SSLParameters 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.SSLParameters in project pravega by pravega.
the class ConnectionFactoryImpl method establishConnection.
@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
Preconditions.checkNotNull(location);
Exceptions.checkNotClosed(closed.get(), this);
final SslContext sslCtx;
if (clientConfig.isEnableTls()) {
try {
SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
} else {
sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
}
sslCtx = sslCtxFactory.build();
} catch (SSLException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
Bootstrap b = new Bootstrap();
b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
}
});
// Start the client.
CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
try {
b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
// since ChannelFuture is complete future.channel() is not a blocking call.
Channel ch = future.channel();
log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
// Once a channel is closed the channel group implementation removes it.
allChannels.add(ch);
connectionComplete.complete(handler);
} else {
connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
}
}
});
} catch (Exception e) {
connectionComplete.completeExceptionally(new ConnectionFailedException(e));
}
// check if channel is registered.
CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
handler.completeWhenRegistered(channelRegisteredFuture);
return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
use of javax.net.ssl.SSLParameters in project pravega by pravega.
the class ConnectionFactoryImplTest method setUp.
@Before
public void setUp() throws Exception {
// Configure SSL.
port = TestUtils.getAvailableListenPort();
final SslContext sslCtx;
if (ssl) {
try {
sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
boolean nio = false;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
try {
bossGroup = new EpollEventLoopGroup(1);
workerGroup = new EpollEventLoopGroup();
} catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
nio = true;
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler handler = sslCtx.newHandler(ch.alloc());
SSLEngine sslEngine = handler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
sslEngine.setSSLParameters(sslParameters);
p.addLast(handler);
}
}
});
// Start the server.
serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
use of javax.net.ssl.SSLParameters in project incubator-gobblin by apache.
the class R2ClientFactory method createHttpClient.
private Client createHttpClient(Config config) {
boolean isSSLEnabled = config.getBoolean(SSL_ENABLED);
SSLContext sslContext = null;
SSLParameters sslParameters = null;
if (isSSLEnabled) {
sslContext = SSLContextFactory.createInstance(config);
sslParameters = sslContext.getDefaultSSLParameters();
}
Map<String, Object> properties = new HashMap<>();
properties.put(HttpClientFactory.HTTP_SSL_CONTEXT, sslContext);
properties.put(HttpClientFactory.HTTP_SSL_PARAMS, sslParameters);
if (config.hasPath(PROPERTIES)) {
properties.putAll(toMap(config.getConfig(PROPERTIES)));
}
return new R2HttpClientProxy(new HttpClientFactory(), properties);
}
Aggregations