Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(rds): match proxy TLS cert SAN to the advertised endpoint (#2603)

Matheus Oliveirab1d7286444e5
diff --git a/docs/services/rds.md b/docs/services/rds.md
index 8d44e9cf65..a9d9d8a6a2 100644
--- a/docs/services/rds.md
+++ b/docs/services/rds.md
@@ -292,3 +292,34 @@ FLOCI_STORAGE_HOST_PERSISTENT_PATH=/absolute/host/path/data
The RDS auth proxy validates the master username and password at the proxy layer. All other database users are passed through directly to the backend engine — create them with standard SQL (`CREATE USER`) and connect as normal.
IAM database authentication is also supported. Set `--enable-iam-database-authentication` at instance creation time and use `aws rds generate-db-auth-token` to obtain a token.
+
+## TLS / SSL
+
+The RDS auth proxy terminates TLS itself (the backend container stays plaintext) using a
+self-signed CA whose Subject Alternative Names cover every advertised host Floci has handed
+out for a DB instance, cluster, or RDS Proxy — the Docker bridge IP, `host.docker.internal`,
+`localhost`, or whatever `rds.endpointHost` resolves to. The CA is persisted at
+`{storage.persistent-path}/tls/rds-ca.crt` and grows its SAN list as new hosts appear, so the
+same root survives restarts and works for every local database, not just the one that
+generated it.
+
+Floci logs the certificate path (and the `PGSSLROOTCERT` hint) the first time it generates or
+loads it:
+
+```
+RDS proxy TLS: CA cert at ./data/tls/rds-ca.crt
+RDS proxy TLS: for sslmode=verify-full set PGSSLROOTCERT=./data/tls/rds-ca.crt
+```
+
+Because the SAN matches the address you actually connect to, `verify-full` (the same level
+Aurora enforces in AWS) works locally too — no need to fall back to `sslmode=disable` just to
+exercise the same connection-string settings you use in production:
+
+```bash
+# PostgreSQL
+PGSSLROOTCERT=./data/tls/rds-ca.crt psql "host=localhost port=7001 user=admin sslmode=verify-full"
+
+# MySQL / MariaDB
+mysql -h 127.0.0.1 -P 7002 -u root -psecret123 \
+ --ssl-mode=VERIFY_IDENTITY --ssl-ca=./data/tls/rds-ca.crt
+```
diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
index 859f861e53..7fd314ddd2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
@@ -84,7 +84,7 @@ public class CertificateGenerator {
* or using virtual threads for concurrent certificate generation.</p>
*/
public GeneratedCertificate generateCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {
- return buildCertificate(domainName, sans, keyAlgorithm, ISSUER_DN, false);
+ return buildCertificate(domainName, sans, keyAlgorithm, ISSUER_DN, false, null);
}
/**
@@ -95,13 +95,25 @@ public class CertificateGenerator {
* Floci once the certificate is installed in their CA bundle.
*/
public GeneratedCertificate generateSelfSignedCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {
- return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true);
+ return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true, null);
+ }
+
+ /**
+ * Same as {@link #generateSelfSignedCertificate(String, List, KeyAlgorithm)}, but signs the
+ * certificate with a caller-supplied key pair instead of minting a new one. Use this to reissue
+ * a trust anchor with an updated SAN list without changing its key: a client that already
+ * trusts a certificate sharing this key will still validate the new one, since the reissued
+ * certificate's signature verifies against the same public key.
+ */
+ public GeneratedCertificate generateSelfSignedCertificate(String domainName, List<String> sans,
+ KeyAlgorithm keyAlgorithm, KeyPair keyPair) {
+ return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true, keyPair);
}
private GeneratedCertificate buildCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm,
- String issuerDn, boolean asCa) {
+ String issuerDn, boolean asCa, KeyPair suppliedKeyPair) {
try {
- KeyPair keyPair = generateKeyPair(keyAlgorithm);
+ KeyPair keyPair = suppliedKeyPair != null ? suppliedKeyPair : generateKeyPair(keyAlgorithm);
Instant now = Instant.now();
Instant notBefore = now;
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
index 0f91ef48b0..fa5cfa87bf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
@@ -620,6 +620,7 @@ public class RdsService implements Resettable, ResourceProvider {
final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
engine, iamEnabled, proxyPort, backendHost, backendPort,
+ instance.getEndpoint().address(),
masterUsername, masterPassword, dbName,
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw));
@@ -1075,6 +1076,7 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getEngine(),
instance.isIamDatabaseAuthenticationEnabled(),
instance.getProxyPort(), instance.getContainerHost(), instance.getContainerPort(),
+ instance.getEndpoint().address(),
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion, id, user, pw));
@@ -1269,6 +1271,7 @@ public class RdsService implements Resettable, ResourceProvider {
proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id),
engine, iamEnabled, proxyPort,
cluster.getContainerHost(), cluster.getContainerPort(),
+ cluster.getEndpoint().address(),
effectiveMasterUser, masterPassword, databaseName,
(user, pw) -> validateDbClusterPasswordForScope(
accountId, clusterRegion, id, user, pw));
@@ -1878,8 +1881,8 @@ public class RdsService implements Resettable, ResourceProvider {
final boolean isCluster = "TRACKED_CLUSTER".equals(target.getType());
final String targetRegion = regionFromArn(proxy.getDbProxyArn());
proxyManager.startProxy(dbProxyRelayKey(proxy), engine, proxy.isIamAuth(),
- proxy.getProxyPort(), backendHost, backendPort, effectiveMasterUser,
- masterPassword, dbName,
+ proxy.getProxyPort(), backendHost, backendPort, proxy.getEndpointHost(),
+ effectiveMasterUser, masterPassword, dbName,
(user, pw) -> isCluster
? validateDbClusterPasswordForScope(
proxyAccountId, targetRegion, targetId, user, pw)
@@ -3738,7 +3741,7 @@ public class RdsService implements Resettable, ResourceProvider {
String effectiveMasterUser = masterUser != null ? masterUser : "root";
String targetId = target.getRdsResourceId();
proxyManager.startProxy(dbProxyRelayKey(proxy), engine, proxy.isIamAuth(), proxy.getProxyPort(),
- backendHost, backendPort, effectiveMasterUser, masterPassword, dbName,
+ backendHost, backendPort, proxy.getEndpointHost(), effectiveMasterUser, masterPassword, dbName,
(user, password) -> clusterTarget
? validateDbClusterPasswordForScope(
accountId, proxyRegion, targetId, user, password)
@@ -3825,8 +3828,8 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.getDbClusterArn(), cluster.getDbClusterIdentifier()),
cluster.getEngine(),
cluster.isIamDatabaseAuthenticationEnabled(), proxyPort,
- restoredHandle.getHost(), restoredHandle.getPort(), effectiveMasterUser,
- cluster.getMasterPassword(), cluster.getDatabaseName(),
+ restoredHandle.getHost(), restoredHandle.getPort(), cluster.getEndpoint().address(),
+ effectiveMasterUser, cluster.getMasterPassword(), cluster.getDatabaseName(),
(user, pw) -> validateDbClusterPasswordForScope(
accountId, clusterRegion,
cluster.getDbClusterIdentifier(), user, pw));
@@ -3946,8 +3949,8 @@ public class RdsService implements Resettable, ResourceProvider {
instance.getDbInstanceArn(), instance.getDbInstanceIdentifier()),
instance.getEngine(),
instance.isIamDatabaseAuthenticationEnabled(), proxyPort,
- backendHost, backendPort, effectiveMasterUser,
- instance.getMasterPassword(), instance.getDbName(),
+ backendHost, backendPort, instance.getEndpoint().address(),
+ effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
(user, pw) -> validateDbPasswordForScope(
accountId, instanceRegion,
instance.getDbInstanceIdentifier(), user, pw));
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java
index 6668e74267..1f44fc182e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy;
import org.jboss.logging.Logger;
+import javax.net.ssl.SSLSocket;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
@@ -16,28 +17,53 @@ import java.util.Arrays;
* Handles the MySQL wire protocol auth intercept using a transparent relay.
*
* <p>The proxy reads the backend's real Handshake V10 (with the backend's actual nonce)
- * and forwards it verbatim to the client. The client then computes its scramble using
- * the backend's nonce. The proxy validates the scramble against the expected master
- * password, then forwards the client's HandshakeResponse directly to the backend for
- * final validation.
+ * and forwards it to the client (with {@code CLIENT_SSL} forced on, so the client can
+ * request TLS even though the backend container itself stays plaintext). The client then
+ * computes its scramble using the backend's nonce. The proxy validates the scramble against
+ * the expected master password, then forwards the client's HandshakeResponse directly to the
+ * backend for final validation.
*
* <p>This avoids any synthetic nonce and lets the backend handle all auth plugin
* negotiation (including caching_sha2_password auth-switch) transparently.
+ *
+ * <p>If the client requests TLS, it sends a short {@code SSLRequest} packet (32-byte payload,
+ * {@code CLIENT_SSL} set) instead of a full {@code HandshakeResponse41}, then immediately starts
+ * a TLS handshake on the same socket. The proxy terminates that TLS handshake itself (the
+ * backend connection remains plaintext), reads the real {@code HandshakeResponse41} over the
+ * now-encrypted stream, and rewrites its sequence number before forwarding it to the backend —
+ * the backend never saw an {@code SSLRequest}, so it expects that response at sequence 1, not 2.
+ * That one "stolen" packet leaves the backend's view of the shared sequence counter permanently
+ * one behind the client's for the rest of the connection phase, so every packet exchanged until
+ * the terminal OK/ERR (including any {@code AuthSwitchRequest}/{@code AuthMoreData} round trips)
+ * is relayed through {@link #relayConnectionPhase} to keep both sides in sync before handing off
+ * to the plain byte-for-byte {@link #bridge}.
*/
public class MySqlProtocolHandler {
private static final Logger LOG = Logger.getLogger(MySqlProtocolHandler.class);
+ private static final int CLIENT_SSL = 0x0800;
private static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x200000;
private static final int CLIENT_SECURE_CONNECTION = 0x8000;
+ // First payload byte of the packet types that can appear during the connection phase.
+ private static final int OK_PACKET_MARKER = 0x00;
+ private static final int ERR_PACKET_MARKER = 0xFF;
+ private static final int AUTH_MORE_DATA_MARKER = 0x01;
+
+ // Second payload byte of an AuthMoreData packet under caching_sha2_password: fast_auth_success
+ // means the backend is about to send the terminal OK with no further input from the client.
+ private static final int CACHING_SHA2_FAST_AUTH_SUCCESS = 0x03;
+
+ // 4-byte capabilities + 4-byte max-packet-size + 1-byte charset + 23 reserved bytes.
+ private static final int SSL_REQUEST_PAYLOAD_LENGTH = 32;
+
public static void handleAuth(Socket client, Socket backend,
String masterUsername, String masterPassword,
boolean iamEnabled, RdsSigV4Validator sigV4,
+ RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator) throws IOException {
- InputStream clientIn = client.getInputStream();
- OutputStream clientOut = client.getOutputStream();
InputStream backendIn = backend.getInputStream();
OutputStream backendOut = backend.getOutputStream();
@@ -53,18 +79,61 @@ public class MySqlProtocolHandler {
// Extract the backend's nonce for our credential validation
byte[] backendNonce = extractMysqlNonce(backendHandshakeRaw);
- // Phase 2: Forward backend's handshake verbatim to the client
+ // The proxy terminates TLS itself, so advertise CLIENT_SSL to the client even if the
+ // (plaintext) backend didn't.
+ forceClientSslCapability(backendHandshakeRaw);
+
+ InputStream clientIn = client.getInputStream();
+ OutputStream clientOut = client.getOutputStream();
+
+ // Phase 2: Forward backend's handshake (with CLIENT_SSL forced on) to the client
clientOut.write(backendHandshakeRaw);
clientOut.flush();
- // Phase 3: Read client's HandshakeResponse41
- byte[] clientResponseRaw = readMysqlPacketRaw(clientIn);
- if (clientResponseRaw == null || clientResponseRaw.length < 40) {
+ // Phase 3: Read the client's first response — either the real HandshakeResponse41,
+ // or a short SSLRequest signaling that a TLS upgrade should happen first.
+ byte[] clientFirstRaw = readMysqlPacketRaw(clientIn);
+ if (clientFirstRaw == null) {
closeQuietly(client);
closeQuietly(backend);
return;
}
+ byte[] clientResponseRaw;
+ int sequenceOffset = 0;
+ if (isSslRequest(clientFirstRaw)) {
+ SSLSocket sslSocket;
+ try {
+ sslSocket = upgradeToTls(client, tlsCertificates);
+ } catch (IOException e) {
+ LOG.warnv("MySQL TLS upgrade failed: {0}", e.getMessage());
+ closeQuietly(client);
+ closeQuietly(backend);
+ return;
+ }
+ client = sslSocket;
+ clientIn = sslSocket.getInputStream();
+ clientOut = sslSocket.getOutputStream();
+
+ clientResponseRaw = readMysqlPacketRaw(clientIn);
+ if (clientResponseRaw == null || clientResponseRaw.length < 40) {
+ closeQuietly(client);
+ closeQuietly(backend);
+ return;
+ }
+ // The backend never saw the SSLRequest, so its view of the shared sequence counter is
+ // permanently one behind the client's for the rest of the connection phase.
+ sequenceOffset = 1;
+ clientResponseRaw[3] = (byte) (clientResponseRaw[3] - sequenceOffset);
+ } else {
+ clientResponseRaw = clientFirstRaw;
+ if (clientResponseRaw.length < 40) {
+ closeQuietly(client);
+ closeQuietly(backend);
+ return;
+ }
+ }
+
// Phase 4: Validate credentials against the backend nonce.
// Master user: validate the scramble locally against the known master password.
// Non-master users: pass through — the backend validates their scramble directly.
@@ -99,15 +168,121 @@ public class MySqlProtocolHandler {
return;
}
- // Phase 5: Forward client's HandshakeResponse to backend and bridge
- // The backend validates the same scramble (same nonce, same password) and sends OK.
- // The bridge then relays all subsequent traffic including the backend's auth response.
+ // Phase 5: Forward client's HandshakeResponse to backend, then relay the rest of the
+ // connection phase (renumbering if a TLS upgrade shifted the shared sequence counter)
+ // before handing off to the plain byte-for-byte bridge.
backendOut.write(clientResponseRaw);
backendOut.flush();
+ if (sequenceOffset != 0
+ && !relayConnectionPhase(clientIn, clientOut, backendIn, backendOut, sequenceOffset)) {
+ closeQuietly(client);
+ closeQuietly(backend);
+ return;
+ }
+
bridge(client, backend);
}
+ /**
+ * Relays packets between client and backend for the remainder of the connection phase,
+ * shifting each sequence number by {@code offset} to correct for a packet the backend never
+ * saw (see {@link #handleAuth}). Stops once the terminal OK/ERR packet reaches the client —
+ * at that point both sides independently reset their sequence counters for the next command,
+ * so the offset no longer applies and {@link #bridge} can take over untouched.
+ *
+ * @return {@code false} if either side closed the connection mid-exchange
+ */
+ private static boolean relayConnectionPhase(InputStream clientIn, OutputStream clientOut,
+ InputStream backendIn, OutputStream backendOut,
+ int offset) throws IOException {
+ while (true) {
+ byte[] backendRaw = readMysqlPacketRaw(backendIn);
+ if (backendRaw == null || backendRaw.length < 5) {
+ return false;
+ }
+ backendRaw[3] = (byte) (backendRaw[3] + offset);
+ clientOut.write(backendRaw);
+ clientOut.flush();
+
+ int marker = backendRaw[4] & 0xFF;
+ if (marker == OK_PACKET_MARKER || marker == ERR_PACKET_MARKER) {
+ return true;
+ }
+ if (marker == AUTH_MORE_DATA_MARKER && backendRaw.length > 5
+ && (backendRaw[5] & 0xFF) == CACHING_SHA2_FAST_AUTH_SUCCESS) {
+ // caching_sha2_password fast-auth success: the client sends nothing back — the
+ // backend's very next packet is the terminal OK. Reading from the client here would
+ // block forever.
+ continue;
+ }
+
+ // AuthSwitchRequest, or AuthMoreData requesting full authentication: the client replies
+ // once more before the backend issues its next verdict.
+ byte[] clientRaw = readMysqlPacketRaw(clientIn);
+ if (clientRaw == null || clientRaw.length < 4) {
+ return false;
+ }
+ clientRaw[3] = (byte) (clientRaw[3] - offset);
+ backendOut.write(clientRaw);
+ backendOut.flush();
+ }
+ }
+
+ // ── TLS upgrade ───────────────────────────────────────────────────────────
+
+ /**
+ * An {@code SSLRequest} is a {@code HandshakeResponse41}-shaped packet truncated to just its
+ * fixed 32-byte prefix (capabilities, max-packet-size, charset, reserved) — a full response
+ * always has at least a null-terminated username after that prefix. {@code CLIENT_SSL} being
+ * set distinguishes it from a (protocol-invalid) truncated real response.
+ */
+ private static boolean isSslRequest(byte[] raw) {
+ if (raw.length != 4 + SSL_REQUEST_PAYLOAD_LENGTH) {
+ return false;
+ }
+ int caps = (raw[4] & 0xFF) | ((raw[5] & 0xFF) << 8)
+ | ((raw[6] & 0xFF) << 16) | ((raw[7] & 0xFF) << 24);
+ return (caps & CLIENT_SSL) != 0;
+ }
+
+ private static SSLSocket upgradeToTls(Socket socket, RdsProxyTlsCertificates tlsCertificates)
+ throws IOException {
+ try {
+ SSLSocket sslSocket = (SSLSocket) tlsCertificates.sslContext().getSocketFactory()
+ .createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
+ sslSocket.setUseClientMode(false);
+ sslSocket.startHandshake();
+ return sslSocket;
+ } catch (Exception e) {
+ throw new IOException("Unable to negotiate MySQL SSL", e);
+ }
+ }
+
+ /**
+ * Sets the {@code CLIENT_SSL} bit in a raw Handshake V10 packet's capability flags, so the
+ * client is offered TLS even when the (plaintext) backend didn't advertise it. Walks the same
+ * fields as {@link #extractMysqlNonce(byte[])} up to the low 2 bytes of the capability flags.
+ */
+ private static void forceClientSslCapability(byte[] raw) {
+ int i = 4 + 1; // skip 4-byte header + protocol version byte
+
+ while (i < raw.length && raw[i] != 0) {
+ i++;
+ }
+ i++; // skip null-terminated server version
+
+ i += 4; // connection id
+ i += 8; // auth-plugin-data part 1
+ i++; // filler byte
+
+ // Capability flags lower 2 bytes, little-endian: CLIENT_SSL (0x0800) lives in the high
+ // byte of this field.
+ if (i + 1 < raw.length) {
+ raw[i + 1] |= (byte) (CLIENT_SSL >> 8);
+ }
+ }
+
// ── Nonce extraction ──────────────────────────────────────────────────────
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
index 158417ff03..662cb278ad 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
@@ -1,44 +1,23 @@
package io.github.hectorvent.floci.services.rds.proxy;
import org.jboss.logging.Logger;
-import org.bouncycastle.asn1.x500.X500Name;
-import org.bouncycastle.asn1.x509.Extension;
-import org.bouncycastle.asn1.x509.GeneralName;
-import org.bouncycastle.asn1.x509.GeneralNames;
-import org.bouncycastle.cert.X509v3CertificateBuilder;
-import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
-import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.bouncycastle.operator.ContentSigner;
-import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import javax.crypto.Mac;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.math.BigInteger;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.SecureRandom;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.time.Instant;
-import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
-import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -64,15 +43,15 @@ public class PostgresProtocolHandler {
private static final int SSL_REQUEST_CODE = 80877103;
private static final int STARTUP_PROTOCOL_VERSION = 196608; // v3.0
- private static volatile SSLContext serverSslContext;
public static void handleAuth(Socket client, Socket backend,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
+ RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator) throws IOException {
// Phase 1: Read client startup message (possibly preceded by SSL request)
- StartupMessage startup = readStartupMessage(client);
+ StartupMessage startup = readStartupMessage(client, tlsCertificates);
if (startup == null) {
closeQuietly(client);
return;
@@ -168,7 +147,8 @@ public class PostgresProtocolHandler {
// ── Startup ───────────────────────────────────────────────────────────────
- private static StartupMessage readStartupMessage(Socket socket) throws IOException {
+ private static StartupMessage readStartupMessage(Socket socket, RdsProxyTlsCertificates tlsCertificates)
+ throws IOException {
Socket currentSocket = socket;
while (true) {
InputStream in = currentSocket.getInputStream();
@@ -182,7 +162,7 @@ public class PostgresProtocolHandler {
if (proto == SSL_REQUEST_CODE) {
out.write('S');
out.flush();
- currentSocket = acceptSsl(currentSocket);
+ currentSocket = acceptSsl(currentSocket, tlsCertificates);
continue;
}
@@ -200,9 +180,9 @@ public class PostgresProtocolHandler {
}
}
- static Socket acceptSsl(Socket socket) throws IOException {
+ static Socket acceptSsl(Socket socket, RdsProxyTlsCertificates tlsCertificates) throws IOException {
try {
- SSLSocket sslSocket = (SSLSocket) serverSslContext().getSocketFactory()
+ SSLSocket sslSocket = (SSLSocket) tlsCertificates.sslContext().getSocketFactory()
.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
sslSocket.setUseClientMode(false);
sslSocket.startHandshake();
@@ -212,64 +192,6 @@ public class PostgresProtocolHandler {
}
}
- private static SSLContext serverSslContext() throws Exception {
- SSLContext context = serverSslContext;
- if (context != null) {
- return context;
- }
- synchronized (PostgresProtocolHandler.class) {
- context = serverSslContext;
- if (context == null) {
- context = createServerSslContext();
- serverSslContext = context;
- }
- return context;
- }
- }
-
- private static SSLContext createServerSslContext() throws Exception {
- if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
- Security.addProvider(new BouncyCastleProvider());
- }
-
- KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
- generator.initialize(2048, new SecureRandom());
- KeyPair keyPair = generator.generateKeyPair();
- Instant now = Instant.now();
-
- X500Name name = new X500Name("CN=localhost");
- X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
- name,
- new BigInteger(128, new SecureRandom()),
- Date.from(now.minus(1, ChronoUnit.MINUTES)),
- Date.from(now.plus(365, ChronoUnit.DAYS)),
- name,
- keyPair.getPublic());
- certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName[] {
- new GeneralName(GeneralName.dNSName, "localhost"),
- new GeneralName(GeneralName.iPAddress, "127.0.0.1")
- }));
-
- ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
- .setProvider(BouncyCastleProvider.PROVIDER_NAME)
- .build(keyPair.getPrivate());
- X509Certificate certificate = new JcaX509CertificateConverter()
- .setProvider(BouncyCastleProvider.PROVIDER_NAME)
- .getCertificate(certificateBuilder.build(signer));
-
- char[] password = new char[0];
- KeyStore keyStore = KeyStore.getInstance("PKCS12");
- keyStore.load(null, password);
- keyStore.setKeyEntry("floci-rds-postgres", keyPair.getPrivate(), password, new java.security.cert.Certificate[] {certificate});
-
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- keyManagerFactory.init(keyStore, password);
-
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
- return context;
- }
-
private record StartupMessage(Socket socket, String username, String database) {}
static String resolveEffectiveDbName(String clientDatabase, String instanceDbName) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
index b84d1042d3..eb65d20961 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
@@ -26,6 +26,7 @@ public class RdsAuthProxy {
private final String dbName;
private final DatabaseEngine engine;
private final RdsSigV4Validator sigV4;
+ private final RdsProxyTlsCertificates tlsCertificates;
private final PasswordValidator passwordValidator;
private volatile boolean running;
@@ -34,7 +35,8 @@ public class RdsAuthProxy {
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
- RdsSigV4Validator sigV4, PasswordValidator passwordValidator) {
+ RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
+ PasswordValidator passwordValidator) {
this.instanceId = instanceId;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -44,6 +46,7 @@ public class RdsAuthProxy {
this.masterPassword = masterPassword;
this.dbName = dbName;
this.sigV4 = sigV4;
+ this.tlsCertificates = tlsCertificates;
this.passwordValidator = passwordValidator;
}
@@ -93,10 +96,10 @@ public class RdsAuthProxy {
switch (engine) {
case POSTGRES -> PostgresProtocolHandler.handleAuth(
client, backend, masterUsername, masterPassword, dbName,
- iamEnabled, sigV4, passwordValidator::validate);
+ iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
case MYSQL, MARIADB -> MySqlProtocolHandler.handleAuth(
client, backend, masterUsername, masterPassword,
- iamEnabled, sigV4, passwordValidator::validate);
+ iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
}
} catch (Exception e) {
LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage());
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
index f9e47a6428..12a44ac3e7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
@@ -17,20 +17,24 @@ public class RdsProxyManager {
private static final Logger LOG = Logger.getLogger(RdsProxyManager.class);
private final RdsSigV4Validator sigV4Validator;
+ private final RdsProxyTlsCertificates tlsCertificates;
private final ConcurrentHashMap<String, RdsAuthProxy> proxies = new ConcurrentHashMap<>();
@Inject
- public RdsProxyManager(RdsSigV4Validator sigV4Validator) {
+ public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates) {
this.sigV4Validator = sigV4Validator;
+ this.tlsCertificates = tlsCertificates;
}
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
+ String advertisedHost,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
+ tlsCertificates.ensureHost(advertisedHost);
RdsAuthProxy proxy = new RdsAuthProxy(
instanceId, backendHost, backendPort, engine, iamEnabled,
- masterUsername, masterPassword, dbName, sigV4Validator, passwordValidator);
+ masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator);
try {
proxy.start(proxyPort);
} catch (IOException e) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java
new file mode 100644
index 0000000000..c6f0bfc0f9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java
@@ -0,0 +1,245 @@
+package io.github.hectorvent.floci.services.rds.proxy;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.CertificateMetadata;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+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.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.jboss.logging.Logger;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Owns the RDS auth proxy's self-signed CA certificate: a single trust anchor shared by every
+ * proxied Postgres/MySQL instance, cluster, and RDS Proxy target, whose Subject Alternative Names
+ * grow to cover every advertised host Floci has handed out (Docker bridge IP, {@code
+ * host.docker.internal}, a configured {@code rds.endpointHost}, etc.).
+ *
+ * <p>Persisted at {@code {persistent-path}/tls/rds-ca.{crt,key}} (plus a metadata file recording
+ * the current SAN list) so the same root survives restarts — a client only has to trust it once
+ * (e.g. {@code sslmode=verify-full sslrootcert=<path>}) to keep working across every local
+ * database and every restart, as long as the advertised host doesn't change.
+ */
+@ApplicationScoped
+public class RdsProxyTlsCertificates {
+
+ private static final Logger LOG = Logger.getLogger(RdsProxyTlsCertificates.class);
+
+ private static final List<String> DEFAULT_SANS = List.of("localhost", "127.0.0.1");
+ private static final String CERT_NAME = "rds-ca.crt";
+ private static final String KEY_NAME = "rds-ca.key";
+ private static final String METADATA_NAME = "rds-ca.metadata.json";
+ private static final String TLS_DIR = "tls";
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private final EmulatorConfig config;
+ private final CertificateGenerator certificateGenerator;
+ private final Object lock = new Object();
+
+ private volatile SSLContext sslContext;
+ private volatile Set<String> currentSans = Set.of();
+ private volatile KeyPair currentKeyPair;
+
+ @Inject
+ public RdsProxyTlsCertificates(EmulatorConfig config, CertificateGenerator certificateGenerator) {
+ this.config = config;
+ this.certificateGenerator = certificateGenerator;
+ }
+
+ /**
+ * Ensures {@code host} is covered by the current CA's SAN list, reissuing the certificate
+ * (and re-persisting it) if it is a genuinely new host. Reissuing reuses the existing key pair
+ * rather than minting a new one, so a client that already trusts a prior copy of this CA (e.g.
+ * one it copied into its own trust store) keeps validating connections after the SAN list
+ * grows — only the SAN extension and serial change, not the signing key. Cheap no-op once a
+ * host is known.
+ */
+ public void ensureHost(String host) {
+ if (host == null || host.isBlank()) {
+ return;
+ }
+ ensureInitialized();
+ if (currentSans.contains(host)) {
+ return;
+ }
+ synchronized (lock) {
+ if (currentSans.contains(host)) {
+ return;
+ }
+ Set<String> updated = new LinkedHashSet<>(currentSans);
+ updated.add(host);
+ regenerate(updated);
+ }
+ }
+
+ /**
+ * Returns the current TLS server context. Handlers should call this per-handshake rather than
+ * caching it themselves — {@link #ensureHost(String)} can swap it out at any time.
+ */
+ public SSLContext sslContext() {
+ ensureInitialized();
+ return sslContext;
+ }
+
+ private void ensureInitialized() {
+ if (sslContext != null) {
+ return;
+ }
+ synchronized (lock) {
+ if (sslContext != null) {
+ return;
+ }
+ ensureBouncyCastleRegistered();
+ Path tlsDir = tlsDir();
+ Path certFile = tlsDir.resolve(CERT_NAME);
+ Path keyFile = tlsDir.resolve(KEY_NAME);
+ Path metadataFile = tlsDir.resolve(METADATA_NAME);
+ if (Files.exists(certFile) && Files.exists(keyFile) && Files.exists(metadataFile)) {
+ try {
+ List<String> persistedSans = readMetadata(metadataFile);
+ loadExisting(certFile, keyFile, persistedSans);
+ // Re-harden on every load: earlier Floci versions wrote this key world-readable,
+ // so an existing install must be tightened too, not just newly generated ones.
+ restrictToOwnerOnly(tlsDir, "rwx------");
+ restrictToOwnerOnly(keyFile, "rw-------");
+ LOG.infov("RDS proxy TLS: reusing existing CA cert: {0} (SANs: {1})",
+ certFile, persistedSans);
+ logTrustHint(certFile);
+ return;
+ } catch (Exception e) {
+ LOG.warnv(e, "RDS proxy TLS: failed to load existing CA cert ({0}); regenerating",
+ e.getMessage());
+ }
+ }
+ regenerate(new LinkedHashSet<>(DEFAULT_SANS));
+ }
+ }
+
+ private void regenerate(Set<String> sans) {
+ try {
+ Path tlsDir = tlsDir();
+ Files.createDirectories(tlsDir);
+ restrictToOwnerOnly(tlsDir, "rwx------");
+ List<String> sanList = new ArrayList<>(sans);
+
+ KeyPair keyPair = this.currentKeyPair;
+ CertificateGenerator.GeneratedCertificate generated = keyPair != null
+ ? certificateGenerator.generateSelfSignedCertificate(
+ "localhost", sanList, KeyAlgorithm.RSA_2048, keyPair)
+ : certificateGenerator.generateSelfSignedCertificate(
+ "localhost", sanList, KeyAlgorithm.RSA_2048);
+
+ Path certFile = tlsDir.resolve(CERT_NAME);
+ Path keyFile = tlsDir.resolve(KEY_NAME);
+ Files.writeString(certFile, generated.certificatePem());
+ Files.writeString(keyFile, generated.privateKeyPem());
+ restrictToOwnerOnly(keyFile, "rw-------");
+ writeMetadata(tlsDir.resolve(METADATA_NAME), sanList);
+
+ X509Certificate certificate = certificateGenerator.parseCertificate(generated.certificatePem());
+ PrivateKey privateKey = certificateGenerator.parsePrivateKey(generated.privateKeyPem());
+ this.sslContext = buildSslContext(certificate, privateKey);
+ this.currentSans = Set.copyOf(sans);
+ this.currentKeyPair = new KeyPair(certificate.getPublicKey(), privateKey);
+
+ LOG.infov("RDS proxy TLS: generated CA cert at {0}", certFile);
+ logTrustHint(certFile);
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed to generate RDS proxy TLS certificate", e);
+ }
+ }
+
+ private void loadExisting(Path certFile, Path keyFile, List<String> sans) throws Exception {
+ X509Certificate certificate = certificateGenerator.parseCertificate(Files.readString(certFile));
+ PrivateKey privateKey = certificateGenerator.parsePrivateKey(Files.readString(keyFile));
+ this.sslContext = buildSslContext(certificate, privateKey);
+ this.currentSans = new LinkedHashSet<>(sans);
+ this.currentKeyPair = new KeyPair(certificate.getPublicKey(), privateKey);
+ }
+
+ private SSLContext buildSslContext(X509Certificate certificate, PrivateKey privateKey) throws Exception {
+ char[] password = new char[0];
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ keyStore.load(null, password);
+ keyStore.setKeyEntry("floci-rds-proxy", privateKey, password,
+ new java.security.cert.Certificate[]{certificate});
+
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keyManagerFactory.init(keyStore, password);
+
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
+ return context;
+ }
+
+ private Path tlsDir() {
+ return Path.of(config.storage().persistentPath(), TLS_DIR);
+ }
+
+ private static void ensureBouncyCastleRegistered() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ }
+
+ /**
+ * Restricts {@code path} to owner-only access. This CA's private key is meant to be trusted by
+ * a developer's client tooling (e.g. {@code sslmode=verify-full}), so unlike Floci's other
+ * generated keys — which only let you impersonate an emulated resource — anyone who can read
+ * this one can mint a certificate for any host the developer's trust store now accepts.
+ * No-ops on filesystems without POSIX permissions (e.g. Windows) rather than failing.
+ */
+ private static void restrictToOwnerOnly(Path path, String posixPermissions) {
+ try {
+ if (Files.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class)) {
+ Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(posixPermissions));
+ }
+ } catch (IOException e) {
+ LOG.warnv(e, "RDS proxy TLS: failed to restrict permissions on {0}", path);
+ }
+ }
+
+ private void logTrustHint(Path certFile) {
+ LOG.infov("RDS proxy TLS: for sslmode=verify-full set PGSSLROOTCERT={0}",
+ certFile.toAbsolutePath());
+ }
+
+ private List<String> readMetadata(Path metadataFile) throws IOException {
+ CertificateMetadata metadata = OBJECT_MAPPER.readValue(metadataFile.toFile(), CertificateMetadata.class);
+ List<String> hostnames = metadata.getHostnames();
+ if (hostnames == null || hostnames.isEmpty()) {
+ throw new IOException("RDS proxy TLS metadata file has no hostnames: " + metadataFile);
+ }
+ return hostnames;
+ }
+
+ private void writeMetadata(Path metadataFile, List<String> sans) throws IOException {
+ CertificateMetadata metadata = CertificateMetadata.create(sans, resolveFlociVersion());
+ String json = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);
+ Files.writeString(metadataFile, json);
+ }
+
+ private static String resolveFlociVersion() {
+ String env = System.getenv("FLOCI_VERSION");
+ return (env != null && !env.isBlank()) ? env : "dev";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
index 951f04c673..7eaab9b251 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
@@ -936,7 +936,7 @@ class RdsServiceTest {
assertEquals("DBSubnetGroupNotFoundFault", exception.getErrorCode());
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
- any(), anyInt(), any(), any(), any(), any());
+ any(), anyInt(), any(), any(), any(), any(), any());
}
@Test
@@ -1001,7 +1001,7 @@ class RdsServiceTest {
assertNull(cluster.getContainerId());
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
}
@Test
@@ -1234,7 +1234,7 @@ class RdsServiceTest {
assertNull(instance.getDockerVolumeName());
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
}
@Test
@@ -1300,7 +1300,7 @@ class RdsServiceTest {
verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(containerManager, never()).stop(any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
}
@Test
@@ -1957,7 +1957,7 @@ class RdsServiceTest {
eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
verify(restoredProxyManager).startProxy(
eq("rds-resource:" + restored.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
- eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432),
+ eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432), any(),
eq("admin"), eq("secret"), eq("app"), any());
restoredService.deleteDbInstance("mydb");
@@ -2010,11 +2010,11 @@ class RdsServiceTest {
eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
verify(restoredProxyManager).startProxy(
eq("rds-resource:" + restoredCluster.getDbClusterArn()), eq(DatabaseEngine.POSTGRES),
- eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432),
+ eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
eq("admin"), eq("secret"), eq("app"), any());
verify(restoredProxyManager).startProxy(
eq("rds-resource:" + restoredMember.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
- eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432),
+ eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432), any(),
eq("admin"), eq("secret"), eq("app"), any());
}
@@ -2038,7 +2038,7 @@ class RdsServiceTest {
.doNothing()
.when(restoredProxyManager).startProxy(
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
org.mockito.Mockito.doThrow(new IllegalStateException("cleanup failed"))
.doNothing()
.doNothing()
@@ -2163,7 +2163,7 @@ class RdsServiceTest {
.doNothing()
.when(restoredProxyManager).startProxy(
any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
org.mockito.Mockito.doThrow(new IllegalStateException("restore container cleanup failed"))
.doThrow(new IllegalStateException("delete container cleanup failed"))
.doNothing()
@@ -2661,7 +2661,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
RdsService service = proxyStoreService(
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
DbProxyAuth requiredAuth = new DbProxyAuth(
@@ -2715,7 +2715,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
RdsService service = proxyStoreService(
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
DbProxyAuth requiredAuth = new DbProxyAuth(
@@ -2981,7 +2981,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
RdsService service = proxyStoreService(
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
@@ -3098,7 +3098,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
RdsService service = proxyStoreService(
regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
@@ -3167,7 +3167,7 @@ class RdsServiceTest {
.getTargets().isEmpty());
verify(proxyManager).startProxy(
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
- anyBoolean(), eq(3306), eq("localhost"), eq(3306),
+ anyBoolean(), eq(3306), eq("localhost"), eq(3306), any(),
eq("admin"), eq("secret"), eq("app"), any());
verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
}
@@ -3197,7 +3197,7 @@ class RdsServiceTest {
relayRunning.set(true);
throw startupFailure;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
doAnswer(invocation -> {
relayRunning.set(false);
return null;
@@ -3664,7 +3664,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
IllegalStateException deleteFailure =
new IllegalStateException("simulated post-mutation target-group delete failure");
doAnswer(invocation -> {
@@ -3729,7 +3729,7 @@ class RdsServiceTest {
relayRunning.set(true);
return null;
}).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
- anyInt(), any(), any(), any(), any());
+ anyInt(), any(), any(), any(), any(), any());
IllegalStateException deleteFailure =
new IllegalStateException("simulated post-mutation proxy delete failure");
doAnswer(invocation -> {
@@ -3892,9 +3892,9 @@ class RdsServiceTest {
String relayKeyB = "rds-resource:" + instanceB.getDbInstanceArn();
verify(proxyManager).startProxy(eq(relayKeyA), any(), anyBoolean(), anyInt(),
- any(), anyInt(), any(), any(), any(), any());
+ any(), anyInt(), any(), any(), any(), any(), any());
verify(proxyManager).startProxy(eq(relayKeyB), any(), anyBoolean(), anyInt(),
- any(), anyInt(), any(), any(), any(), any());
+ any(), anyInt(), any(), any(), any(), any(), any());
org.mockito.Mockito.clearInvocations(proxyManager);
serviceA.deleteDbInstance("shared-db");
@@ -4009,7 +4009,7 @@ class RdsServiceTest {
assertTrue(rawClusters.get("cluster1").isPresent());
assertTrue(rawClusters.get(currentAccount + "/cluster1").isEmpty());
verify(proxyManager, never()).startProxy(
- any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any());
+ any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any(), any());
}
@Test
@@ -4115,7 +4115,7 @@ class RdsServiceTest {
assertEquals("insufficient-resource-limits", failed.getStatus());
verify(proxyManager, never()).startProxy(
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
- any(), anyInt(), any(), any(), any(), any());
+ any(), anyInt(), any(), any(), any(), any(), any());
DbProxy another = service.createDbProxy(
"another-proxy", "MYSQL", true, false, "NONE", PROXY_ROLE_ARN,
@@ -4135,7 +4135,7 @@ class RdsServiceTest {
verify(proxyManager).startProxy(
eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
anyBoolean(), eq(failed.getProxyPort()), any(), anyInt(),
- any(), any(), any(), any());
+ any(), any(), any(), any(), any());
}
@Test
@@ -4161,7 +4161,7 @@ class RdsServiceTest {
service.getDbProxy("app-proxy", "us-east-1").getStatus());
verify(proxyManager, never()).startProxy(
eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
- any(), anyInt(), any(), any(), any(), any());
+ any(), anyInt(), any(), any(), any(), any(), any());
}
@Test
@@ -4225,7 +4225,7 @@ class RdsServiceTest {
assertEquals("app-proxy", restored.getDbProxyName());
verify(restoredProxyManager).startProxy(eq("db-proxy:" + restored.getDbProxyArn()),
eq(DatabaseEngine.POSTGRES),
- eq(false), anyInt(), eq("127.0.0.1"), eq(15432),
+ eq(false), anyInt(), eq("127.0.0.1"), eq(15432), any(),
eq("admin"), eq("secret"), eq("app"), any());
}
@@ -4297,7 +4297,7 @@ class RdsServiceTest {
ArgumentCaptor.forClass(RdsAuthProxy.PasswordValidator.class);
verify(restoredProxyManager).startProxy(eq("db-proxy:" + proxy.getDbProxyArn()),
eq(DatabaseEngine.POSTGRES),
- eq(false), eq(5432), eq("127.0.0.1"), eq(15432), eq("admin"),
+ eq(false), eq(5432), eq("127.0.0.1"), eq(15432), any(), eq("admin"),
eq("target-secret"), eq("app"), validator.capture());
assertTrue(validator.getValue().validate("admin", "target-secret"));
assertFalse(validator.getValue().validate("admin", "default-secret"));
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java
new file mode 100644
index 0000000000..141f4ed131
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java
@@ -0,0 +1,467 @@
+package io.github.hectorvent.floci.services.rds.proxy;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.cert.X509Certificate;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class MySqlProtocolHandlerTest {
+
+ private static final int CLIENT_PROTOCOL_41 = 0x0200;
+ private static final int CLIENT_SECURE_CONNECTION = 0x8000;
+ private static final int CLIENT_SSL = 0x0800;
+
+ @TempDir
+ Path tempDir;
+
+ @Test
+ void forwardsPlaintextHandshakeResponseUnmodifiedWhenClientDoesNotRequestTls() throws Exception {
+ byte[] nonce = fixedNonce();
+ AtomicReference<Byte> backendResponseSeq = new AtomicReference<>();
+ AtomicReference<byte[]> backendResponsePayload = new AtomicReference<>();
+
+ try (ServerSocket backendServer = new ServerSocket(0);
+ ServerSocket clientServer = new ServerSocket(0)) {
+
+ Thread backendThread = Thread.ofVirtual().start(() -> {
+ try {
+ mockMySqlBackend(backendServer, nonce, backendResponseSeq, backendResponsePayload);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
+ Socket proxyClient = clientServer.accept();
+ Socket backend = new Socket("localhost", backendServer.getLocalPort());
+
+ Thread authThread = Thread.ofVirtual().start(() -> {
+ try {
+ MySqlProtocolHandler.handleAuth(
+ proxyClient, backend, "admin", "secret",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ InputStream clientIn = ourClient.getInputStream();
+ OutputStream clientOut = ourClient.getOutputStream();
+
+ byte[] serverHandshake = readMysqlPacketRaw(clientIn);
+ assertNotNull(serverHandshake);
+ // The proxy forces CLIENT_SSL even though the mock backend didn't advertise it.
+ assertTrue((capabilityFlagsLower(serverHandshake) & CLIENT_SSL) != 0);
+
+ byte[] scramble = scrambleNativePassword("secret", nonce);
+ byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 1);
+ clientOut.write(response);
+ clientOut.flush();
+
+ // Wait for the backend's OK packet to come back through the bridge before tearing
+ // down sockets, so we don't race the proxy mid-relay.
+ assertNotNull(readMysqlPacketRaw(clientIn));
+
+ ourClient.close();
+ proxyClient.close();
+ authThread.join(5_000);
+ backendThread.join(5_000);
+ assertEquals(false, authThread.isAlive(), "authThread did not terminate");
+ assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
+ }
+ }
+
+ assertEquals((byte) 1, backendResponseSeq.get(), "sequence must be unchanged when no TLS upgrade occurs");
+ assertEquals("admin", extractUsername(backendResponsePayload.get()));
+ }
+
+ @Test
+ void upgradesToTlsOnSslRequestAndRenumbersSequenceBeforeForwardingToBackend() throws Exception {
+ byte[] nonce = fixedNonce();
+ AtomicReference<Byte> backendResponseSeq = new AtomicReference<>();
+ AtomicReference<byte[]> backendResponsePayload = new AtomicReference<>();
+ RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
+ tlsCertificates.ensureHost("172.17.0.6");
+
+ try (ServerSocket backendServer = new ServerSocket(0);
+ ServerSocket clientServer = new ServerSocket(0)) {
+
+ Thread backendThread = Thread.ofVirtual().start(() -> {
+ try {
+ mockMySqlBackend(backendServer, nonce, backendResponseSeq, backendResponsePayload);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
+ Socket proxyClient = clientServer.accept();
+ Socket backend = new Socket("localhost", backendServer.getLocalPort());
+
+ Thread authThread = Thread.ofVirtual().start(() -> {
+ try {
+ MySqlProtocolHandler.handleAuth(
+ proxyClient, backend, "admin", "secret",
+ false, testSigV4Validator(), tlsCertificates,
+ (user, pass) -> true);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ InputStream clientIn = ourClient.getInputStream();
+ OutputStream clientOut = ourClient.getOutputStream();
+
+ byte[] serverHandshake = readMysqlPacketRaw(clientIn);
+ assertNotNull(serverHandshake);
+ assertTrue((capabilityFlagsLower(serverHandshake) & CLIENT_SSL) != 0);
+
+ // SSLRequest: 32-byte payload, CLIENT_SSL set, sequence 1 (right after the server's
+ // handshake at sequence 0).
+ clientOut.write(buildSslRequest());
+ clientOut.flush();
+
+ SSLSocket sslClient = trustedClientSocket(ourClient);
+ sslClient.startHandshake();
+ InputStream tlsIn = sslClient.getInputStream();
+ OutputStream tlsOut = sslClient.getOutputStream();
+
+ byte[] scramble = scrambleNativePassword("secret", nonce);
+ // Real clients send this at sequence 2 after the TLS upgrade — the proxy must
+ // rewrite it to 1 before forwarding to the (plaintext-only) backend.
+ byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2);
+ tlsOut.write(response);
+ tlsOut.flush();
+
+ // The mock backend replies with sequence 2 (its own view of the shared counter);
+ // the client, having sent its SSLRequest at sequence 1, expects that reply at 3.
+ byte[] okPacket = readMysqlPacketRaw(tlsIn);
+ assertNotNull(okPacket);
+ assertEquals((byte) 3, okPacket[3],
+ "client sent SSLRequest(1) then response(2), so it expects the backend's "
+ + "reply at sequence 3, not the backend's own sequence 2");
+
+ ourClient.close();
+ proxyClient.close();
+ authThread.join(5_000);
+ backendThread.join(5_000);
+ assertEquals(false, authThread.isAlive(), "authThread did not terminate");
+ assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
+ }
+ }
+
+ assertEquals((byte) 1, backendResponseSeq.get(),
+ "backend never saw the SSLRequest, so it must receive the real response at sequence 1");
+ assertEquals("admin", extractUsername(backendResponsePayload.get()));
+ }
+
+ @Test
+ void fastAuthSuccessDoesNotBlockWaitingForAClientReply() throws Exception {
+ byte[] nonce = fixedNonce();
+ RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
+ tlsCertificates.ensureHost("172.17.0.7");
+
+ try (ServerSocket backendServer = new ServerSocket(0);
+ ServerSocket clientServer = new ServerSocket(0)) {
+
+ Thread backendThread = Thread.ofVirtual().start(() -> {
+ try (Socket socket = backendServer.accept()) {
+ OutputStream out = socket.getOutputStream();
+ InputStream in = socket.getInputStream();
+
+ out.write(buildHandshakeV10(nonce));
+ out.flush();
+
+ readMysqlPacketRaw(in); // the real HandshakeResponse41, forwarded at sequence 1
+
+ // caching_sha2_password fast-auth success: AuthMoreData(0x03) immediately
+ // followed by the terminal OK — the client sends nothing back in between.
+ writeMysqlPacket(out, 2, new byte[]{0x01, 0x03});
+ writeMysqlPacket(out, 3, new byte[]{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00});
+ out.flush();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
+ Socket proxyClient = clientServer.accept();
+ Socket backend = new Socket("localhost", backendServer.getLocalPort());
+
+ Thread authThread = Thread.ofVirtual().start(() -> {
+ try {
+ MySqlProtocolHandler.handleAuth(
+ proxyClient, backend, "admin", "secret",
+ false, testSigV4Validator(), tlsCertificates,
+ (user, pass) -> true);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ InputStream clientIn = ourClient.getInputStream();
+ OutputStream clientOut = ourClient.getOutputStream();
+
+ assertNotNull(readMysqlPacketRaw(clientIn));
+
+ clientOut.write(buildSslRequest());
+ clientOut.flush();
+
+ SSLSocket sslClient = trustedClientSocket(ourClient);
+ sslClient.startHandshake();
+ InputStream tlsIn = sslClient.getInputStream();
+ OutputStream tlsOut = sslClient.getOutputStream();
+
+ byte[] scramble = scrambleNativePassword("secret", nonce);
+ byte[] response = buildHandshakeResponse41("admin", scramble, (byte) 2);
+ tlsOut.write(response);
+ tlsOut.flush();
+
+ // Neither packet should require anything further from the client — if the proxy
+ // wrongly waits for a client reply after AuthMoreData(0x03), this blocks until the
+ // join timeout below fails the test.
+ byte[] authMoreData = readMysqlPacketRaw(tlsIn);
+ assertNotNull(authMoreData);
+ assertEquals((byte) 0x01, authMoreData[4], "expected AuthMoreData");
+
+ byte[] okPacket = readMysqlPacketRaw(tlsIn);
+ assertNotNull(okPacket);
+ assertEquals((byte) 0x00, okPacket[4], "expected the terminal OK packet");
+
+ ourClient.close();
+ proxyClient.close();
+ authThread.join(5_000);
+ backendThread.join(5_000);
+ assertEquals(false, authThread.isAlive(), "authThread did not terminate");
+ assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
+ }
+ }
+ }
+
+ private RdsProxyTlsCertificates testTlsCertificates() {
+ EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
+ when(storage.persistentPath()).thenReturn(tempDir.toString());
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ when(config.storage()).thenReturn(storage);
+ return new RdsProxyTlsCertificates(config, new CertificateGenerator());
+ }
+
+ private static RdsSigV4Validator testSigV4Validator() {
+ return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
+ }
+
+ private static SSLSocket trustedClientSocket(Socket socket) throws Exception {
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, new TrustManager[]{new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) {}
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) {}
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ }}, null);
+ SSLSocket sslSocket = (SSLSocket) context.getSocketFactory()
+ .createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
+ sslSocket.setUseClientMode(true);
+ return sslSocket;
+ }
+
+ private static void mockMySqlBackend(ServerSocket server, byte[] nonce,
+ AtomicReference<Byte> responseSeq,
+ AtomicReference<byte[]> responsePayload) throws IOException {
+ try (Socket socket = server.accept()) {
+ OutputStream out = socket.getOutputStream();
+ InputStream in = socket.getInputStream();
+
+ out.write(buildHandshakeV10(nonce));
+ out.flush();
+
+ byte[] responseRaw = readMysqlPacketRaw(in);
+ responseSeq.set(responseRaw[3]);
+ byte[] payload = new byte[responseRaw.length - 4];
+ System.arraycopy(responseRaw, 4, payload, 0, payload.length);
+ responsePayload.set(payload);
+
+ writeMysqlPacket(out, 2, new byte[]{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00}); // OK packet
+ out.flush();
+ }
+ }
+
+ // ── MySQL Handshake V10 (server -> client) ──────────────────────────────
+
+ private static byte[] buildHandshakeV10(byte[] nonce) throws IOException {
+ ByteArrayOutputStream payload = new ByteArrayOutputStream();
+ payload.write(10); // protocol version
+ payload.write("8.0.34".getBytes(StandardCharsets.UTF_8));
+ payload.write(0);
+ writeInt32LE(payload, 1); // connection id
+ payload.write(nonce, 0, 8); // auth-plugin-data part 1
+ payload.write(0); // filler
+ int capsLower = (CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION) & 0xFFFF; // no CLIENT_SSL
+ writeInt16LE(payload, capsLower);
+ payload.write(0x21); // charset
+ writeInt16LE(payload, 0x0002); // status flags
+ writeInt16LE(payload, 0); // capability flags upper
+ payload.write(0); // auth-plugin-data length (not advertised)
+ payload.write(new byte[10]); // reserved
+ payload.write(nonce, 8, 12); // auth-plugin-data part 2 (12 bytes)
+ payload.write(0); // null terminator
+
+ return wrapPacket(0, payload.toByteArray());
+ }
+
+ // ── MySQL SSLRequest / HandshakeResponse41 (client -> server) ───────────
+
+ private static byte[] buildSslRequest() throws IOException {
+ ByteArrayOutputStream payload = new ByteArrayOutputStream();
+ writeInt32LE(payload, CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_SSL);
+ writeInt32LE(payload, 0); // max packet size
+ payload.write(0x21); // charset
+ payload.write(new byte[23]); // reserved
+ return wrapPacket(1, payload.toByteArray());
+ }
+
+ private static byte[] buildHandshakeResponse41(String username, byte[] scramble, byte sequence)
+ throws IOException {
+ ByteArrayOutputStream payload = new ByteArrayOutputStream();
+ writeInt32LE(payload, CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION);
+ writeInt32LE(payload, 0); // max packet size
+ payload.write(0x21); // charset
+ payload.write(new byte[23]); // reserved
+ payload.write(username.getBytes(StandardCharsets.UTF_8));
+ payload.write(0);
+ payload.write(scramble.length); // CLIENT_SECURE_CONNECTION: 1-byte length prefix
+ payload.write(scramble);
+
+ return wrapPacket(sequence, payload.toByteArray());
+ }
+
+ private static String extractUsername(byte[] payload) {
+ int i = 4 + 4 + 1 + 23; // caps + max-packet-size + charset + reserved
+ int start = i;
+ while (i < payload.length && payload[i] != 0) {
+ i++;
+ }
+ return new String(payload, start, i - start, StandardCharsets.UTF_8);
+ }
+
+ private static int capabilityFlagsLower(byte[] handshakeRaw) {
+ int i = 4 + 1; // header + protocol version
+ while (i < handshakeRaw.length && handshakeRaw[i] != 0) {
+ i++;
+ }
+ i++; // null terminator
+ i += 4; // connection id
+ i += 8; // auth-plugin-data part 1
+ i++; // filler
+ return (handshakeRaw[i] & 0xFF) | ((handshakeRaw[i + 1] & 0xFF) << 8);
+ }
+
+ private static byte[] fixedNonce() {
+ byte[] nonce = new byte[20];
+ for (int i = 0; i < nonce.length; i++) {
+ nonce[i] = (byte) (i + 1);
+ }
+ return nonce;
+ }
+
+ private static byte[] scrambleNativePassword(String password, byte[] nonce) throws Exception {
+ MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
+ byte[] hash1 = sha1.digest(password.getBytes(StandardCharsets.UTF_8));
+ sha1.reset();
+ byte[] hash2 = sha1.digest(hash1);
+ sha1.reset();
+ sha1.update(nonce);
+ sha1.update(hash2);
+ byte[] hash3 = sha1.digest();
+
+ byte[] result = new byte[20];
+ for (int i = 0; i < 20; i++) {
+ result[i] = (byte) (hash1[i] ^ hash3[i]);
+ }
+ return result;
+ }
+
+ // ── Raw packet helpers ───────────────────────────────────────────────────
+
+ private static byte[] wrapPacket(int sequence, byte[] payload) {
+ byte[] raw = new byte[4 + payload.length];
+ int len = payload.length;
+ raw[0] = (byte) (len & 0xFF);
+ raw[1] = (byte) ((len >> 8) & 0xFF);
+ raw[2] = (byte) ((len >> 16) & 0xFF);
+ raw[3] = (byte) sequence;
+ System.arraycopy(payload, 0, raw, 4, payload.length);
+ return raw;
+ }
+
+ private static void writeMysqlPacket(OutputStream out, int sequence, byte[] payload) throws IOException {
+ out.write(wrapPacket(sequence, payload));
+ }
+
+ private static byte[] readMysqlPacketRaw(InputStream in) throws IOException {
+ int b0 = in.read();
+ int b1 = in.read();
+ int b2 = in.read();
+ int seq = in.read();
+ if ((b0 | b1 | b2 | seq) < 0) {
+ return null;
+ }
+ int length = b0 | (b1 << 8) | (b2 << 16);
+ byte[] raw = new byte[4 + length];
+ raw[0] = (byte) b0;
+ raw[1] = (byte) b1;
+ raw[2] = (byte) b2;
+ raw[3] = (byte) seq;
+ int offset = 4;
+ while (offset < raw.length) {
+ int n = in.read(raw, offset, raw.length - offset);
+ if (n < 0) {
+ throw new EOFException("Connection closed while reading MySQL packet");
+ }
+ offset += n;
+ }
+ return raw;
+ }
+
+ private static void writeInt32LE(ByteArrayOutputStream out, int value) {
+ out.write(value & 0xFF);
+ out.write((value >> 8) & 0xFF);
+ out.write((value >> 16) & 0xFF);
+ out.write((value >> 24) & 0xFF);
+ }
+
+ private static void writeInt16LE(ByteArrayOutputStream out, int value) {
+ out.write(value & 0xFF);
+ out.write((value >> 8) & 0xFF);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
index 6b2fe076a8..9762f6ca08 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.services.rds.proxy;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
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.CsvSource;
@@ -12,23 +15,36 @@ import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLHandshakeException;
+import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
class PostgresProtocolHandlerTest {
private static final int SSL_REQUEST_CODE = 80877103;
private static final int STARTUP_PROTOCOL_VERSION = 196608;
+ @TempDir
+ Path tempDir;
+
@ParameterizedTest
@CsvSource({
"auth_db, postgres, auth_db",
@@ -68,7 +84,7 @@ class PostgresProtocolHandlerTest {
PostgresProtocolHandler.handleAuth(
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
- false, testSigV4Validator(),
+ false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -122,7 +138,7 @@ class PostgresProtocolHandlerTest {
PostgresProtocolHandler.handleAuth(
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
- false, testSigV4Validator(),
+ false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -176,7 +192,7 @@ class PostgresProtocolHandlerTest {
PostgresProtocolHandler.handleAuth(
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
- false, testSigV4Validator(),
+ false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -212,6 +228,106 @@ class PostgresProtocolHandlerTest {
}
}
+ @Test
+ void hostnameVerificationSucceedsForRegisteredAdvertisedHost() throws Exception {
+ try (ServerSocket backendServer = new ServerSocket(0);
+ ServerSocket clientServer = new ServerSocket(0)) {
+
+ RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
+ String advertisedHost = "172.17.0.5";
+ tlsCertificates.ensureHost(advertisedHost);
+
+ int backendPort = backendServer.getLocalPort();
+ Thread backendThread = Thread.ofVirtual().start(() -> {
+ try {
+ mockBackendStartup(backendServer, new AtomicReference<>(), false);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
+ Socket proxyClient = clientServer.accept();
+ Socket backend = new Socket("localhost", backendPort);
+
+ Thread authThread = Thread.ofVirtual().start(() -> {
+ try {
+ PostgresProtocolHandler.handleAuth(
+ proxyClient, backend,
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), tlsCertificates,
+ (user, pass) -> true);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
+ DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
+
+ writeSslRequest(clientOut);
+ assertEquals('S', clientIn.readUnsignedByte());
+
+ Path caCertFile = tempDir.resolve("tls").resolve("rds-ca.crt");
+ SSLSocket sslClient = verifyingClientSocket(ourClient, caCertFile, advertisedHost);
+ sslClient.startHandshake(); // must not throw — advertisedHost is in the cert's SAN
+
+ proxyClient.close();
+ authThread.join(5_000);
+ backendThread.join(5_000);
+ }
+ }
+ }
+
+ @Test
+ void hostnameVerificationFailsForUnregisteredAdvertisedHost() throws Exception {
+ try (ServerSocket backendServer = new ServerSocket(0);
+ ServerSocket clientServer = new ServerSocket(0)) {
+
+ RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
+ tlsCertificates.ensureHost("172.17.0.5");
+
+ int backendPort = backendServer.getLocalPort();
+ Thread backendThread = Thread.ofVirtual().start(() -> {
+ try {
+ mockBackendStartup(backendServer, new AtomicReference<>(), false);
+ } catch (IOException e) {
+ // Backend connection is torn down before completing startup — expected here.
+ }
+ });
+
+ try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
+ Socket proxyClient = clientServer.accept();
+ Socket backend = new Socket("localhost", backendPort);
+
+ Thread authThread = Thread.ofVirtual().start(() -> {
+ try {
+ PostgresProtocolHandler.handleAuth(
+ proxyClient, backend,
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), tlsCertificates,
+ (user, pass) -> true);
+ } catch (IOException ignored) {
+ // Client aborts the handshake below — the handler observing that is expected.
+ }
+ });
+
+ DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
+ DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
+
+ writeSslRequest(clientOut);
+ assertEquals('S', clientIn.readUnsignedByte());
+
+ Path caCertFile = tempDir.resolve("tls").resolve("rds-ca.crt");
+ SSLSocket sslClient = verifyingClientSocket(ourClient, caCertFile, "never-registered.example.com");
+ assertThrows(SSLHandshakeException.class, sslClient::startHandshake);
+
+ proxyClient.close();
+ authThread.join(5_000);
+ }
+ }
+ }
+
@Test
void closesClientWhenBackendClosesDuringBridge() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0);
@@ -235,7 +351,7 @@ class PostgresProtocolHandlerTest {
PostgresProtocolHandler.handleAuth(
proxyClient, backend,
"dbadmin", "adminpass", "postgres",
- false, testSigV4Validator(),
+ false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> true);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -266,6 +382,44 @@ class PostgresProtocolHandlerTest {
return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));
}
+ private RdsProxyTlsCertificates testTlsCertificates() {
+ EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
+ when(storage.persistentPath()).thenReturn(tempDir.toString());
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ when(config.storage()).thenReturn(storage);
+ return new RdsProxyTlsCertificates(config, new CertificateGenerator());
+ }
+
+ /**
+ * Wraps {@code socket} in a client-side {@link SSLSocket} that trusts only {@code caCertFile}
+ * and enforces standard HTTPS-style hostname verification against {@code advertisedHost} —
+ * the same SAN-matching behavior libpq performs for {@code sslmode=verify-full}.
+ */
+ private static SSLSocket verifyingClientSocket(Socket socket, Path caCertFile, String advertisedHost)
+ throws Exception {
+ X509Certificate ca;
+ try (var in = Files.newInputStream(caCertFile)) {
+ ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in);
+ }
+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ trustStore.load(null, null);
+ trustStore.setCertificateEntry("rds-ca", ca);
+
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(trustStore);
+
+ SSLContext context = SSLContext.getInstance("TLS");
+ context.init(null, tmf.getTrustManagers(), null);
+
+ SSLSocket sslSocket = (SSLSocket) context.getSocketFactory()
+ .createSocket(socket, advertisedHost, socket.getPort(), true);
+ sslSocket.setUseClientMode(true);
+ SSLParameters params = sslSocket.getSSLParameters();
+ params.setEndpointIdentificationAlgorithm("HTTPS");
+ sslSocket.setSSLParameters(params);
+ return sslSocket;
+ }
+
private static void mockBackendStartup(ServerSocket server, AtomicReference<String> backendDatabase,
boolean failWithError) throws IOException {
try (Socket socket = server.accept()) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java
index bf2878318f..72704cb603 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java
@@ -22,7 +22,8 @@ class RdsProxyManagerTest {
@Test
void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int firstPort = availablePort();
try {
start(manager, "proxy", firstPort);
@@ -41,7 +42,8 @@ class RdsProxyManagerTest {
@Test
void registrationFailureAfterBindReleasesCandidateListener() throws IOException {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int proxyPort = availablePort();
try {
assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort));
@@ -54,7 +56,8 @@ class RdsProxyManagerTest {
@Test
void failedReplacementPreservesOriginalRegistryEntry() throws IOException {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int originalPort = availablePort();
try {
start(manager, "proxy", originalPort);
@@ -73,7 +76,8 @@ class RdsProxyManagerTest {
@Test
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int firstPort = availablePort();
start(manager, "first", firstPort);
int secondPort = availablePort();
@@ -88,7 +92,8 @@ class RdsProxyManagerTest {
@Test
void closeFailurePropagatesAndManagerRetainsOwnership() throws Exception {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
RdsAuthProxy proxy = authProxy("proxy");
ServerSocket serverSocket = mock(ServerSocket.class);
IOException closeFailure = new IOException("simulated close failure");
@@ -107,7 +112,8 @@ class RdsProxyManagerTest {
@Test
void failedPreviousStopRestoresMappingAndReleasesCandidate() throws Exception {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
RdsAuthProxy previous = mock(RdsAuthProxy.class);
doThrow(new IllegalStateException("simulated previous stop failure"))
.when(previous).stop();
@@ -124,7 +130,8 @@ class RdsProxyManagerTest {
@Test
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
- RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
+ RdsProxyManager manager = new RdsProxyManager(
+ mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
int successfulPort = availablePort();
start(manager, "successful", successfulPort);
RdsAuthProxy failed = mock(RdsAuthProxy.class);
@@ -143,13 +150,13 @@ class RdsProxyManagerTest {
private static void start(RdsProxyManager manager, String key, int proxyPort) {
manager.startProxy(key, DatabaseEngine.POSTGRES, false, proxyPort,
- "localhost", 1, "admin", "secret", "app", (user, password) -> true);
+ "localhost", 1, "localhost", "admin", "secret", "app", (user, password) -> true);
}
private static RdsAuthProxy authProxy(String key) {
return new RdsAuthProxy(key, "localhost", 1, DatabaseEngine.POSTGRES, false,
"admin", "secret", "app", mock(RdsSigV4Validator.class),
- (user, password) -> true);
+ mock(RdsProxyTlsCertificates.class), (user, password) -> true);
}
private static void setServerSocket(RdsAuthProxy proxy, ServerSocket socket) throws Exception {
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java
new file mode 100644
index 0000000000..7014a46fe5
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java
@@ -0,0 +1,133 @@
+package io.github.hectorvent.floci.services.rds.proxy;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import javax.net.ssl.SSLContext;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class RdsProxyTlsCertificatesTest {
+
+ @TempDir
+ Path tempDir;
+
+ @Test
+ void ensureHostIsIdempotentWhenHostAlreadyCovered() {
+ RdsProxyTlsCertificates certs = newCertificates();
+ certs.ensureHost("172.17.0.5");
+ SSLContext firstContext = certs.sslContext();
+
+ certs.ensureHost("172.17.0.5");
+
+ assertSame(firstContext, certs.sslContext(), "no regeneration for an already-covered host");
+ }
+
+ @Test
+ void ensureHostRegeneratesWhenHostIsNew() {
+ RdsProxyTlsCertificates certs = newCertificates();
+ certs.ensureHost("172.17.0.5");
+ SSLContext firstContext = certs.sslContext();
+
+ certs.ensureHost("host.docker.internal");
+
+ assertNotSame(firstContext, certs.sslContext(), "a genuinely new host must trigger regeneration");
+ }
+
+ @Test
+ void persistsAndReloadsSansAcrossInstances() throws Exception {
+ RdsProxyTlsCertificates first = newCertificates();
+ first.ensureHost("172.17.0.5");
+ first.ensureHost("host.docker.internal");
+
+ Path certFile = tempDir.resolve("tls").resolve("rds-ca.crt");
+ Path keyFile = tempDir.resolve("tls").resolve("rds-ca.key");
+ Path metadataFile = tempDir.resolve("tls").resolve("rds-ca.metadata.json");
+ assertTrue(Files.exists(certFile));
+ assertTrue(Files.exists(keyFile));
+ assertTrue(Files.exists(metadataFile));
+ String persistedCertPem = Files.readString(certFile);
+
+ // A fresh instance (simulating a restart) backed by the same persistent path must reuse
+ // the same cert rather than regenerating — otherwise a user's trusted sslrootcert goes stale
+ // on every restart even when no new host has appeared.
+ RdsProxyTlsCertificates reloaded = newCertificates();
+ reloaded.ensureHost("172.17.0.5");
+ reloaded.ensureHost("host.docker.internal");
+
+ assertEquals(persistedCertPem, Files.readString(certFile));
+ }
+
+ @Test
+ void growingSansReusesTheSameKeyPairSoOlderCertCopiesStillValidateNewOnes() throws Exception {
+ RdsProxyTlsCertificates certs = newCertificates();
+ certs.ensureHost("172.17.0.5");
+
+ CertificateGenerator generator = new CertificateGenerator();
+ var firstCertificate = generator.parseCertificate(
+ Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
+
+ certs.ensureHost("host.docker.internal");
+
+ var secondCertificate = generator.parseCertificate(
+ Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
+
+ assertEquals(firstCertificate.getPublicKey(), secondCertificate.getPublicKey(),
+ "growing the SAN list must reuse the existing key pair, not mint a new one, "
+ + "or a client that already trusts a prior copy of the CA loses trust");
+ assertDoesNotThrow(() -> secondCertificate.verify(firstCertificate.getPublicKey()),
+ "the old cert's public key must still validate the reissued cert's signature");
+ }
+
+ @Test
+ void privateKeyAndTlsDirAreRestrictedToOwnerOnly() throws Exception {
+ Path tlsDir = tempDir.resolve("tls");
+ assumeTrue(Files.getFileStore(tempDir).supportsFileAttributeView(PosixFileAttributeView.class),
+ "POSIX permissions are not supported on this filesystem");
+
+ RdsProxyTlsCertificates certs = newCertificates();
+ certs.ensureHost("172.17.0.5");
+
+ Path keyFile = tlsDir.resolve("rds-ca.key");
+ assertEquals(Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE),
+ Files.getPosixFilePermissions(keyFile),
+ "the CA private key must not be readable by anyone but the owner");
+ assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(tlsDir),
+ "the tls directory must not be traversable by anyone but the owner");
+ }
+
+ @Test
+ void generatedCertificateIsAGenuineTrustAnchor() throws Exception {
+ RdsProxyTlsCertificates certs = newCertificates();
+ certs.ensureHost("172.17.0.5");
+
+ CertificateGenerator generator = new CertificateGenerator();
+ var certificate = generator.parseCertificate(
+ Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt")));
+
+ assertEquals(certificate.getIssuerX500Principal(), certificate.getSubjectX500Principal());
+ }
+
+ private RdsProxyTlsCertificates newCertificates() {
+ EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
+ when(storage.persistentPath()).thenReturn(tempDir.toString());
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ when(config.storage()).thenReturn(storage);
+ return new RdsProxyTlsCertificates(config, new CertificateGenerator());
+ }
+}