mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(rds): require database role grants for PostgreSQL IAM login (#5945)
* fix(rds): require database role grants for PostgreSQL IAM login * fix(rds): preserve standard proxy IAM authentication * fix(rds): report PAM refusal for IAM member passwords
This commit is contained in:
1 parent
e9154fb928
commit
678c5b82a6
13 files changed
+817
-71
No files matched your search
@@ -61,6 +61,7 @@ import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
|
||||
import io.github.hectorvent.floci.services.rds.model.PointInTimeRestoreRequest;
|
||||
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
|
||||
import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyBinding;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
|
||||
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
||||
@@ -5953,7 +5954,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
: validateDbPasswordForScope(
|
||||
proxyAccountId, targetRegion, targetId, user, pw),
|
||||
proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(),
|
||||
targetRegion, proxyAccountId, proxy.getDbProxyResourceId()));
|
||||
targetRegion, proxyAccountId, proxy.getDbProxyResourceId()),
|
||||
RdsAuthProxy.EndpointKind.STANDARD_DB_PROXY);
|
||||
}
|
||||
putTargetGroupForAccount(proxyAccountId, proxyKey, updatedTargetGroup);
|
||||
if (updatedProxy != null) {
|
||||
@@ -7997,7 +7999,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
: validateDbPasswordForScope(
|
||||
accountId, proxyRegion, targetId, user, password),
|
||||
proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(),
|
||||
proxyRegion, accountId, proxy.getDbProxyResourceId()));
|
||||
proxyRegion, accountId, proxy.getDbProxyResourceId()),
|
||||
RdsAuthProxy.EndpointKind.STANDARD_DB_PROXY);
|
||||
}
|
||||
|
||||
private DbProxyTargetGroup copyProxyTargetGroup(DbProxyTargetGroup source) {
|
||||
|
||||
+136
-2
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
@@ -22,6 +23,7 @@ import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -121,6 +123,21 @@ public class PostgresProtocolHandler {
|
||||
int handshakeTimeoutMillis,
|
||||
boolean forwardStartupParameters) throws IOException {
|
||||
|
||||
return authenticate(client, backendConnector, masterUsername, masterPassword, dbName,
|
||||
iamEnabled, sigV4, binding, tlsCertificates, passwordValidator,
|
||||
handshakeTimeoutMillis, forwardStartupParameters, true);
|
||||
}
|
||||
|
||||
/** Standard DB Proxy IAM does not enroll the backend role in database-native IAM. */
|
||||
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) throws IOException {
|
||||
|
||||
client.setSoTimeout(handshakeTimeoutMillis);
|
||||
|
||||
// Phase 1: Read client startup message (possibly preceded by SSL request)
|
||||
@@ -232,6 +249,24 @@ public class PostgresProtocolHandler {
|
||||
// Buffer all backend messages until ReadyForQuery ('Z')
|
||||
List<byte[]> bufferedMessages = readUntilReadyForQuery(backendIn);
|
||||
|
||||
// Native IAM-enabled PostgreSQL roles opt in through actual rds_iam membership. A
|
||||
// superuser is not implicitly a member, and an opted-in role uses IAM rather
|
||||
// than its password. Standard DB Proxy checks LOGIN without database IAM opt-in.
|
||||
// Check before trying defaults or handing over the session.
|
||||
DatabaseRole admittedRole = null;
|
||||
if (iamEnabled && !endsWithErrorResponse(bufferedMessages)) {
|
||||
admittedRole = readDatabaseRole(backendIn, backendOut, clientUsername, isIam, false, databaseIamAuthentication);
|
||||
if (admittedRole == null || !admittedRole.allowed()) {
|
||||
refuseDatabaseRole(clientOut, client, backend, clientUsername,
|
||||
admittedRole != null && admittedRole.pamRequired(),
|
||||
admittedRole == null ? "catalog lookup failed"
|
||||
: !databaseIamAuthentication ? "LOGIN required"
|
||||
: isIam ? "LOGIN and rds_iam membership required"
|
||||
: "LOGIN without rds_iam membership required");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String iamRole = null;
|
||||
List<SessionSetting> roleDefaultsAfterHandover = List.of();
|
||||
List<byte[]> notices = new ArrayList<>();
|
||||
@@ -370,8 +405,8 @@ public class PostgresProtocolHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// The role's client_encoding goes last, once the proxy sends no more SQL, and only
|
||||
// if the client did not choose an encoding itself.
|
||||
// Apply the role's encoding only if the client did not choose one. The
|
||||
// remaining role identity query is ASCII under either encoding.
|
||||
if (roleEncoding != null && !clientChoseEncoding(startup.parameters())) {
|
||||
DefaultOutcome outcome = applyDefault(backendIn, backendOut, roleEncoding, clientUsername);
|
||||
if (outcome.failure() != null) {
|
||||
@@ -391,6 +426,22 @@ public class PostgresProtocolHandler {
|
||||
bufferedMessages = insertBeforeStartupTrailer(bufferedMessages, notices);
|
||||
}
|
||||
|
||||
// Defaults can reopen the backend and handover resolves the role name again.
|
||||
// Bind the final session to the admitted role OID, so dropping/recreating the
|
||||
// name during login cannot hand a token to a different database role.
|
||||
if (iamHandover && !endsWithErrorResponse(bufferedMessages)) {
|
||||
DatabaseRole selectedRole = readDatabaseRole(backendIn, backendOut, clientUsername, true, true, databaseIamAuthentication);
|
||||
if (selectedRole == null || !selectedRole.allowed() || admittedRole == null
|
||||
|| !selectedRole.oid().equals(admittedRole.oid())) {
|
||||
refuseDatabaseRole(clientOut, client, backend, clientUsername, false,
|
||||
selectedRole == null ? "final catalog lookup failed"
|
||||
: !selectedRole.allowed() ? (databaseIamAuthentication
|
||||
? "final LOGIN and rds_iam membership required" : "final LOGIN required")
|
||||
: "role identity changed during handover");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge
|
||||
if (endsWithErrorResponse(bufferedMessages)) {
|
||||
for (byte[] msg : bufferedMessages) {
|
||||
@@ -881,6 +932,89 @@ public class PostgresProtocolHandler {
|
||||
return readUntilReadyForQuery(in);
|
||||
}
|
||||
|
||||
/** A real PostgreSQL role identity and its choice of authentication method. */
|
||||
private record DatabaseRole(String oid, boolean allowed, boolean pamRequired) {}
|
||||
|
||||
/**
|
||||
* Follow catalog membership edges, including indirect grants. pg_has_role treats a
|
||||
* superuser as privileged without a grant, which is not an IAM authentication opt-in.
|
||||
* All SQL is ASCII even when the client selected a non-UTF8 encoding, and catalog
|
||||
* objects and operators are qualified independently of the client's search_path.
|
||||
*/
|
||||
static String databaseRoleQuery(String role, boolean iam, boolean sessionRole) {
|
||||
return databaseRoleQuery(role, iam, sessionRole, true);
|
||||
}
|
||||
|
||||
static String databaseRoleQuery(String role, boolean iam, boolean sessionRole,
|
||||
boolean databaseIamAuthentication) {
|
||||
String name = sessionRole ? "SESSION_USER" : "pg_catalog.convert_from(pg_catalog.decode('"
|
||||
+ HexFormat.of().formatHex(role.getBytes(StandardCharsets.UTF_8)) + "', 'hex'), 'UTF8')";
|
||||
if (!databaseIamAuthentication) {
|
||||
return "SELECT r.oid::pg_catalog.text, r.rolcanlogin FROM pg_catalog.pg_roles r "
|
||||
+ "WHERE r.rolname OPERATOR(pg_catalog.=) " + name;
|
||||
}
|
||||
String membership = "EXISTS (SELECT 1 FROM memberships m JOIN pg_catalog.pg_roles i "
|
||||
+ "ON i.oid OPERATOR(pg_catalog.=) m.oid "
|
||||
+ "WHERE i.rolname OPERATOR(pg_catalog.=) 'rds_iam')";
|
||||
String admission = iam ? "r.rolcanlogin AND " + membership
|
||||
: "CASE WHEN " + membership + " THEN 'pam' WHEN r.rolcanlogin THEN 't' ELSE 'f' END";
|
||||
return "WITH RECURSIVE memberships(oid) AS ("
|
||||
+ "SELECT a.roleid FROM pg_catalog.pg_auth_members a JOIN pg_catalog.pg_roles r "
|
||||
+ "ON r.oid OPERATOR(pg_catalog.=) a.member WHERE r.rolname OPERATOR(pg_catalog.=) " + name
|
||||
+ " UNION SELECT a.roleid FROM pg_catalog.pg_auth_members a JOIN memberships m "
|
||||
+ "ON a.member OPERATOR(pg_catalog.=) m.oid) "
|
||||
+ "SELECT r.oid::pg_catalog.text, " + admission
|
||||
+ " FROM pg_catalog.pg_roles r WHERE r.rolname OPERATOR(pg_catalog.=) " + name;
|
||||
}
|
||||
|
||||
private static DatabaseRole readDatabaseRole(InputStream in, OutputStream out, String role,
|
||||
boolean iam, boolean sessionRole,
|
||||
boolean databaseIamAuthentication) throws IOException {
|
||||
List<byte[]> messages = runQuery(in, out,
|
||||
databaseRoleQuery(role, iam, sessionRole, databaseIamAuthentication));
|
||||
if (firstErrorResponse(messages) != null) {
|
||||
logDatabaseRoleRefusal(role, "catalog query returned an error");
|
||||
return null;
|
||||
}
|
||||
List<SessionSetting> rows = settingsFromDataRows(messages);
|
||||
if (rows.size() != 1) {
|
||||
logDatabaseRoleRefusal(role, rows.isEmpty() ? "database role not found" : "unexpected catalog row count");
|
||||
return null;
|
||||
}
|
||||
SessionSetting row = rows.getFirst();
|
||||
boolean pamRequired = databaseIamAuthentication && !iam && row.value().equals("pam");
|
||||
if (!row.name().matches("[0-9]{1,10}")
|
||||
|| !(row.value().equals("t") || row.value().equals("f") || pamRequired)) {
|
||||
logDatabaseRoleRefusal(role, "invalid catalog row format");
|
||||
return null;
|
||||
}
|
||||
long oid = Long.parseLong(row.name());
|
||||
if (oid == 0 || oid > 4_294_967_295L) {
|
||||
logDatabaseRoleRefusal(role, "invalid database role OID");
|
||||
return null;
|
||||
}
|
||||
return new DatabaseRole(row.name(), row.value().equals("t"), pamRequired);
|
||||
}
|
||||
|
||||
private static void refuseDatabaseRole(OutputStream out, Socket client, Socket backend, String user,
|
||||
boolean pamRequired, String reason)
|
||||
throws IOException {
|
||||
logDatabaseRoleRefusal(user, reason);
|
||||
try {
|
||||
sendErrorResponse(out, "FATAL", pamRequired ? "28000" : "28P01",
|
||||
(pamRequired ? "PAM" : "password") + " authentication failed for user \"" + user + "\"");
|
||||
out.flush();
|
||||
} finally {
|
||||
closeQuietly(client);
|
||||
closeQuietly(backend);
|
||||
}
|
||||
}
|
||||
|
||||
private static void logDatabaseRoleRefusal(String user, String reason) {
|
||||
LOG.infov("PostgreSQL role admission refused for user {0}: {1}",
|
||||
SigV4RequestValidator.sanitizeForLog(user), reason);
|
||||
}
|
||||
|
||||
static String quoteIdentifier(String identifier) {
|
||||
return "\"" + identifier.replace("\"", "\"\"") + "\"";
|
||||
}
|
||||
|
||||
@@ -22,6 +22,11 @@ public class RdsAuthProxy {
|
||||
|
||||
private final int backendPort;
|
||||
private volatile boolean iamEnabled;
|
||||
private final EndpointKind endpointKind;
|
||||
|
||||
/** Native database IAM and standard client-to-proxy IAM have different role requirements. */
|
||||
public enum EndpointKind { DATABASE, STANDARD_DB_PROXY }
|
||||
|
||||
private final String instanceId;
|
||||
private final String backendHost;
|
||||
private final String masterUsername;
|
||||
@@ -78,11 +83,27 @@ public class RdsAuthProxy {
|
||||
int maxConnections, RdsProxyBinding binding,
|
||||
MySqlProtocolHandler.IamUserChecker iamUserChecker,
|
||||
RdsBackendGate backendGate) {
|
||||
this(instanceId, backendHost, backendPort, engine, iamEnabled, masterUsername, masterPassword,
|
||||
dbName, sigV4, tlsCertificates, passwordValidator, handshakeTimeoutMillis,
|
||||
backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker, backendGate,
|
||||
EndpointKind.DATABASE);
|
||||
}
|
||||
|
||||
public RdsAuthProxy(String instanceId, String backendHost, int backendPort,
|
||||
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) {
|
||||
this.instanceId = instanceId;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
this.engine = engine;
|
||||
this.iamEnabled = iamEnabled;
|
||||
this.endpointKind = endpointKind;
|
||||
this.masterUsername = masterUsername;
|
||||
this.masterPassword = masterPassword;
|
||||
this.dbName = dbName;
|
||||
@@ -210,7 +231,7 @@ public class RdsAuthProxy {
|
||||
session = PostgresProtocolHandler.authenticate(
|
||||
client, connector, masterUsername, masterPassword, dbName,
|
||||
iamEnabled, sigV4, binding, tlsCertificates, authAdapter,
|
||||
handshakeTimeoutMillis, true);
|
||||
handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE);
|
||||
if (session != null) {
|
||||
PostgresProtocolHandler.bridge(session);
|
||||
}
|
||||
|
||||
@@ -44,13 +44,24 @@ public class RdsProxyManager {
|
||||
String masterUsername, String masterPassword, String dbName,
|
||||
RdsAuthProxy.MasterPasswordCheck passwordValidator,
|
||||
RdsProxyBinding binding) {
|
||||
startProxy(instanceId, engine, iamEnabled, proxyPort, backendHost, backendPort,
|
||||
advertisedHost, masterUsername, masterPassword, dbName, passwordValidator,
|
||||
binding, RdsAuthProxy.EndpointKind.DATABASE);
|
||||
}
|
||||
|
||||
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.MasterPasswordCheck passwordValidator,
|
||||
RdsProxyBinding binding, RdsAuthProxy.EndpointKind endpointKind) {
|
||||
tlsCertificates.ensureHost(advertisedHost);
|
||||
EmulatorConfig.RdsServiceConfig rdsConfig = config.services().rds();
|
||||
RdsAuthProxy proxy = new RdsAuthProxy(
|
||||
instanceId, backendHost, backendPort, engine, iamEnabled,
|
||||
masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator,
|
||||
rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(),
|
||||
rdsConfig.proxyMaxConnections(), binding, backendGate);
|
||||
rdsConfig.proxyMaxConnections(), binding, username -> binding != null, backendGate, endpointKind);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
} catch (IOException e) {
|
||||
|
||||
Reference in new issue
Block a user