mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(rds): match proxy TLS cert SAN to the advertised endpoint (#2603)
Persists a shared self-signed CA whose SAN list grows to cover every advertised RDS host, enabling sslmode=verify-full / VERIFY_IDENTITY for both Postgres and MySQL proxy connections. Reissuing the CA for a new host now reuses its existing key pair instead of minting a new one, so a client that already trusts a prior copy keeps validating connections as the SAN list grows. The MySQL TLS upgrade path also renumbers every packet through the rest of the connection phase (not just the first), since the backend's sequence counter stays one behind the client's for as long as that phase lasts. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
e0bf1929e1
commit
b1d7286444
13 files changed
+1308
-152
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
+188
-13
@@ -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 ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
+7
-85
@@ -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) {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+245
@@ -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";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user