mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(elasticache): terminate required TLS at cache proxies (#6227)
This commit is contained in:
1 parent
b4c71b9e25
commit
346a7f4526
25 files changed
+979
-100
No files matched your search
@@ -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<>();
|
||||
|
||||
+36
-2
@@ -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;
|
||||
|
||||
+8
@@ -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<>();
|
||||
|
||||
+9
@@ -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
-16
@@ -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) {
|
||||
|
||||
+57
@@ -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;
|
||||
}
|
||||
|
||||
+12
-2
@@ -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();
|
||||
|
||||
+80
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-37
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user