Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(rds): bound PostgreSQL handshake packet lengths (#3102)

Niels Kootstra148ea6f3dbff
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
index 4536bc8f39..8f2430d35c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java
@@ -43,6 +43,7 @@ public class PostgresProtocolHandler {
private static final int SSL_REQUEST_CODE = 80877103;
private static final int STARTUP_PROTOCOL_VERSION = 196608; // v3.0
+ private static final int MAX_HANDSHAKE_PACKET_LENGTH = 1_048_576;
public static Socket authenticate(Socket client, Socket backend,
String masterUsername, String masterPassword, String dbName,
@@ -153,10 +154,7 @@ public class PostgresProtocolHandler {
while (true) {
InputStream in = currentSocket.getInputStream();
OutputStream out = currentSocket.getOutputStream();
- int length = readInt32(in);
- if (length < 8) {
- return null;
- }
+ int length = checkedPacketLength(readInt32(in), 8, "startup message");
int proto = readInt32(in);
if (proto == SSL_REQUEST_CODE) {
@@ -267,7 +265,7 @@ public class PostgresProtocolHandler {
LOG.warnv("Expected PasswordMessage ('p'), got {0}", (char) type);
return null;
}
- int length = readInt32(in);
+ int length = checkedPacketLength(readInt32(in), 5, "password message");
byte[] data = new byte[length - 4];
readFully(in, data);
// Strip trailing null terminator
@@ -288,7 +286,7 @@ public class PostgresProtocolHandler {
return false;
}
- int length = readInt32(in);
+ int length = checkedPacketLength(readInt32(in), 8, "backend authentication message");
int authType = readInt32(in);
if (authType == 0) {
@@ -354,7 +352,7 @@ public class PostgresProtocolHandler {
if (in.read() != 'R') {
return false;
}
- int len2 = readInt32(in);
+ int len2 = checkedPacketLength(readInt32(in), 8, "SASL continue message");
if (readInt32(in) != 11) {
return false;
}
@@ -395,7 +393,7 @@ public class PostgresProtocolHandler {
if (in.read() != 'R') {
return false;
}
- int len3 = readInt32(in);
+ int len3 = checkedPacketLength(readInt32(in), 8, "SASL final message");
if (readInt32(in) != 12) {
return false;
}
@@ -471,7 +469,7 @@ public class PostgresProtocolHandler {
LOG.warnv("Expected AuthenticationOK from backend, got type={0}", type);
return false;
}
- int length = readInt32(in);
+ int length = checkedPacketLength(readInt32(in), 8, "authentication response");
int authType = readInt32(in);
if (length > 8) {
byte[] extra = new byte[length - 8];
@@ -511,7 +509,7 @@ public class PostgresProtocolHandler {
if (type < 0) {
throw new EOFException("Connection closed before ReadyForQuery");
}
- int length = readInt32(in);
+ int length = checkedPacketLength(readInt32(in), 4, "backend message");
byte[] payload = new byte[length - 4];
readFully(in, payload);
@@ -644,6 +642,18 @@ public class PostgresProtocolHandler {
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
+ private static int checkedPacketLength(int length, int minimum, String packetName) throws IOException {
+ if (length < minimum) {
+ throw new IOException("PostgreSQL " + packetName + " length is below the "
+ + minimum + " byte minimum: " + length);
+ }
+ if (length > MAX_HANDSHAKE_PACKET_LENGTH) {
+ throw new IOException("PostgreSQL " + packetName + " length exceeds the "
+ + MAX_HANDSHAKE_PACKET_LENGTH + " byte limit: " + length);
+ }
+ return length;
+ }
+
private static void readFully(InputStream in, byte[] buf) throws IOException {
int offset = 0;
while (offset < buf.length) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
index 2b89398ec6..dda789fca8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
+import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -33,6 +34,7 @@ import java.security.cert.X509Certificate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,6 +47,133 @@ class PostgresProtocolHandlerTest {
@TempDir
Path tempDir;
+ @Test
+ void rejectsStartupMessageAboveTheHandshakeLimitBeforeReadingPayload() throws Exception {
+ ByteArrayOutputStream input = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(input);
+ out.writeInt(1_048_577);
+ out.writeInt(STARTUP_PROTOCOL_VERSION);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(input.toByteArray()), mock(Socket.class),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL startup message length exceeds the 1048576 byte limit: 1048577",
+ error.getMessage());
+ }
+
+ @Test
+ void acceptsStartupMessageAtTheHandshakeLimit() throws Exception {
+ byte[] startup = new byte[1_048_576];
+ ByteArrayOutputStream headerBytes = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(headerBytes);
+ out.writeInt(startup.length);
+ out.writeInt(STARTUP_PROTOCOL_VERSION);
+ byte[] header = headerBytes.toByteArray();
+ System.arraycopy(header, 0, startup, 0, header.length);
+
+ MemorySocket client = new MemorySocket(startup);
+ assertNull(PostgresProtocolHandler.authenticate(
+ client, new MemorySocket(new byte[0]),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+ }
+
+ @Test
+ void rejectsNegativeStartupMessageLength() throws Exception {
+ ByteArrayOutputStream input = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(input);
+ out.writeInt(-1);
+ out.writeInt(STARTUP_PROTOCOL_VERSION);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL startup message length is below the 8 byte minimum: -1",
+ error.getMessage());
+ }
+
+ @Test
+ void rejectsPasswordMessageBelowItsProtocolMinimum() throws Exception {
+ ByteArrayOutputStream input = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(input);
+ writeStartup(out, "dbadmin", "postgres");
+ out.writeByte('p');
+ out.writeInt(4);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL password message length is below the 5 byte minimum: 4",
+ error.getMessage());
+ }
+
+ @Test
+ void rejectsOversizedBackendAuthenticationMessage() throws Exception {
+ ByteArrayOutputStream backendInput = new ByteArrayOutputStream();
+ DataOutputStream backendOut = new DataOutputStream(backendInput);
+ backendOut.writeByte('R');
+ backendOut.writeInt(1_048_577);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL backend authentication message length exceeds the 1048576 byte limit: 1048577",
+ error.getMessage());
+ }
+
+ @Test
+ void rejectsOversizedBackendMessageBeforeBufferingIt() throws Exception {
+ ByteArrayOutputStream backendInput = new ByteArrayOutputStream();
+ DataOutputStream backendOut = new DataOutputStream(backendInput);
+ backendOut.writeByte('R');
+ backendOut.writeInt(8);
+ backendOut.writeInt(0);
+ backendOut.writeByte('Z');
+ backendOut.writeInt(1_048_577);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL backend message length exceeds the 1048576 byte limit: 1048577",
+ error.getMessage());
+ }
+
+ @Test
+ void rejectsOversizedSaslContinuationMessage() throws Exception {
+ ByteArrayOutputStream backendInput = new ByteArrayOutputStream();
+ DataOutputStream backendOut = new DataOutputStream(backendInput);
+ backendOut.writeByte('R');
+ backendOut.writeInt(8);
+ backendOut.writeInt(10);
+ backendOut.writeByte('R');
+ backendOut.writeInt(1_048_577);
+
+ IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
+ new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
+ "dbadmin", "adminpass", "postgres",
+ false, testSigV4Validator(), testTlsCertificates(),
+ (user, pass) -> true));
+
+ assertEquals("PostgreSQL SASL continue message length exceeds the 1048576 byte limit: 1048577",
+ error.getMessage());
+ }
+
@ParameterizedTest
@CsvSource({
"auth_db, postgres, auth_db",
@@ -595,6 +724,14 @@ class PostgresProtocolHandlerTest {
assertEquals('I', in.readByte());
}
+ private static byte[] startupAndPassword() throws IOException {
+ ByteArrayOutputStream input = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(input);
+ writeStartup(out, "dbadmin", "postgres");
+ writePassword(out, "adminpass");
+ return input.toByteArray();
+ }
+
private static void writeErrorResponse(DataOutputStream out, String severity, String sqlState,
String message) throws IOException {
ByteArrayOutputStream fields = new ByteArrayOutputStream();
@@ -643,4 +780,23 @@ class PostgresProtocolHandlerTest {
return params;
}
+ private static final class MemorySocket extends Socket {
+ private final ByteArrayInputStream input;
+ private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ private MemorySocket(byte[] input) {
+ this.input = new ByteArrayInputStream(input);
+ }
+
+ @Override
+ public ByteArrayInputStream getInputStream() {
+ return input;
+ }
+
+ @Override
+ public ByteArrayOutputStream getOutputStream() {
+ return output;
+ }
+ }
+
}