Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(rds): use MySQL 8.4 auth options (#3001)

Aniket Shuklae26e9a68fdc5
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
index b0d6b244d3..e520efe8db 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
@@ -30,6 +30,7 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
@@ -157,10 +158,10 @@ public class RdsContainerManager {
specBuilder, storageResourceId, exactVolumeName, engine, image);
// Add engine-specific command
- List<String> cmd = buildContainerCmd(engine);
- if (!cmd.isEmpty()) {
- specBuilder.withCmd(cmd);
- }
+ List<String> cmd = buildContainerCmd(engine, image);
+ if (!cmd.isEmpty()) {
+ specBuilder.withCmd(cmd);
+ }
ContainerSpec spec = specBuilder.build();
@@ -667,12 +668,62 @@ public class RdsContainerManager {
return envs;
}
- private List<String> buildContainerCmd(DatabaseEngine engine) {
- // Configure MySQL to use mysql_native_password so the proxy can authenticate
- // without needing caching_sha2_password RSA key exchange
+ static List<String> buildContainerCmd(DatabaseEngine engine, String image) {
+ // Keep the backend handshake on mysql_native_password so the transparent proxy can
+ // validate the client scramble. MySQL 8.4 removed default-authentication-plugin and
+ // requires the native plugin to be enabled separately before selecting it as the default.
+ // Indeterminate tags and MySQL 9+ use the server default, which the proxy also supports.
return switch (engine) {
- case MYSQL -> List.of("--default-authentication-plugin=mysql_native_password");
+ case MYSQL -> {
+ Optional<MySqlVersion> version = mysqlImageVersion(image);
+ if (version.isEmpty() || version.get().major() >= 9) {
+ yield List.of();
+ }
+ yield version.get().major() == 8 && version.get().minor() >= 4
+ ? List.of(
+ "--mysql-native-password=ON",
+ "--authentication-policy=mysql_native_password")
+ : List.of("--default-authentication-plugin=mysql_native_password");
+ }
case POSTGRES, MARIADB -> List.of();
};
}
+
+ private static Optional<MySqlVersion> mysqlImageVersion(String image) {
+ if (image == null || image.isBlank()) {
+ return Optional.empty();
+ }
+ String reference = image;
+ int digestSeparator = reference.indexOf('@');
+ if (digestSeparator >= 0) {
+ reference = reference.substring(0, digestSeparator);
+ }
+ int slashSeparator = reference.lastIndexOf('/');
+ int tagSeparator = reference.lastIndexOf(':');
+ if (tagSeparator < slashSeparator || tagSeparator == reference.length() - 1) {
+ return Optional.empty();
+ }
+ String tag = reference.substring(tagSeparator + 1);
+ int dot = tag.indexOf('.');
+ if (dot <= 0 || dot == tag.length() - 1) {
+ return Optional.empty();
+ }
+ int minorEnd = dot + 1;
+ while (minorEnd < tag.length() && Character.isDigit(tag.charAt(minorEnd))) {
+ minorEnd++;
+ }
+ if (minorEnd == dot + 1) {
+ return Optional.empty();
+ }
+ try {
+ int major = Integer.parseInt(tag.substring(0, dot));
+ int minor = Integer.parseInt(tag.substring(dot + 1, minorEnd));
+ return Optional.of(new MySqlVersion(major, minor));
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+
+ private record MySqlVersion(int major, int minor) {
+ }
}
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 a92b907e4a..c744fae6cb 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
@@ -43,8 +43,11 @@ 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 = 0x0008_0000;
private static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x200000;
private static final int CLIENT_SECURE_CONNECTION = 0x8000;
+ private static final String MYSQL_NATIVE_PASSWORD = "mysql_native_password";
+ private static final String CACHING_SHA2_PASSWORD = "caching_sha2_password";
// First payload byte of the packet types that can appear during the connection phase.
private static final int OK_PACKET_MARKER = 0x00;
@@ -78,6 +81,7 @@ public class MySqlProtocolHandler {
// Extract the backend's nonce for our credential validation
byte[] backendNonce = extractMysqlNonce(backendHandshakeRaw);
+ String backendAuthPlugin = extractMysqlAuthPlugin(backendHandshakeRaw);
// The proxy terminates TLS itself, so advertise CLIENT_SSL to the client even if the
// (plaintext) backend didn't.
@@ -153,7 +157,8 @@ public class MySqlProtocolHandler {
boolean valid;
try {
if (masterUsername.equals(clientUsername)) {
- byte[] expected = scrambleNativePassword(masterPassword, backendNonce);
+ byte[] expected = scramblePassword(
+ masterPassword, backendNonce, backendAuthPlugin);
valid = Arrays.equals(expected, clientAuthData);
} else {
// Non-master user: defer to backend — it knows their password.
@@ -345,6 +350,42 @@ public class MySqlProtocolHandler {
return nonce;
}
+ private static String extractMysqlAuthPlugin(byte[] raw) {
+ int i = 4 + 1;
+ while (i < raw.length && raw[i] != 0) {
+ i++;
+ }
+ i++;
+ i += 4 + 8 + 1;
+ if (i + 2 > raw.length) {
+ return MYSQL_NATIVE_PASSWORD;
+ }
+ int capabilities = (raw[i] & 0xFF) | ((raw[i + 1] & 0xFF) << 8);
+ i += 2;
+ if (i + 5 > raw.length) {
+ return MYSQL_NATIVE_PASSWORD;
+ }
+ i += 1 + 2;
+ capabilities |= ((raw[i] & 0xFF) | ((raw[i + 1] & 0xFF) << 8)) << 16;
+ i += 2;
+ int authDataLen = raw[i] & 0xFF;
+ i += 1 + 10;
+ if ((capabilities & CLIENT_PLUGIN_AUTH) == 0) {
+ return MYSQL_NATIVE_PASSWORD;
+ }
+ i += Math.max(13, authDataLen - 8);
+ if (i >= raw.length) {
+ return MYSQL_NATIVE_PASSWORD;
+ }
+ int pluginStart = i;
+ while (i < raw.length && raw[i] != 0) {
+ i++;
+ }
+ return i == pluginStart
+ ? MYSQL_NATIVE_PASSWORD
+ : new String(raw, pluginStart, i - pluginStart, StandardCharsets.UTF_8);
+ }
+
// ── Parse HandshakeResponse41 ─────────────────────────────────────────────
private static String[] parseHandshakeResponse(byte[] data) {
@@ -427,6 +468,16 @@ public class MySqlProtocolHandler {
// ── Scramble ──────────────────────────────────────────────────────────────
+ private static byte[] scramblePassword(String password, byte[] nonce, String authPlugin)
+ throws Exception {
+ return switch (authPlugin) {
+ case CACHING_SHA2_PASSWORD -> scrambleCachingSha2Password(password, nonce);
+ case MYSQL_NATIVE_PASSWORD -> scrambleNativePassword(password, nonce);
+ default -> throw new IllegalArgumentException(
+ "Unsupported MySQL authentication plugin: " + authPlugin);
+ };
+ }
+
private static byte[] scrambleNativePassword(String password, byte[] nonce) throws Exception {
if (password == null || password.isEmpty()) {
return new byte[0];
@@ -447,6 +498,27 @@ public class MySqlProtocolHandler {
return result;
}
+ private static byte[] scrambleCachingSha2Password(String password, byte[] nonce)
+ throws Exception {
+ if (password == null || password.isEmpty()) {
+ return new byte[0];
+ }
+ MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
+ byte[] hash1 = sha256.digest(password.getBytes(StandardCharsets.UTF_8));
+ sha256.reset();
+ byte[] hash2 = sha256.digest(hash1);
+ sha256.reset();
+ sha256.update(hash2);
+ sha256.update(nonce);
+ byte[] hash3 = sha256.digest();
+
+ byte[] result = new byte[32];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = (byte) (hash1[i] ^ hash3[i]);
+ }
+ return result;
+ }
+
// ── MySQL packet helpers ──────────────────────────────────────────────────
/**
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
index 24f8c12c1d..4d42194d7c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -47,6 +48,43 @@ class RdsContainerManagerTest {
@TempDir
Path tempDir;
+ @Test
+ void mysql84UsesSupportedNativePasswordOptions() {
+ assertEquals(
+ List.of(
+ "--mysql-native-password=ON",
+ "--authentication-policy=mysql_native_password"),
+ RdsContainerManager.buildContainerCmd(DatabaseEngine.MYSQL, "mysql:8.4"));
+ assertEquals(
+ List.of(
+ "--mysql-native-password=ON",
+ "--authentication-policy=mysql_native_password"),
+ RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.MYSQL,
+ "registry.example.com:5000/mysql:8.4.3-oracle@sha256:abcdef"));
+ }
+
+ @Test
+ void olderMysqlKeepsLegacyNativePasswordOption() {
+ assertEquals(
+ List.of("--default-authentication-plugin=mysql_native_password"),
+ RdsContainerManager.buildContainerCmd(DatabaseEngine.MYSQL, "mysql:8.0.36"));
+ assertTrue(RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.POSTGRES, "postgres:18").isEmpty());
+ assertTrue(RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.MARIADB, "mariadb:11").isEmpty());
+ }
+
+ @Test
+ void defersToServerAuthenticationForMysql9AndUnversionedImages() {
+ assertTrue(RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.MYSQL, "mysql:9.0").isEmpty());
+ assertTrue(RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.MYSQL, "mysql:latest").isEmpty());
+ assertTrue(RdsContainerManager.buildContainerCmd(
+ DatabaseEngine.MYSQL, "mysql@sha256:abcdef").isEmpty());
+ }
+
@Test
void postgresInitSqlCreatesRdsIamRoleWhenMissing() {
String sql = RdsContainerManager.postgresIamRoleInitSql();
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
index a17cd7629d..5b0bc0268c 100644
--- 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
@@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.cert.X509Certificate;
+import java.util.HexFormat;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -34,6 +35,7 @@ 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;
+ private static final int CLIENT_PLUGIN_AUTH = 0x0008_0000;
@TempDir
Path tempDir;
@@ -100,6 +102,60 @@ class MySqlProtocolHandlerTest {
assertEquals("admin", extractUsername(backendResponsePayload.get()));
}
+ @Test
+ void validatesCachingSha2MasterScrambleAndForwardsResponse() 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, "caching_sha2_password",
+ 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();
+ assertNotNull(readMysqlPacketRaw(clientIn));
+ byte[] scramble = HexFormat.of().parseHex(
+ "746ebe205d56a0707acb3e796e834e0dd7b1d61743b26bd5202c7a623230c7c9");
+ clientOut.write(buildHandshakeResponse41("admin", scramble, (byte) 1));
+ clientOut.flush();
+ 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());
+ assertEquals("admin", extractUsername(backendResponsePayload.get()));
+ }
+
@Test
void upgradesToTlsOnSslRequestAndRenumbersSequenceBeforeForwardingToBackend() throws Exception {
byte[] nonce = fixedNonce();
@@ -307,11 +363,17 @@ class MySqlProtocolHandlerTest {
private static void mockMySqlBackend(ServerSocket server, byte[] nonce,
AtomicReference<Byte> responseSeq,
AtomicReference<byte[]> responsePayload) throws IOException {
+ mockMySqlBackend(server, nonce, null, responseSeq, responsePayload);
+ }
+
+ private static void mockMySqlBackend(ServerSocket server, byte[] nonce, String authPlugin,
+ 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.write(buildHandshakeV10(nonce, authPlugin));
out.flush();
byte[] responseRaw = readMysqlPacketRaw(in);
@@ -328,6 +390,10 @@ class MySqlProtocolHandlerTest {
// ── MySQL Handshake V10 (server -> client) ──────────────────────────────
private static byte[] buildHandshakeV10(byte[] nonce) throws IOException {
+ return buildHandshakeV10(nonce, null);
+ }
+
+ private static byte[] buildHandshakeV10(byte[] nonce, String authPlugin) throws IOException {
ByteArrayOutputStream payload = new ByteArrayOutputStream();
payload.write(10); // protocol version
payload.write("8.0.34".getBytes(StandardCharsets.UTF_8));
@@ -335,15 +401,23 @@ class MySqlProtocolHandlerTest {
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
+ int capabilities = CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION;
+ if (authPlugin != null) {
+ capabilities |= CLIENT_PLUGIN_AUTH;
+ }
+ int capsLower = capabilities & 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)
+ writeInt16LE(payload, (capabilities >>> 16) & 0xFFFF);
+ payload.write(authPlugin == null ? 0 : 21);
payload.write(new byte[10]); // reserved
payload.write(nonce, 8, 12); // auth-plugin-data part 2 (12 bytes)
payload.write(0); // null terminator
+ if (authPlugin != null) {
+ payload.write(authPlugin.getBytes(StandardCharsets.UTF_8));
+ payload.write(0);
+ }
return wrapPacket(0, payload.toByteArray());
}