Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify InstrumentedSslConnectionSocketFactory #2094

Merged
merged 1 commit into from
Jan 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,54 +18,28 @@

import com.codahale.metrics.Timer;
import com.palantir.dialogue.hc5.DialogueClientMetrics.ConnectionConnect_Result;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.UnsafeArg;
import com.palantir.logsafe.exceptions.SafeIoException;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.http.ssl.TlsCiphers;
import org.apache.hc.core5.io.Closer;
import org.apache.hc.core5.util.Timeout;

/**
* InstrumentedSslConnectionSocketFactory is based closely on {@link SSLConnectionSocketFactory}, with two changes
* described below.
* InstrumentedSslConnectionSocketFactory extends {@link SSLConnectionSocketFactory} for a couple minor features.
* <ol>
* <li>{@link #rawSocketCreator} provided for socks proxy support.</li>
* <li>{@link #connectSocket(Socket, HttpHost, InetSocketAddress, InetSocketAddress, Timeout, Object, HttpContext)}
* <li>{@link #connectSocket(Socket, InetSocketAddress, Timeout, HttpContext)}
* overridden to add timing metrics around {@link Socket#connect(SocketAddress, int)}</li>
* </ol>
* The implementation of the connectSocket override borrows heavily from the original implementation of
* {@link SSLConnectionSocketFactory} from httpclient5-5.2.1 licensed under Apache 2.0 in order to apply
* instrumentation without interfering with behavior.
*/
final class InstrumentedSslConnectionSocketFactory extends SSLConnectionSocketFactory {
private static final SafeLogger log = SafeLoggerFactory.get(InstrumentedSslConnectionSocketFactory.class);

private final Supplier<Socket> rawSocketCreator;
private final String[] supportedProtocols;
private final String[] supportedCipherSuites;
private final String clientName;

private final Timer connectTimerSuccess;
private final Timer connectTimerFailure;
Expand All @@ -79,9 +53,6 @@ final class InstrumentedSslConnectionSocketFactory extends SSLConnectionSocketFa
HostnameVerifier hostnameVerifier,
Supplier<Socket> rawSocketCreator) {
super(socketFactory, supportedProtocols, supportedCipherSuites, hostnameVerifier);
this.supportedProtocols = supportedProtocols;
this.supportedCipherSuites = supportedCipherSuites;
this.clientName = clientName;
this.rawSocketCreator = rawSocketCreator;
this.connectTimerSuccess = dialogueClientMetrics
.connectionConnect()
Expand All @@ -101,106 +72,21 @@ public Socket createSocket(HttpContext _context) {
}

@Override
public Socket connectSocket(
Socket socket,
HttpHost host,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
Timeout connectTimeout,
Object attachment,
HttpContext context)
protected void connectSocket(
final Socket sock,
final InetSocketAddress remoteAddress,
final Timeout connectTimeout,
final HttpContext context)
throws IOException {
Preconditions.checkNotNull(host, "host is required");
Preconditions.checkNotNull(remoteAddress, "remoteAddress is required");
Socket sock = socket != null ? socket : createSocket(context);
if (localAddress != null) {
sock.bind(localAddress);
}
try {
if (log.isDebugEnabled()) {
log.debug(
"Connecting socket to {} ({}) with timeout {}",
SafeArg.of("clientName", clientName),
UnsafeArg.of("remoteAddress", remoteAddress),
SafeArg.of("connectTimeout", connectTimeout));
}
// Run this under a doPrivileged to support lib users that run under a SecurityManager this allows granting
// connect permissions only to this library
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
doConnect(
sock,
remoteAddress,
Timeout.defaultsToDisabled(connectTimeout).toMillisecondsIntBound());
return null;
});
} catch (PrivilegedActionException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException) cause;
}
throw new SafeIoException("Failed to connect", e, SafeArg.of("clientName", clientName));
}
} catch (IOException ex) {
Closer.closeQuietly(sock);
throw ex;
}
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
SSLSocket sslsock = (SSLSocket) sock;
executeHandshake(sslsock, host.getHostName(), attachment);
return sock;
}
return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), attachment, context);
}

private void doConnect(Socket sock, InetSocketAddress remoteAddress, int connectTimeoutMillis) throws IOException {
boolean success = false;
long startNanos = System.nanoTime();
try {
sock.connect(remoteAddress, connectTimeoutMillis);
super.connectSocket(sock, remoteAddress, connectTimeout, context);
success = true;
} finally {
long durationNanos = System.nanoTime() - startNanos;
Timer timer = success ? connectTimerSuccess : connectTimerFailure;
timer.update(durationNanos, TimeUnit.NANOSECONDS);
}
}

private void executeHandshake(SSLSocket sslSocket, String target, Object attachment) throws IOException {
TlsConfig tlsConfig = attachment instanceof TlsConfig ? (TlsConfig) attachment : TlsConfig.DEFAULT;
if (supportedProtocols != null) {
sslSocket.setEnabledProtocols(supportedProtocols);
} else {
sslSocket.setEnabledProtocols(TLS.excludeWeak(sslSocket.getEnabledProtocols()));
}
if (supportedCipherSuites != null) {
sslSocket.setEnabledCipherSuites(supportedCipherSuites);
} else {
sslSocket.setEnabledCipherSuites(TlsCiphers.excludeWeak(sslSocket.getEnabledCipherSuites()));
}
Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout();
if (handshakeTimeout != null) {
sslSocket.setSoTimeout(handshakeTimeout.toMillisecondsIntBound());
}

prepareSocket(sslSocket);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example of how this can be dangerous -- this prepareSocket method was deprecated in the weeks since we added this instrumented implementation in favor of an overload with an additional HttpContext context parameter. While not breaking, that sort of change can cause us to miss out on bugfixes and new feature support when we replace logic as opposed to wrapping it as this PR does.


sslSocket.startHandshake();
verifyHostname(sslSocket, target);
}

private void verifyHostname(SSLSocket sslsock, String hostname) throws IOException {
try {
SSLSession session = sslsock.getSession();
if (session == null) {
throw new SSLHandshakeException("SSL session not available");
}
verifySession(hostname, session);
} catch (IOException iox) {
// close the socket before re-throwing the exception
Closer.closeQuietly(sslsock);
throw iox;
}
}
}
Loading