fix(elasticache): terminate required TLS at cache proxies (#6227)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-24 09:31:10 -04:00
1 parent b4c71b9e25
commit 346a7f4526
25 files changed
+979 -100

No files matched your search

@@ -170,13 +170,21 @@ import software.amazon.awssdk.services.wafv2.Wafv2Client;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList;
@@ -388,6 +396,28 @@ public final class TestFixtures {
return ENDPOINT.getHost();
}
/**
* A TLS context that trusts only the CA Floci serves at {@code /_floci/ca.pem}, for a client
* that verifies an endpoint Floci signs, such as a DSQL cluster or an encrypted cache.
*/
public static SSLContext flociCaTrust() throws IOException, InterruptedException, GeneralSecurityException {
HttpResponse<String> ca = emulatorHttpClient().send(
HttpRequest.newBuilder(ENDPOINT.resolve("/_floci/ca.pem")).build(),
HttpResponse.BodyHandlers.ofString());
KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
trusted.load(null, null);
int index = 0;
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(
new ByteArrayInputStream(ca.body().getBytes(StandardCharsets.US_ASCII)))) {
trusted.setCertificateEntry("floci-" + index++, certificate);
}
TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trust.init(trusted);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trust.getTrustManagers(), null);
return context;
}
// ============================================
// Lambda dispatch availability probe
// ============================================
@@ -16,21 +16,12 @@ import software.amazon.awssdk.services.dsql.model.GetClusterResponse;
import software.amazon.awssdk.services.dsql.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dsql.model.ValidationException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
@@ -229,21 +220,7 @@ class DsqlCompatTest {
public ServerNameSocketFactory(Properties info) throws Exception {
this.serverName = info.getProperty(SERVER_NAME_PROPERTY);
HttpResponse<String> ca = TestFixtures.emulatorHttpClient().send(
HttpRequest.newBuilder(TestFixtures.endpoint().resolve("/_floci/ca.pem")).build(),
HttpResponse.BodyHandlers.ofString());
KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
trusted.load(null, null);
int index = 0;
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(
new ByteArrayInputStream(ca.body().getBytes(StandardCharsets.US_ASCII)))) {
trusted.setCertificateEntry("floci-" + index++, certificate);
}
TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trust.init(trusted);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trust.getTrustManagers(), null);
this.delegate = context.getSocketFactory();
this.delegate = TestFixtures.flociCaTrust().getSocketFactory();
}
@Override
@@ -35,6 +35,8 @@ import software.amazon.awssdk.services.elasticache.model.UserAlreadyExistsExcept
import software.amazon.awssdk.services.elasticache.model.UserGroupNotFoundException;
import software.amazon.awssdk.services.elasticache.model.UserNotFoundException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -447,9 +449,15 @@ class ElastiCacheTest {
Assumptions.assumeTrue(userCreated && userId != null, "User must exist from earlier ordered test");
}
private static Socket openSocket(int port) throws IOException {
Socket socket = new Socket(TestFixtures.proxyHost(), port);
/** The group has an auth token, so it is encrypted in transit and its endpoint takes TLS only. */
private static Socket openSocket(int port) throws Exception {
SSLSocket socket = (SSLSocket) TestFixtures.flociCaTrust().getSocketFactory()
.createSocket(TestFixtures.proxyHost(), port);
SSLParameters parameters = socket.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(parameters);
socket.setSoTimeout(5000);
socket.startHandshake();
return socket;
}
+28
View File
@@ -6,6 +6,34 @@
Floci manages real Valkey/Redis Docker containers and proxies TCP connections to them. This means any Redis client works — including IAM authentication.
## Encrypted cache connections
Redis/Valkey replication groups with transit encryption enabled take TLS at the advertised
proxy endpoint. This includes groups using an AUTH token or IAM authentication, and a group
remains encrypted when its last user group is removed. With `TransitEncryptionMode` set to
`preferred`, the endpoint takes both TLS and unencrypted connections so clients can move to
TLS; any other encrypted group takes TLS only. A modify that moves a `preferred` group to
`required` closes its open unencrypted connections, as AWS does, and its TLS connections carry
on. AWS adds new TLS endpoints while a group is `preferred`; Floci serves both kinds on the one
endpoint. Serverless Redis/Valkey endpoints take TLS only. Unencrypted caches and Memcached
retain their existing transport.
The cache listener uses a server certificate issued by Floci's shared local CA, including
the default Floci endpoint names, IPv4 and IPv6 loopback, `host.docker.internal`,
the `floci.base-url` host, and the configured Floci and cluster-announce hostnames.
The listener renews its leaf certificate a minute before it expires, never past the CA's own
expiry, while retaining the same trusted CA.
Trust `{persistent-path}/tls/floci-root-ca.crt` or the CA from `GET /_floci/ca.pem`.
The main HTTP listener's TLS setting does not disable cache transit encryption.
```bash
valkey-cli --tls --cacert ./floci-root-ca.crt -h localhost -p "$CACHE_PORT" \
--user "$CACHE_USER" --askpass PING
```
TLS terminates in Floci's cache proxy; the Docker backend hop retains its existing
transport. This does not add Memcached transit encryption or change cache-user ACL enforcement.
## Supported Management Actions
<!-- floci:actions:start -->
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
/**
* Issues the server leaf a Floci TLS listener presents, signed by Floci's CA, and says when the
* next one is due. A leaf lasts a year but never past the CA, and is due a minute before it ends,
* unless it already ends with the CA: that one cannot be extended without a new trust anchor.
*/
public final class ServerCertificateRenewal {
private static final Duration VALIDITY = Duration.ofDays(365);
private static final Duration RENEWAL_MARGIN = Duration.ofSeconds(60);
private final FlociCertificateAuthority authority;
private final CertificateGenerator generator;
private final Clock clock;
/** A listener's server context and the end of its leaf's validity. */
public record Leaf(SSLContext context, Instant notAfter) {
}
public ServerCertificateRenewal(FlociCertificateAuthority authority, CertificateGenerator generator, Clock clock) {
this.authority = authority;
this.generator = generator;
this.clock = clock;
}
/** A new leaf for {@code sans}. An expired CA signs nothing, so it fails rather than issue a dead leaf. */
public Leaf issue(List<String> sans) throws GeneralSecurityException, IOException {
Instant now = clock.instant();
X509Certificate ca = authority.certificate();
ca.checkValidity(Date.from(now));
Instant notAfter = now.plus(VALIDITY);
Instant caNotAfter = ca.getNotAfter().toInstant();
if (caNotAfter.isBefore(notAfter)) {
notAfter = caNotAfter;
}
CertificateGenerator.GeneratedCertificate generated = generator.generateIssuedCertificate(
"localhost", sans, KeyAlgorithm.RSA_2048, null, authority.issuer(),
CertificateGenerator.LeafUsage.SERVER, notAfter);
SSLContext context = authority.serverSslContext(Pem.parseCertificate(generated.certificatePem()),
Pem.parsePrivateKey(generated.privateKeyPem()));
return new Leaf(context, generated.notAfter());
}
/** True with no leaf yet, and once {@code leaf} is due. */
public boolean due(Leaf leaf) {
if (leaf == null) {
return true;
}
Instant renewAt = leaf.notAfter();
if (renewAt.isBefore(authority.certificate().getNotAfter().toInstant())) {
renewAt = renewAt.minus(RENEWAL_MARGIN);
}
return !renewAt.isAfter(clock.instant());
}
}
@@ -85,6 +85,11 @@ public class TlsConfigSource implements ConfigSource {
return List.copyOf(sans);
}
/** Default endpoint names shared by HTTP and service-specific TLS listeners. */
public static List<String> defaultEndpointHostnames() {
return DEFAULT_SAN_HOSTNAMES.stream().filter(host -> !host.contains("*")).toList();
}
private static volatile Path resolvedTlsDir;
private final Map<String, String> properties = new HashMap<>();
@@ -32,6 +32,7 @@ import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupSettings;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
import io.github.hectorvent.floci.services.elasticache.model.TransitEncryption;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheAuthProxy;
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
import io.github.hectorvent.floci.services.kms.KmsService;
@@ -1630,8 +1631,18 @@ public class ElastiCacheService implements ResourceProvider {
if (cluster.getServerlessCacheName() == null) {
proxyManager.startProxy(cluster.getCacheClusterId(), cluster.getAuthMode(),
cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),
(username, password) -> validateCacheClusterPassword(
accountId, cluster.getCacheClusterId(), username, password));
new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return validateCacheClusterPassword(accountId, cluster.getCacheClusterId(), username, password);
}
@Override
public TransitEncryption transitEncryption() {
return cluster.getAuthMode() != AuthMode.NO_AUTH
? TransitEncryption.REQUIRED : TransitEncryption.NONE;
}
});
} else {
proxyManager.startProxy(cluster.getCacheClusterId(), AuthMode.NO_AUTH,
cluster.getConfigurationEndpoint().port(), handle.getHost(), handle.getPort(),
@@ -1679,6 +1690,11 @@ public class ElastiCacheService implements ResourceProvider {
return user == null ? null : user.getAuthMode();
}
@Override
public TransitEncryption transitEncryption() {
return TransitEncryption.REQUIRED;
}
@Override
public String ownerAccountId() {
return account;
@@ -1810,6 +1826,7 @@ public class ElastiCacheService implements ResourceProvider {
}
boolean hadUserGroups = !group.getUserGroupIds().isEmpty();
boolean tookUnencrypted = group.transitEncryption() != TransitEncryption.REQUIRED;
settings.applyTo(group);
group.setUserGroupIds(nextUserGroupIds);
group.getAssociatedUserIds().addAll(directUsersToAdd);
@@ -1825,11 +1842,22 @@ public class ElastiCacheService implements ResourceProvider {
}
groups.put(groupId, group);
if (tookUnencrypted && group.transitEncryption() == TransitEncryption.REQUIRED) {
dropUnencryptedConnections(group);
}
return group;
}
}
}
/** Required transit encryption drops every unencrypted connection, the node endpoints' included. */
private void dropUnencryptedConnections(ReplicationGroup group) {
proxyManager.dropUnencryptedConnections(group.getReplicationGroupId());
for (ClusterNode node : group.getClusterNodes()) {
proxyManager.dropUnencryptedConnections(node.getMemberClusterId());
}
}
/**
* A live account takes the key as a key id, key ARN or alias and reports the key ARN on the
* group; a key it cannot use is one fault whatever the reason.
@@ -2509,6 +2537,12 @@ public class ElastiCacheService implements ResourceProvider {
return groups.getForAccount(accountId, groupId).map(ReplicationGroup::getAuthMode).orElse(null);
}
@Override
public TransitEncryption transitEncryption() {
return groups.getForAccount(accountId, groupId)
.map(ReplicationGroup::transitEncryption).orElse(TransitEncryption.REQUIRED);
}
@Override
public String ownerAccountId() {
return accountId;
@@ -110,6 +110,14 @@ public class ReplicationGroup {
return transitEncryptionEnabled != null ? transitEncryptionEnabled : authMode != AuthMode.NO_AUTH;
}
/** An encrypted group takes TLS only unless its mode is preferred, the mode clients migrate to TLS under. */
public TransitEncryption transitEncryption() {
if (!isEncryptedInTransit()) {
return TransitEncryption.NONE;
}
return "preferred".equals(transitEncryptionMode) ? TransitEncryption.PREFERRED : TransitEncryption.REQUIRED;
}
public Set<String> getAssociatedUserIds() { return associatedUserIds; }
public void setAssociatedUserIds(Set<String> associatedUserIds) {
this.associatedUserIds = associatedUserIds != null ? associatedUserIds : new HashSet<>();
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.elasticache.model;
/**
* Which connections a cache endpoint takes. {@code TransitEncryptionMode} preferred takes
* encrypted and unencrypted ones, so clients can move to TLS; required takes only TLS.
*/
public enum TransitEncryption {
NONE, PREFERRED, REQUIRED
}
@@ -62,6 +62,7 @@ public abstract class AbstractRedisAuthProxy {
private final int backendPort;
private final int handshakeTimeoutMillis;
private final Set<Socket> handshakingClients = ConcurrentHashMap.newKeySet();
private final Set<Socket> unencryptedClients = ConcurrentHashMap.newKeySet();
private volatile boolean running;
private ServerSocket serverSocket;
@@ -93,6 +94,25 @@ public abstract class AbstractRedisAuthProxy {
/** Closes a socket, tolerating errors. Implementations may add their own logging. */
protected abstract void closeQuietly(Socket socket);
/** Establishes the client transport before reading credentials. */
protected ClientTransport clientTransport(Socket client) throws IOException {
return ClientTransport.unencrypted(client);
}
/**
* The connection a client's commands arrive on: the socket to answer and close, and the stream
* to read, which replays any bytes already read to choose the transport.
*/
protected record ClientTransport(Socket socket, InputStream input, boolean encrypted) {
static ClientTransport unencrypted(Socket socket) throws IOException {
return new ClientTransport(socket, socket.getInputStream(), false);
}
static ClientTransport encrypted(Socket socket) throws IOException {
return new ClientTransport(socket, socket.getInputStream(), true);
}
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
running = true;
@@ -101,6 +121,10 @@ public abstract class AbstractRedisAuthProxy {
serviceName, resourceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
}
int localPort() {
return serverSocket.getLocalPort();
}
public void stop() {
running = false;
try {
@@ -116,6 +140,13 @@ public abstract class AbstractRedisAuthProxy {
handshakingClients.clear();
}
/** Closes every connection that is not encrypted, as AWS does once transit encryption is required. */
public void dropUnencryptedConnections() {
for (Socket client : unencryptedClients) {
closeQuietly(client);
}
}
private void acceptLoop() {
while (running) {
try {
@@ -140,7 +171,21 @@ public abstract class AbstractRedisAuthProxy {
try {
client.setTcpNoDelay(true);
client.setSoTimeout(handshakeTimeoutMillis);
RespReader reader = new RespReader(client.getInputStream());
ClientTransport transport = clientTransport(client);
if (transport.socket() != client) {
handshakingClients.add(transport.socket());
handshakingClients.remove(client);
client = transport.socket();
}
if (!transport.encrypted()) {
unencryptedClients.add(client);
}
if (!running) {
closeQuietly(client);
return;
}
InputStream input = transport.input();
RespReader reader = new RespReader(input);
while (true) {
String[] cmd = reader.readCommand();
@@ -150,17 +195,17 @@ public abstract class AbstractRedisAuthProxy {
}
if (cmd[0].equalsIgnoreCase("AUTH")) {
handleAuth(client, cmd);
handleAuth(client, input, cmd);
return;
}
if (cmd[0].equalsIgnoreCase("HELLO")) {
if (authRequired() || hasAuthOption(cmd)) {
if (handleHello(client, cmd)) {
if (handleHello(client, input, cmd)) {
return;
}
continue;
}
bridgeCommand(client, cmd);
bridgeCommand(client, input, cmd);
return;
}
if (authRequired()) {
@@ -169,7 +214,7 @@ public abstract class AbstractRedisAuthProxy {
return;
}
bridgeCommand(client, cmd);
bridgeCommand(client, input, cmd);
return;
}
} catch (Exception e) {
@@ -177,10 +222,11 @@ public abstract class AbstractRedisAuthProxy {
closeQuietly(client);
} finally {
handshakingClients.remove(client);
unencryptedClients.remove(client);
}
}
private void handleAuth(Socket client, String[] cmd) throws IOException {
private void handleAuth(Socket client, InputStream input, String[] cmd) throws IOException {
String username;
String password;
@@ -207,10 +253,10 @@ public abstract class AbstractRedisAuthProxy {
}
writeResponse(client, OK_RESPONSE);
bridgeCommand(client, null);
bridgeCommand(client, input, null);
}
private boolean handleHello(Socket client, String[] cmd) throws IOException {
private boolean handleHello(Socket client, InputStream input, String[] cmd) throws IOException {
if (cmd.length > 1) {
long protocolVersion;
try {
@@ -272,7 +318,7 @@ public abstract class AbstractRedisAuthProxy {
return false;
}
bridgeCommand(client, forwarded.toArray(String[]::new));
bridgeCommand(client, input, forwarded.toArray(String[]::new));
return true;
}
@@ -293,7 +339,7 @@ public abstract class AbstractRedisAuthProxy {
return true;
}
private void bridgeCommand(Socket client, String[] command) throws IOException {
private void bridgeCommand(Socket client, InputStream input, String[] command) throws IOException {
Socket backend = new Socket(backendHost, backendPort);
try {
backend.setTcpNoDelay(true);
@@ -302,7 +348,7 @@ public abstract class AbstractRedisAuthProxy {
}
client.setSoTimeout(0);
handshakingClients.remove(client);
bridge(client, backend);
bridge(client, input, backend);
} catch (IOException e) {
closeQuietly(backend);
throw e;
@@ -319,12 +365,13 @@ public abstract class AbstractRedisAuthProxy {
* from {@code handleConnection} blocks in {@code join} here; scheduling nested virtual-thread
* relays under load can stall delivery of backend responses (e.g. PING/PONG) to the client.
*/
private void bridge(Socket client, Socket backend) {
private void bridge(Socket client, InputStream clientInput, Socket backend) throws IOException {
InputStream backendInput = backend.getInputStream();
CountDownLatch firstRelayDone = new CountDownLatch(1);
Thread t1 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-c2b-" + resourceId)
.start(() -> {
try {
relay(client, backend);
relay(clientInput, backend);
} finally {
firstRelayDone.countDown();
}
@@ -332,7 +379,7 @@ public abstract class AbstractRedisAuthProxy {
Thread t2 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-b2c-" + resourceId)
.start(() -> {
try {
relay(backend, client);
relay(backendInput, client);
} finally {
firstRelayDone.countDown();
}
@@ -349,10 +396,9 @@ public abstract class AbstractRedisAuthProxy {
}
}
private static void relay(Socket from, Socket to) {
private static void relay(InputStream in, Socket to) {
byte[] buf = new byte[8192];
try {
InputStream in = from.getInputStream();
OutputStream out = to.getOutputStream();
int n;
while ((n = in.read(buf)) != -1) {
@@ -1,10 +1,18 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.TransitEncryption;
import org.jboss.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.net.Socket;
import java.util.function.Supplier;
/**
* TCP auth proxy for a single ElastiCache replication group.
@@ -14,21 +22,65 @@ import java.net.Socket;
public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
private static final Logger LOG = Logger.getLogger(ElastiCacheAuthProxy.class);
/** The content type of a TLS handshake record, the first byte of every ClientHello. */
private static final int TLS_HANDSHAKE_RECORD = 0x16;
private final String groupId;
private final AuthMode authMode;
private final PasswordValidator passwordValidator;
private final SigV4Validator sigV4Validator;
private final Supplier<SSLContext> tlsContext;
public ElastiCacheAuthProxy(String groupId, AuthMode authMode,
String backendHost, int backendPort,
PasswordValidator passwordValidator,
SigV4Validator sigV4Validator) {
this(groupId, authMode, backendHost, backendPort, passwordValidator, sigV4Validator, null);
}
public ElastiCacheAuthProxy(String groupId, AuthMode authMode,
String backendHost, int backendPort,
PasswordValidator passwordValidator, SigV4Validator sigV4Validator,
Supplier<SSLContext> tlsContext) {
super(LOG, "ElastiCache", "ec", groupId, backendHost, backendPort);
this.groupId = groupId;
this.authMode = authMode;
this.passwordValidator = passwordValidator;
this.sigV4Validator = sigV4Validator;
this.tlsContext = tlsContext;
}
@Override
protected ClientTransport clientTransport(Socket client) throws IOException {
TransitEncryption encryption = tlsContext == null ? TransitEncryption.NONE : passwordValidator.transitEncryption();
return switch (encryption) {
case NONE -> ClientTransport.unencrypted(client);
case REQUIRED -> ClientTransport.encrypted(handshake(tlsContext.get().getSocketFactory()
.createSocket(client, client.getInetAddress().getHostAddress(), client.getPort(), true), client));
case PREFERRED -> eitherTransport(client);
};
}
/** Both kinds are taken: a client that does not open with a TLS handshake is speaking RESP in the clear. */
private ClientTransport eitherTransport(Socket client) throws IOException {
int first = client.getInputStream().read();
if (first == -1) {
throw new EOFException("client closed the connection before sending anything");
}
InputStream consumed = new ByteArrayInputStream(new byte[]{(byte) first});
if (first != TLS_HANDSHAKE_RECORD) {
return new ClientTransport(client, new SequenceInputStream(consumed, client.getInputStream()), false);
}
return ClientTransport.encrypted(handshake(tlsContext.get().getSocketFactory()
.createSocket(client, consumed, true), client));
}
private static SSLSocket handshake(Socket layered, Socket client) throws IOException {
SSLSocket encrypted = (SSLSocket) layered;
encrypted.setUseClientMode(false);
encrypted.setSoTimeout(client.getSoTimeout());
encrypted.startHandshake();
return encrypted;
}
@Override
@@ -111,6 +163,11 @@ public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
public interface PasswordValidator {
boolean validatePassword(String username, String password);
/** Read per connection: a modify can move the cache from preferred to required while the proxy runs. */
default TransitEncryption transitEncryption() {
return TransitEncryption.NONE;
}
default boolean hasMembers() {
return false;
}
@@ -18,11 +18,13 @@ public class ElastiCacheProxyManager {
private static final Logger LOG = Logger.getLogger(ElastiCacheProxyManager.class);
private final SigV4Validator sigV4Validator;
private final ElastiCacheTlsCertificates tlsCertificates;
private final ConcurrentHashMap<String, ElastiCacheAuthProxy> proxies = new ConcurrentHashMap<>();
@Inject
public ElastiCacheProxyManager(SigV4Validator sigV4Validator) {
public ElastiCacheProxyManager(SigV4Validator sigV4Validator, ElastiCacheTlsCertificates tlsCertificates) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
}
public void startProxy(String groupId, AuthMode authMode, int proxyPort,
@@ -36,7 +38,7 @@ public class ElastiCacheProxyManager {
ElastiCacheAuthProxy.PasswordValidator passwordValidator, String authIdentity) {
ElastiCacheAuthProxy proxy = new ElastiCacheAuthProxy(
authIdentity, authMode, backendHost, backendPort,
passwordValidator, sigV4Validator);
passwordValidator, sigV4Validator, tlsCertificates::sslContext);
try {
proxy.start(proxyPort);
proxies.put(groupId, proxy);
@@ -54,6 +56,14 @@ public class ElastiCacheProxyManager {
}
}
/** Closes the proxy's unencrypted connections; its encrypted ones carry on. */
public void dropUnencryptedConnections(String groupId) {
ElastiCacheAuthProxy proxy = proxies.get(groupId);
if (proxy != null) {
proxy.dropUnencryptedConnections();
}
}
public void stopAll() {
proxies.values().forEach(ElastiCacheAuthProxy::stop);
proxies.clear();
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.config.ServerCertificateRenewal;
import io.github.hectorvent.floci.config.TlsConfigSource;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.net.ssl.SSLContext;
import java.net.URI;
import java.time.Clock;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
/** Signs the cache listener certificate with the same local CA clients trust for Floci. */
@ApplicationScoped
public class ElastiCacheTlsCertificates {
private static final Logger LOG = Logger.getLogger(ElastiCacheTlsCertificates.class);
private final ServerCertificateRenewal renewal;
private final Set<String> hosts;
private volatile ServerCertificateRenewal.Leaf leaf;
@Inject
public ElastiCacheTlsCertificates(FlociCertificateAuthority authority, EmulatorConfig config,
CertificateGenerator generator) {
this(authority, config, generator, Clock.systemUTC());
}
ElastiCacheTlsCertificates(FlociCertificateAuthority authority, EmulatorConfig config,
CertificateGenerator generator, Clock clock) {
this.renewal = new ServerCertificateRenewal(authority, generator, clock);
this.hosts = new LinkedHashSet<>(TlsConfigSource.defaultEndpointHostnames());
hosts.add("::1");
config.hostname().ifPresent(this::addHost);
config.services().elasticache().clusterAnnounceHostname().ifPresent(this::addHost);
String baseUrl = config.baseUrl();
if (baseUrl != null && !baseUrl.isBlank()) {
try {
addHost(URI.create(baseUrl).getHost());
} catch (IllegalArgumentException e) {
LOG.warnv(e, "ElastiCache TLS: could not extract a hostname from floci.base-url: {0}", baseUrl);
}
}
}
private void addHost(String host) {
if (host == null || host.isBlank()) {
return;
}
String name = host.strip();
hosts.add(name.startsWith("[") && name.endsWith("]") ? name.substring(1, name.length() - 1) : name);
}
public SSLContext sslContext() {
ServerCertificateRenewal.Leaf current = leaf;
if (renewal.due(current)) {
synchronized (this) {
if (renewal.due(leaf)) {
leaf = build();
}
current = leaf;
}
}
return current.context();
}
private ServerCertificateRenewal.Leaf build() {
try {
return renewal.issue(new ArrayList<>(hosts));
} catch (Exception e) {
LOG.errorv(e, "Failed to issue the ElastiCache endpoint certificate");
throw new IllegalStateException("Failed to issue the ElastiCache endpoint certificate", e);
}
}
}
@@ -4,9 +4,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.CertificateMetadata;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.config.FlociVersion;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.config.ServerCertificateRenewal;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -16,13 +15,8 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -47,13 +41,12 @@ public class RdsProxyTlsCertificates {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final FlociCertificateAuthority certificateAuthority;
private final CertificateGenerator certificateGenerator;
private final Clock clock;
private final ServerCertificateRenewal renewal;
private final Object lock = new Object();
private volatile ServerCertificate current;
private record ServerCertificate(SSLContext context, Set<String> sans, Instant notAfter) {
private record ServerCertificate(ServerCertificateRenewal.Leaf leaf, Set<String> sans) {
}
@Inject
@@ -64,8 +57,7 @@ public class RdsProxyTlsCertificates {
RdsProxyTlsCertificates(FlociCertificateAuthority certificateAuthority, CertificateGenerator certificateGenerator,
Clock clock) {
this.certificateAuthority = certificateAuthority;
this.certificateGenerator = certificateGenerator;
this.clock = clock;
this.renewal = new ServerCertificateRenewal(certificateAuthority, certificateGenerator, clock);
}
/**
@@ -96,7 +88,7 @@ public class RdsProxyTlsCertificates {
*/
public SSLContext sslContext() {
ensureInitialized();
return current.context();
return current.leaf().context();
}
private void ensureInitialized() {
@@ -153,22 +145,10 @@ public class RdsProxyTlsCertificates {
private void regenerate(Set<String> sans) {
try {
Path tlsDir = tlsDir();
List<String> sanList = new ArrayList<>(sans);
Instant now = clock.instant();
certificateAuthority.certificate().checkValidity(Date.from(now));
Instant notAfter = now.plus(365, ChronoUnit.DAYS);
if (certificateAuthority.certificate().getNotAfter().toInstant().isBefore(notAfter)) {
notAfter = certificateAuthority.certificate().getNotAfter().toInstant();
}
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateIssuedCertificate(
"localhost", sanList, KeyAlgorithm.RSA_2048, null, certificateAuthority.issuer(),
CertificateGenerator.LeafUsage.SERVER, notAfter);
X509Certificate certificate = Pem.parseCertificate(generated.certificatePem());
PrivateKey privateKey = Pem.parsePrivateKey(generated.privateKeyPem());
SSLContext context = certificateAuthority.serverSslContext(certificate, privateKey);
writeMetadata(tlsDir.resolve(METADATA_NAME), sanList);
current = new ServerCertificate(context, Set.copyOf(sans), generated.notAfter());
ServerCertificateRenewal.Leaf leaf = renewal.issue(sanList);
writeMetadata(tlsDir().resolve(METADATA_NAME), sanList);
current = new ServerCertificate(leaf, Set.copyOf(sans));
} catch (Exception e) {
throw new IllegalStateException("Failed to generate RDS proxy TLS certificate", e);
}
@@ -176,15 +156,7 @@ public class RdsProxyTlsCertificates {
private boolean needsRenewal() {
ServerCertificate certificate = current;
if (certificate == null) {
return true;
}
Instant renewAt = certificate.notAfter();
// A leaf capped at CA expiry cannot be extended without replacing the trust anchor.
if (renewAt.isBefore(certificateAuthority.certificate().getNotAfter().toInstant())) {
renewAt = renewAt.minusSeconds(60);
}
return !renewAt.isAfter(clock.instant());
return renewal.due(certificate == null ? null : certificate.leaf());
}
private Path tlsDir() {
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateExpiredException;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ServerCertificateRenewalTest {
@TempDir
Path directory;
@Test
void aLeafLastsAYearAndIsDueAMinuteBeforeItEnds() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
// after the CA's creation: a CA signs nothing before its own validity starts
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(now);
ServerCertificateRenewal renewal = new ServerCertificateRenewal(authority, new CertificateGenerator(), clock);
ServerCertificateRenewal.Leaf leaf = renewal.issue(List.of("localhost"));
assertEquals(now.plus(365, ChronoUnit.DAYS), leaf.notAfter());
assertTrue(renewal.due(null));
when(clock.instant()).thenReturn(leaf.notAfter().minusSeconds(61));
assertFalse(renewal.due(leaf));
when(clock.instant()).thenReturn(leaf.notAfter().minusSeconds(60));
assertTrue(renewal.due(leaf));
}
@Test
void aLeafEndsWithTheCaAndIsNotDueAgainUntilTheCaEnds() throws Exception {
CertificateGenerator.GeneratedCertificate ca = new CertificateGenerator().generateCaCertificate(
"Short-lived CA", Instant.now().plus(1, ChronoUnit.DAYS));
Files.writeString(directory.resolve(FlociCertificateAuthority.CA_CERT_NAME), ca.certificatePem());
Files.writeString(directory.resolve(FlociCertificateAuthority.CA_KEY_NAME), ca.privateKeyPem());
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
Instant caNotAfter = authority.certificate().getNotAfter().toInstant();
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(Instant.now());
ServerCertificateRenewal renewal = new ServerCertificateRenewal(authority, new CertificateGenerator(), clock);
ServerCertificateRenewal.Leaf leaf = renewal.issue(List.of("localhost"));
assertEquals(caNotAfter, leaf.notAfter());
when(clock.instant()).thenReturn(caNotAfter.minusSeconds(1));
assertFalse(renewal.due(leaf), "a new leaf could end no later, so renewing it would only churn");
when(clock.instant()).thenReturn(caNotAfter);
assertTrue(renewal.due(leaf));
when(clock.instant()).thenReturn(caNotAfter.plusSeconds(1));
assertThrows(CertificateExpiredException.class, () -> renewal.issue(List.of("localhost")));
}
}
@@ -1,9 +1,9 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.testing.TlsTrust;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Set;
@@ -14,15 +14,7 @@ final class TlsTestSupport {
private TlsTestSupport() {}
static SSLContext trustOnlyTheCa() throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci",
FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, factory.getTrustManagers(), null);
return context;
return TlsTrust.trusting(FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());
}
static Set<String> dnsSans(X509Certificate certificate) throws Exception {
@@ -859,7 +859,7 @@ class ElastiCacheIntegrationTest {
}
private static Socket openSocket(int port) throws IOException {
Socket socket = new Socket("localhost", port);
Socket socket = ElastiCacheTestConnections.openSocket("localhost", port);
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
return socket;
}
@@ -275,7 +275,7 @@ class ElastiCachePortSharingIntegrationTest {
* endpoint reaching a different group's proxy produces.
*/
private static String withAuth(int port, String token, String... command) throws IOException {
try (Socket socket = new Socket("localhost", port)) {
try (Socket socket = ElastiCacheTestConnections.openSocket("localhost", port)) {
socket.setSoTimeout(10_000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
@@ -205,7 +205,7 @@ class ElastiCacheServerlessIntegrationTest {
}
private static Socket socket(ServerlessCache cache) throws IOException {
Socket socket = new Socket(cache.endpoint().address(), cache.endpoint().port());
Socket socket = ElastiCacheTestConnections.openSocket(cache.endpoint().address(), cache.endpoint().port(), !"memcached".equals(cache.engine()));
socket.setSoTimeout(10_000);
return socket;
}
@@ -417,6 +417,21 @@ class ElastiCacheServiceTest {
assertTrue(service.getReplicationGroup("open").getUserGroupIds().isEmpty());
}
@Test
void requiredTransitEncryptionDropsTheUnencryptedConnectionsPreferredTook() {
service.createReplicationGroup("open", "test", AuthMode.NO_AUTH, null, "us-east-1");
service.modifyReplicationGroup("open", null, null,
new ReplicationGroupSettings(null, null, null, null, "preferred", true));
verify(proxyManager, never()).dropUnencryptedConnections(anyString());
service.modifyReplicationGroup("open", null, null,
new ReplicationGroupSettings(null, null, null, null, "required"));
service.modifyReplicationGroup("open", null, null, ReplicationGroupSettings.unchanged());
verify(proxyManager, times(1)).dropUnencryptedConnections("open");
}
@Test
void createReplicationGroupRejectsAnUnknownUserGroupBeforeProvisioning() {
ElastiCacheService.CreateReplicationGroupRequest request = new ElastiCacheService.CreateReplicationGroupRequest(
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.CacheCluster;
import io.github.hectorvent.floci.services.elasticache.model.ClusterNode;
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
import io.github.hectorvent.floci.testing.TlsTrust;
import jakarta.enterprise.inject.spi.CDI;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.net.Socket;
/** Real CA validation for cache data-plane tests; never uses a trust-all manager. */
public final class ElastiCacheTestConnections {
private ElastiCacheTestConnections() {}
static Socket openSocket(String host, int port) throws IOException {
ElastiCacheService service = CDI.current().select(ElastiCacheService.class).get();
for (ReplicationGroup group : service.listReplicationGroups(null)) {
if (!group.isEncryptedInTransit()) {
continue;
}
if (group.getProxyPort() == port) {
return openSocket(host, port, true);
}
for (ClusterNode node : group.getClusterNodes()) {
if (node.getProxyPort() == port) {
return openSocket(host, port, true);
}
}
}
for (CacheCluster cluster : service.findCacheClusters(null)) {
if (cluster.getAuthMode() != AuthMode.NO_AUTH && cluster.getConfigurationEndpoint() != null
&& cluster.getConfigurationEndpoint().port() == port) {
return openSocket(host, port, true);
}
}
return openSocket(host, port, false);
}
static Socket openSocket(String host, int port, boolean encrypted) throws IOException {
if (!encrypted) {
return new Socket(host, port);
}
try {
FlociCertificateAuthority authority = CDI.current().select(FlociCertificateAuthority.class).get();
SSLSocket socket = (SSLSocket) TlsTrust.trusting(authority.certificate()).getSocketFactory()
.createSocket(host, port);
SSLParameters parameters = socket.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(parameters);
socket.setSoTimeout(10000);
socket.startHandshake();
return socket;
} catch (Exception e) {
throw new IOException("Could not establish a trusted cache TLS connection", e);
}
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.testutil.FreePorts;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
@@ -294,7 +293,7 @@ class AbstractRedisAuthProxyHandshakeTest {
private static TestProxy startProxy(ServerSocket backendServer, boolean authRequired,
String username, String password,
int handshakeTimeoutMillis) throws IOException {
int proxyPort = FreePorts.anyInterfacePort();
int proxyPort = 0;
TestProxy proxy = new TestProxy("127.0.0.1", backendServer.getLocalPort(), proxyPort,
authRequired, username, password, handshakeTimeoutMillis);
proxy.start(proxyPort);
@@ -366,7 +365,7 @@ class AbstractRedisAuthProxyHandshakeTest {
}
private int proxyPort() {
return proxyPort;
return localPort();
}
private int authenticationAttempts() {
@@ -0,0 +1,106 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLContext;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ElastiCacheTlsCertificatesTest {
@TempDir
Path directory;
@Test
void concurrentHandshakesRenewAnExpiringLeafOnce() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
CertificateGenerator generator = spy(new CertificateGenerator());
CertificateGenerator.GeneratedCertificate expiring = new CertificateGenerator().generateIssuedCertificate(
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048, null, authority.issuer(),
CertificateGenerator.LeafUsage.SERVER, Instant.now().plusSeconds(120));
doReturn(expiring).doCallRealMethod().when(generator)
.generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
Clock clock = mock(Clock.class);
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(120));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config(), generator, clock);
SSLContext original = certificates.sslContext();
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(61));
assertSame(original, certificates.sslContext());
when(clock.instant()).thenReturn(expiring.notAfter().minusSeconds(60));
List<CompletableFuture<SSLContext>> contexts = IntStream.range(0, 8)
.mapToObj(ignored -> CompletableFuture.supplyAsync(certificates::sslContext)).toList();
SSLContext renewed = contexts.getFirst().get(10, TimeUnit.SECONDS);
assertNotSame(original, renewed);
for (CompletableFuture<SSLContext> context : contexts) {
assertSame(renewed, context.get(10, TimeUnit.SECONDS));
}
assertSame(renewed, certificates.sslContext());
verify(generator, times(2)).generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
}
@Test
void failedIssuancePreservesTheCauseAndCanBeRetried() {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
CertificateGenerator generator = spy(new CertificateGenerator());
IllegalStateException failure = new IllegalStateException("certificate setup failed");
doThrow(failure).doCallRealMethod().when(generator)
.generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config(), generator);
assertSame(failure, assertThrows(IllegalStateException.class, certificates::sslContext).getCause());
assertNotNull(certificates.sslContext());
verify(generator, times(2)).generateIssuedCertificate(anyString(), anyList(), eq(KeyAlgorithm.RSA_2048), isNull(),
any(CertificateGenerator.Issuer.class), eq(CertificateGenerator.LeafUsage.SERVER), any(Instant.class));
}
@Test
void blankConfiguredHostnamesAreSkipped() {
EmulatorConfig config = config();
when(config.hostname()).thenReturn(Optional.of(" "));
when(config.baseUrl()).thenReturn(" ");
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.of(" "));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(
FlociCertificateAuthority.loadOrCreate(directory), config, new CertificateGenerator());
assertNotNull(certificates.sslContext());
}
private EmulatorConfig config() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.hostname()).thenReturn(Optional.empty());
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.empty());
return config;
}
}
@@ -0,0 +1,280 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import io.github.hectorvent.floci.services.elasticache.model.TransitEncryption;
import io.github.hectorvent.floci.testing.TlsTrust;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ElastiCacheTlsProxyTest {
private static final byte[] AUTH = "*2\r\n$4\r\nAUTH\r\n$18\r\nsynthetic-password\r\n"
.getBytes(StandardCharsets.UTF_8);
private static final byte[] PING = "*1\r\n$4\r\nPING\r\n".getBytes(StandardCharsets.UTF_8);
@TempDir
Path directory;
private ElastiCacheAuthProxy proxy(FlociCertificateAuthority authority, int backendPort) {
return proxy(authority, backendPort, () -> TransitEncryption.REQUIRED);
}
private ElastiCacheAuthProxy proxy(FlociCertificateAuthority authority, int backendPort,
Supplier<TransitEncryption> encryption) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.hostname()).thenReturn(Optional.of("cache.test"));
when(config.baseUrl()).thenReturn("https://base.test:4566");
when(config.services().elasticache().clusterAnnounceHostname()).thenReturn(Optional.of("nodes.test"));
ElastiCacheTlsCertificates certificates = new ElastiCacheTlsCertificates(authority, config, new CertificateGenerator());
return new ElastiCacheAuthProxy("tls-test", AuthMode.PASSWORD, "127.0.0.1", backendPort,
new ElastiCacheAuthProxy.PasswordValidator() {
@Override
public boolean validatePassword(String username, String password) {
return "synthetic-password".equals(password);
}
@Override
public TransitEncryption transitEncryption() {
return encryption.get();
}
}, mock(SigV4Validator.class), certificates::sslContext);
}
@ParameterizedTest
@ValueSource(strings = {"cache.test", "nodes.test", "base.test", "host.docker.internal",
"localhost", "127.0.0.1", "0.0.0.0", "::1", "localhost.floci.io"})
void tlsVerifiesTheSharedCaAndEndpointNameThenAuthenticatesAndRelays(String hostname) throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocket backend = new ServerSocket(0)) {
CompletableFuture<String> received = CompletableFuture.supplyAsync(() -> {
try (Socket socket = backend.accept()) {
socket.setSoTimeout(5000);
String[] command = new RespReader(socket.getInputStream()).readCommand();
socket.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
return command[0];
} catch (Exception e) {
throw new IllegalStateException(e);
}
});
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort());
proxy.start(0);
try (Socket client = tlsClient(authority, proxy.localPort(), hostname)) {
BufferedReader reader = reader(client);
assertEquals("+OK", send(client, reader, AUTH));
assertEquals("+PONG", send(client, reader, PING));
assertEquals("PING", received.get(5, TimeUnit.SECONDS));
} finally {
proxy.stop();
}
}
}
@Test
void encryptedEndpointRejectsPlaintextBeforeBackendAccess() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocketChannel backend = idleBackend()) {
ElastiCacheAuthProxy proxy = proxy(authority, backendPort(backend));
proxy.start(0);
try (Socket client = plaintextClient(proxy.localPort())) {
client.getOutputStream().write(PING);
client.getOutputStream().flush();
// A fatal TLS alert or EOF is acceptable; no RESP success can be returned.
int first = client.getInputStream().read();
assertTrue(first == -1 || first == 21);
awaitProxyClose(client);
assertNull(backend.accept(), "a refused client must not reach the backend");
} finally {
proxy.stop();
}
}
}
@Test
void rejectsAnUntrustedCaAndAnIncorrectEndpointName() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory.resolve("server"));
FlociCertificateAuthority wrong = FlociCertificateAuthority.loadOrCreate(directory.resolve("untrusted"));
try (ServerSocketChannel backend = idleBackend()) {
ElastiCacheAuthProxy proxy = proxy(authority, backendPort(backend));
proxy.start(0);
int port = proxy.localPort();
try {
for (boolean wrongName : new boolean[]{false, true}) {
SSLContext context = TlsTrust.trusting((wrongName ? authority : wrong).certificate());
// autoClose off: tcp stays open after the refusal, so the proxy's close can be seen
try (Socket tcp = plaintextClient(port);
SSLSocket client = (SSLSocket) context.getSocketFactory().createSocket(tcp,
wrongName ? "wrong.test" : "cache.test", port, false)) {
verifyEndpointName(client);
assertThrows(IOException.class, client::startHandshake);
awaitProxyClose(tcp);
}
}
assertNull(backend.accept(), "a refused client must not reach the backend");
} finally {
proxy.stop();
}
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void preferredModeTakesEncryptedAndUnencryptedClients(boolean encrypted) throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
try (ServerSocket backend = new ServerSocket(0)) {
answerEveryCommandWithPong(backend);
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort(), () -> TransitEncryption.PREFERRED);
proxy.start(0);
try (Socket client = encrypted
? tlsClient(authority, proxy.localPort(), "cache.test")
: plaintextClient(proxy.localPort())) {
BufferedReader reader = reader(client);
assertEquals("+OK", send(client, reader, AUTH));
assertEquals("+PONG", send(client, reader, PING));
} finally {
proxy.stop();
}
}
}
@Test
void requiredModeDropsUnencryptedConnectionsAndKeepsEncryptedOnes() throws Exception {
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(directory);
AtomicReference<TransitEncryption> mode = new AtomicReference<>(TransitEncryption.PREFERRED);
try (ServerSocket backend = new ServerSocket(0)) {
answerEveryCommandWithPong(backend);
ElastiCacheAuthProxy proxy = proxy(authority, backend.getLocalPort(), mode::get);
proxy.start(0);
try (Socket plaintext = plaintextClient(proxy.localPort());
Socket encrypted = tlsClient(authority, proxy.localPort(), "cache.test")) {
BufferedReader plaintextReader = reader(plaintext);
BufferedReader encryptedReader = reader(encrypted);
assertEquals("+OK", send(plaintext, plaintextReader, AUTH));
assertEquals("+PONG", send(plaintext, plaintextReader, PING));
assertEquals("+OK", send(encrypted, encryptedReader, AUTH));
assertEquals("+PONG", send(encrypted, encryptedReader, PING));
mode.set(TransitEncryption.REQUIRED);
proxy.dropUnencryptedConnections();
assertNull(plaintextReader.readLine(), "the unencrypted connection must be closed");
assertEquals("+PONG", send(encrypted, encryptedReader, PING));
} finally {
proxy.stop();
}
}
}
private static SSLSocket tlsClient(FlociCertificateAuthority authority, int port, String hostname) throws Exception {
Socket tcp = plaintextClient(port);
SSLSocket client = (SSLSocket) TlsTrust.trusting(authority.certificate()).getSocketFactory()
.createSocket(tcp, hostname, port, true);
verifyEndpointName(client);
client.startHandshake();
return client;
}
private static Socket plaintextClient(int port) throws IOException {
Socket client = new Socket("127.0.0.1", port);
client.setSoTimeout(5000);
return client;
}
private static void verifyEndpointName(SSLSocket client) {
SSLParameters parameters = client.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
client.setSSLParameters(parameters);
}
private static BufferedReader reader(Socket client) throws IOException {
return new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
}
private static String send(Socket client, BufferedReader reader, byte[] command) throws IOException {
client.getOutputStream().write(command);
client.getOutputStream().flush();
return reader.readLine();
}
/** Returns once the proxy has closed the connection, so it has finished with the client. */
private static void awaitProxyClose(Socket tcp) throws IOException {
InputStream in = tcp.getInputStream();
try {
while (in.read() != -1) {
// drains whatever the proxy sent before closing, a TLS alert for one
}
} catch (SocketException expected) {
// a reset closes the connection as well
}
}
/** A backend that only accepts without blocking, so a check for a connection answers at once. */
private static ServerSocketChannel idleBackend() throws IOException {
ServerSocketChannel backend = ServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 0));
backend.configureBlocking(false);
return backend;
}
private static int backendPort(ServerSocketChannel backend) throws IOException {
return ((InetSocketAddress) backend.getLocalAddress()).getPort();
}
/** Answers every command on every relayed connection with PONG, until the backend is closed. */
private static void answerEveryCommandWithPong(ServerSocket backend) {
Thread.ofVirtual().start(() -> {
while (!backend.isClosed()) {
try {
Socket relayed = backend.accept();
Thread.ofVirtual().start(() -> answerWithPong(relayed));
} catch (IOException expected) {
// the test closed the backend
}
}
});
}
private static void answerWithPong(Socket relayed) {
try (relayed) {
RespReader reader = new RespReader(relayed.getInputStream());
while (true) {
reader.readCommand();
relayed.getOutputStream().write("+PONG\r\n".getBytes(StandardCharsets.UTF_8));
relayed.getOutputStream().flush();
}
} catch (IOException expected) {
// the proxy closed the relay, which ends the stream
}
}
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.testing;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
/** A client TLS context that trusts one CA and nothing else, so a test sees real verification. */
public final class TlsTrust {
private TlsTrust() {
}
public static SSLContext trusting(X509Certificate ca) throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci", ca);
TrustManagerFactory managers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
managers.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, managers.getTrustManagers(), null);
return context;
}
}