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

@@ -438,6 +438,66 @@ class PostgresProtocolHandlerTest {
}
}
@Test
void forceSslRefusesPlaintextStartupBeforeContactingTheBackend() throws Exception {
try (ServerSocket clientServer = new ServerSocket(0);
Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort());
Socket proxyClient = acceptTestSocket(clientServer)) {
AtomicReference<Object> outcome = new AtomicReference<>();
Thread authThread = Thread.ofVirtual().start(() -> outcome.set(authenticateRequiringSsl(proxyClient)));
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
writeStartup(clientOut, "dbadmin", "appdb");
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
Map<Character, String> error = readErrorResponse(clientIn);
assertEquals("FATAL", error.get('S'));
assertEquals("28000", error.get('C'));
assertEquals("no pg_hba.conf entry for host \"" + ourClient.getLocalAddress().getHostAddress()
+ "\", user \"dbadmin\", database \"appdb\", no encryption", error.get('M'));
assertEquals(-1, clientIn.read(), "the proxy closes the refused connection");
authThread.join(5_000);
assertFalse(authThread.isAlive(), "authThread did not terminate");
assertEquals("no session", outcome.get());
}
}
@Test
void forceSslAcceptsStartupOverTls() throws Exception {
try (ServerSocket clientServer = new ServerSocket(0);
Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort());
Socket proxyClient = acceptTestSocket(clientServer)) {
Thread authThread = Thread.ofVirtual().start(() -> authenticateRequiringSsl(proxyClient));
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
writeSslRequest(clientOut);
assertEquals('S', new DataInputStream(ourClient.getInputStream()).readUnsignedByte());
try (SSLSocket sslClient = trustedClientSocket(ourClient)) {
sslClient.startHandshake();
writeStartup(new DataOutputStream(sslClient.getOutputStream()), "dbadmin", "appdb");
readCleartextPasswordChallenge(new DataInputStream(sslClient.getInputStream()));
} finally {
authThread.join(5_000);
assertFalse(authThread.isAlive(), "authThread did not terminate");
}
}
}
private Object authenticateRequiringSsl(Socket proxyClient) {
try {
PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate(
proxyClient, NEVER_CONNECT, "dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testBinding(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000,
true, true, (user, database, parameters) -> { }, null, true);
return session == null ? "no session" : session;
} catch (IOException e) {
return e;
}
}
@Test
void acceptsPostgresSslRequestAndContinuesStartup() throws Exception {
AtomicReference<String> backendDatabase = new AtomicReference<>();
@@ -0,0 +1,181 @@
package io.floci.aws.services.rds.proxy;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import static io.floci.aws.testing.RdsRequests.assumeDocker;
import static io.floci.aws.testing.RdsRequests.createPostgresInstance;
import static io.floci.aws.testing.RdsRequests.deleteInstance;
import static io.floci.aws.testing.RdsRequests.rds;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@Tag("docker")
class RdsPostgresForceSslIntegrationTest {
private static final String MASTER_USER = "master";
private static final String MASTER_PASSWORD = "Master123!";
@BeforeEach
void checkDocker() throws InterruptedException {
assumeDocker();
}
@BeforeEach
void registerPostgresDriver() throws ClassNotFoundException {
Class.forName("org.postgresql.Driver");
}
@Test
void instanceParameterGroupForceSslFollowsGroupChangesOnARunningInstance() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String group = "force-ssl-" + suffix;
String dbId = "force-ssl-" + suffix;
createInstanceParameterGroup(group, "postgres16");
try {
int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, false, group);
assertThat(selectOne(port, "disable"), equalTo(1));
setInstanceForceSsl(group, "1");
assertPlaintextRefused(port);
assertThat(selectOne(port, "require"), equalTo(1));
setInstanceForceSsl(group, "0");
assertThat(selectOne(port, "disable"), equalTo(1));
} finally {
deleteInstance(dbId);
deleteInstanceParameterGroup(group);
}
}
@ParameterizedTest
@ValueSource(strings = {"test", "222222222222"})
void auroraClusterParameterGroupForceSslRefusesPlaintextOnClusterAndMemberEndpoints(String accessKey)
throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String clusterGroup = "force-ssl-cpg-" + suffix;
String memberGroup = "force-ssl-mpg-" + suffix;
String clusterId = "force-ssl-cluster-" + suffix;
String memberId = clusterId + "-member";
rds("CreateDBClusterParameterGroup", accessKey)
.formParam("DBClusterParameterGroupName", clusterGroup)
.formParam("DBParameterGroupFamily", "aurora-postgresql16")
.formParam("Description", "force ssl")
.when().post("/").then().statusCode(200);
createInstanceParameterGroup(memberGroup, "aurora-postgresql16", accessKey);
try {
rds("ModifyDBClusterParameterGroup", accessKey)
.formParam("DBClusterParameterGroupName", clusterGroup)
.formParam("Parameters.member.1.ParameterName", "rds.force_ssl")
.formParam("Parameters.member.1.ParameterValue", "1")
.formParam("Parameters.member.1.ApplyMethod", "immediate")
.when().post("/").then().statusCode(200);
setInstanceForceSsl(memberGroup, "0", accessKey);
int clusterPort = rds("CreateDBCluster", accessKey)
.formParam("DBClusterIdentifier", clusterId)
.formParam("Engine", "aurora-postgresql")
.formParam("DBClusterParameterGroupName", clusterGroup)
.formParam("MasterUsername", MASTER_USER)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.when().post("/").then().statusCode(200).extract().xmlPath()
.getInt("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.Port");
int memberPort = rds("CreateDBInstance", accessKey)
.formParam("DBInstanceIdentifier", memberId)
.formParam("DBClusterIdentifier", clusterId)
.formParam("DBInstanceClass", "db.r5.large")
.formParam("Engine", "aurora-postgresql")
.formParam("DBParameterGroupName", memberGroup)
.when().post("/").then().statusCode(200).extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
assertPlaintextRefused(clusterPort);
assertThat(selectOne(clusterPort, "require"), equalTo(1));
assertPlaintextRefused(memberPort);
assertThat(selectOne(memberPort, "require"), equalTo(1));
} finally {
rds("DeleteDBInstance", accessKey)
.formParam("DBInstanceIdentifier", memberId)
.formParam("SkipFinalSnapshot", "true")
.when().post("/");
rds("DeleteDBCluster", accessKey)
.formParam("DBClusterIdentifier", clusterId)
.formParam("SkipFinalSnapshot", "true")
.when().post("/");
rds("DeleteDBClusterParameterGroup", accessKey)
.formParam("DBClusterParameterGroupName", clusterGroup)
.when().post("/");
deleteInstanceParameterGroup(memberGroup, accessKey);
}
}
private static void createInstanceParameterGroup(String group, String family) {
createInstanceParameterGroup(group, family, "test");
}
private static void createInstanceParameterGroup(String group, String family, String accessKey) {
rds("CreateDBParameterGroup", accessKey)
.formParam("DBParameterGroupName", group)
.formParam("DBParameterGroupFamily", family)
.formParam("Description", "force ssl")
.when().post("/").then().statusCode(200);
}
private static void deleteInstanceParameterGroup(String group) {
deleteInstanceParameterGroup(group, "test");
}
private static void deleteInstanceParameterGroup(String group, String accessKey) {
rds("DeleteDBParameterGroup", accessKey)
.formParam("DBParameterGroupName", group)
.when().post("/");
}
private static void setInstanceForceSsl(String group, String value) {
setInstanceForceSsl(group, value, "test");
}
private static void setInstanceForceSsl(String group, String value, String accessKey) {
rds("ModifyDBParameterGroup", accessKey)
.formParam("DBParameterGroupName", group)
.formParam("Parameters.member.1.ParameterName", "rds.force_ssl")
.formParam("Parameters.member.1.ParameterValue", value)
.formParam("Parameters.member.1.ApplyMethod", "immediate")
.when().post("/").then().statusCode(200);
}
private static void assertPlaintextRefused(int port) {
SQLException refused = assertThrows(SQLException.class, () -> selectOne(port, "disable"));
assertThat(refused.getSQLState(), equalTo("28000"));
assertThat(refused.getMessage(), containsString("no pg_hba.conf entry"));
assertThat(refused.getMessage(), containsString("no encryption"));
}
private static int selectOne(int port, String sslMode) throws SQLException {
Properties properties = new Properties();
properties.setProperty("user", MASTER_USER);
properties.setProperty("password", MASTER_PASSWORD);
properties.setProperty("sslmode", sslMode);
try (Connection connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:" + port + "/postgres", properties);
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT 1")) {
result.next();
return result.getInt(1);
}
}
}
@@ -29,8 +29,12 @@ public final class RdsRequests {
private RdsRequests() {}
public static RequestSpecification rds(String action) {
return rds(action, "test");
}
public static RequestSpecification rds(String action, String accessKey) {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20261011/us-east-1/rds/aws4_request")
"AWS4-HMAC-SHA256 Credential=" + accessKey + "/20261011/us-east-1/rds/aws4_request")
.contentType(URLENC).formParam("Action", action).formParam("Version", "2014-10-31");
}
@@ -97,7 +101,16 @@ public final class RdsRequests {
/** Creates a PostgreSQL instance with database {@code appdb} and returns its endpoint port. */
public static int createPostgresInstance(String id, String masterUsername, String masterPassword,
boolean iamDatabaseAuthentication) {
return rds("CreateDBInstance")
return createPostgresInstance(id, masterUsername, masterPassword, iamDatabaseAuthentication, null);
}
/**
* Creates a PostgreSQL instance with database {@code appdb}, in DB parameter group
* {@code parameterGroupName} unless it is null, and returns its endpoint port.
*/
public static int createPostgresInstance(String id, String masterUsername, String masterPassword,
boolean iamDatabaseAuthentication, String parameterGroupName) {
RequestSpecification request = rds("CreateDBInstance")
.formParam("DBInstanceIdentifier", id)
.formParam("Engine", "postgres")
.formParam("MasterUsername", masterUsername)
@@ -105,7 +118,11 @@ public final class RdsRequests {
.formParam("DBName", "appdb")
.formParam("AllocatedStorage", "20")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("EnableIAMDatabaseAuthentication", iamDatabaseAuthentication)
.formParam("EnableIAMDatabaseAuthentication", iamDatabaseAuthentication);
if (parameterGroupName != null) {
request.formParam("DBParameterGroupName", parameterGroupName);
}
return request
.when().post("/").then().statusCode(200)
.extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");