fix(rds): refuse plaintext PostgreSQL connections when rds.force_ssl is 1 (#8663)

With rds.force_ssl set to 1 in a PostgreSQL instance's DB parameter group, or in an Aurora PostgreSQL cluster's DB cluster parameter group, the RDS auth proxy refuses a startup that did not negotiate TLS with FATAL "no pg_hba.conf entry for host ..., no encryption" (SQLSTATE 28000), before the password exchange and without opening a backend connection. The value is read from the current parameter group on every new connection, as the parameter is dynamic on AWS. On Aurora it comes from the cluster parameter group only, looked up in the account and Region the relay ARN names, for the cluster endpoint and member endpoints. RdsRequests.createPostgresInstance takes an optional DB parameter group, and the docs give the RDS and Aurora PostgreSQL versions whose default groups force SSL.

Closes #8641
This commit is contained in:
rajp33 authored and GitHub committed 2026-11-19 07:52:07 -04:00
1 parent 4c0f8237f6
commit 4d12c76411
9 files changed
+460 -18

No files matched your search

@@ -72,6 +72,7 @@ import io.floci.aws.services.rds.proxy.RdsProxyManager;
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -244,6 +245,8 @@ public class RdsService implements Resettable, ResourceProvider {
"MYSQL_NATIVE_PASSWORD", "MYSQL_CACHING_SHA2_PASSWORD",
"POSTGRES_SCRAM_SHA_256", "POSTGRES_MD5", "SQL_SERVER_AUTHENTICATION");
private static final String RDS_RESOURCE_RELAY_PREFIX = "rds-resource:";
public RdsService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
Ec2Service ec2Service,
@@ -498,6 +501,11 @@ public class RdsService implements Resettable, ResourceProvider {
this.clusterAutomatedBackups = new InMemoryStorage<>();
}
@PostConstruct
void registerForceSslPolicy() {
proxyManager.forceSslWhen(this::relayForcesSsl);
}
public void restorePersistedRuntime() {
Map<Integer, String> persistedPortOwners = reservePersistedProxyPorts();
restoreClusters(persistedPortOwners);
@@ -11147,7 +11155,38 @@ public class RdsService implements Resettable, ResourceProvider {
if (identity == null || identity.isBlank()) {
identity = currentAccountId() + ":" + resourceId;
}
return "rds-resource:" + identity;
return RDS_RESOURCE_RELAY_PREFIX + identity;
}
private boolean relayForcesSsl(String relayKey) {
if (!relayKey.startsWith(RDS_RESOURCE_RELAY_PREFIX)) {
return false;
}
String arn = relayKey.substring(RDS_RESOURCE_RELAY_PREFIX.length());
return AwsArnUtils.resourceIfArnFor(arn, "rds")
.map(resource -> relayEngineParameters(arn, resource))
.map(parameters -> "1".equals(parameters.get("rds.force_ssl")))
.orElse(false);
}
private Map<String, String> relayEngineParameters(String arn, String resource) {
String accountId = accountIdFromArn(arn);
String region = effectiveRegion(regionResolver.regionOf(arn));
DbCluster cluster;
if (resource.startsWith("cluster:")) {
cluster = findClusterForScope(accountId, region, resource.substring("cluster:".length()));
} else {
DbInstance instance = findInstanceByArnOrNull(accountId, region, arn);
if (instance == null) {
return Map.of();
}
if (instance.getDbClusterIdentifier() == null) {
return instanceEngineParameters(instance);
}
cluster = findClusterForScope(accountId, region, instance.getDbClusterIdentifier());
}
return cluster == null ? Map.of()
: clusterEngineParameters(accountId, region, cluster.getParameterGroupName());
}
private Collection<DbCluster> allClusters() {
@@ -31,7 +31,8 @@ import java.util.function.BiConsumer;
*
* <p>Flow:
* <ol>
* <li>Read client StartupMessage (handles PostgreSQL SSL negotiation)
* <li>Read client StartupMessage (handles PostgreSQL SSL negotiation), refusing one sent
* without TLS when {@code rds.force_ssl} requires it
* <li>Challenge client with AuthenticationCleartextPassword
* <li>Read client password
* <li>Validate (IAM SigV4 or plain password)
@@ -208,12 +209,26 @@ public class PostgresProtocolHandler {
boolean forwardStartupParameters, boolean databaseIamAuthentication,
StartupObserver startupObserver,
SessionRoleHandover roleHandover) throws IOException {
return authenticate(client, backendConnector, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, binding, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
forwardStartupParameters, databaseIamAuthentication, startupObserver, roleHandover, false);
}
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyBinding binding, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator, int handshakeTimeoutMillis,
boolean forwardStartupParameters, boolean databaseIamAuthentication,
StartupObserver startupObserver,
SessionRoleHandover roleHandover,
boolean requireSsl) throws IOException {
client.setSoTimeout(handshakeTimeoutMillis);
// Phase 1: Read client startup message (possibly preceded by SSL request)
StartupMessage startup = readStartupMessage(client, backendConnector, databaseIamAuthentication,
tlsCertificates, handshakeTimeoutMillis);
tlsCertificates, handshakeTimeoutMillis, requireSsl);
if (startup == null) {
closeQuietly(client);
return null;
@@ -609,7 +624,7 @@ public class PostgresProtocolHandler {
private static StartupMessage readStartupMessage(Socket socket, BackendConnector backendConnector,
boolean forwardCancel, RdsProxyTlsCertificates tlsCertificates,
int handshakeTimeoutMillis) throws IOException {
int handshakeTimeoutMillis, boolean requireSsl) throws IOException {
Socket currentSocket = socket;
while (true) {
InputStream in = currentSocket.getInputStream();
@@ -645,10 +660,15 @@ public class PostgresProtocolHandler {
}
Map<String, String> params = PostgresWire.startupParameters(startup.body());
return new StartupMessage(currentSocket,
params.getOrDefault("user", "postgres"),
params.get("database"),
params);
String user = params.getOrDefault("user", "postgres");
if (requireSsl && !(currentSocket instanceof SSLSocket)) {
sendErrorResponse(out, "FATAL", "28000", "no pg_hba.conf entry for host \""
+ currentSocket.getInetAddress().getHostAddress() + "\", user \"" + user
+ "\", database \"" + params.getOrDefault("database", user) + "\", no encryption");
out.flush();
return null;
}
return new StartupMessage(currentSocket, user, params.get("database"), params);
}
}
@@ -11,6 +11,7 @@ import java.net.ServerSocket;
import java.net.Socket;
import java.time.Duration;
import java.util.concurrent.Semaphore;
import java.util.function.BooleanSupplier;
/**
* TCP auth proxy for a single RDS DB instance or cluster.
@@ -45,6 +46,7 @@ public class RdsAuthProxy {
private final int backendConnectTimeoutMillis;
private final Semaphore connectionPermits;
private final RdsBackendGate backendGate;
private final BooleanSupplier forceSsl;
private volatile boolean running;
private ServerSocket serverSocket;
@@ -123,6 +125,24 @@ public class RdsAuthProxy {
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate, EndpointKind endpointKind) {
this(instanceId, backendHost, backendPort, backendEndpointResolver, backendRuntimeId,
engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, handshakeTimeoutMillis,
backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker,
backendGate, endpointKind, () -> false);
}
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
BackendEndpointResolver backendEndpointResolver, String backendRuntimeId,
DatabaseEngine engine, boolean iamEnabled,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
MasterPasswordCheck passwordValidator,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, RdsProxyBinding binding,
MySqlProtocolHandler.IamUserChecker iamUserChecker,
RdsBackendGate backendGate, EndpointKind endpointKind,
BooleanSupplier forceSsl) {
if (backendRuntimeId == null || backendRuntimeId.isBlank()) {
throw new IllegalArgumentException("RDS backend runtime ID is required");
}
@@ -146,6 +166,7 @@ public class RdsAuthProxy {
this.backendConnectTimeoutMillis = backendConnectTimeoutMillis;
this.connectionPermits = new Semaphore(Math.max(1, maxConnections));
this.backendGate = backendGate;
this.forceSsl = forceSsl;
}
public void start(int proxyPort) throws IOException {
@@ -268,7 +289,8 @@ public class RdsAuthProxy {
session = PostgresProtocolHandler.authenticate(
client, connector, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, binding, tlsCertificates, authAdapter,
handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE);
handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE,
(user, database, parameters) -> { }, null, forceSsl.getAsBoolean());
if (session != null) {
PostgresProtocolHandler.bridge(session);
}
@@ -14,6 +14,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
/**
* Registry of all active RDS auth proxies. One proxy per DB instance or cluster.
@@ -30,6 +31,7 @@ public class RdsProxyManager {
private final RdsContainerManager containerManager;
private final ConcurrentHashMap<String, RdsAuthProxy> proxies = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, RdsAuthProxy> pendingFailedStarts = new ConcurrentHashMap<>();
private volatile Predicate<String> forceSsl = instanceId -> false;
@Inject
public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
@@ -107,7 +109,8 @@ public class RdsProxyManager {
engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4Validator,
tlsCertificates, passwordValidator, rdsConfig.proxyHandshakeTimeoutMillis(),
rdsConfig.proxyBackendConnectTimeoutMillis(), rdsConfig.proxyMaxConnections(),
binding, username -> binding != null, backendGate, endpointKind);
binding, username -> binding != null, backendGate, endpointKind,
() -> forceSsl.test(instanceId));
try {
proxy.start(proxyPort);
} catch (IOException e) {
@@ -152,6 +155,10 @@ public class RdsProxyManager {
}
}
public void forceSslWhen(Predicate<String> forceSsl) {
this.forceSsl = forceSsl;
}
public synchronized void updateMasterPassword(String instanceId, String newPassword) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {