diff --git a/docs/services/rds.md b/docs/services/rds.md index 51e3669db3..29b752f58a 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -1163,6 +1163,14 @@ so the password challenge is not emitted as separate header and payload writes. This supports PgBouncer logins over plaintext and TLS while keeping the same password, IAM and database-role checks. +For PostgreSQL, the proxy logs in to the backend with whatever the backend asks for: +trust, a cleartext or MD5 password, or SCRAM-SHA-256. With SCRAM, it checks the +backend's server signature before it accepts the login, prepares the password +with SASLprep as PostgreSQL does, and refuses a backend that switches to a +cleartext or MD5 request, or starts a second exchange, once the first has begun. +A backend login the proxy refuses reaches the client as +`FATAL 08006 Backend database authentication failed`. + IAM database authentication is also supported. Set `--enable-iam-database-authentication` at instance creation time and use `aws rds generate-db-auth-token` to obtain a token. Aurora members use their cluster's IAM database authentication setting and master diff --git a/src/main/java/io/floci/aws/core/common/BackendAuthenticator.java b/src/main/java/io/floci/aws/core/common/BackendAuthenticator.java new file mode 100644 index 0000000000..2854bdd063 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/BackendAuthenticator.java @@ -0,0 +1,323 @@ +package io.floci.aws.core.common; + +import javax.crypto.Mac; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Optional; + +/** + * Answers the password challenge of a PostgreSQL server Floci logs in to as a client, such as the + * RDS proxy's backend or an Aurora DSQL cluster's external database: cleartext, MD5 and + * SCRAM-SHA-256 (RFC 5802 and 7677, without channel binding), or SCRAM-SHA-256 alone where the + * server is known to store SCRAM verifiers. One instance serves one connection, as the SCRAM + * exchange keeps its state between the messages. + */ +public final class BackendAuthenticator { + + private static final String SCRAM = "SCRAM-SHA-256"; + private static final int NONCE_BYTES = 18; + /** PostgreSQL stores 4096; a server asking for far more would only make Floci burn CPU. */ + static final int MAX_ITERATIONS = 1_000_000; + /** + * The largest server-first or server-final SCRAM message read, in bytes. PostgreSQL's are under + * 200; the limit keeps a peer from making Floci copy and split megabytes before it logs in. + */ + static final int MAX_SCRAM_MESSAGE = 4096; + /** The largest decoded salt taken, in bytes. PostgreSQL's are 16. */ + static final int MAX_SALT_BYTES = 1024; + + private final String user; + private final String password; + private final String clientNonce; + private final String scramUserName; + private final boolean scramOnly; + + /** Whether a request for a password, cleartext, MD5 or SASL, was answered on this connection. */ + private boolean started; + private String clientFirstBare; + private byte[] serverSignature; + private boolean scramVerified; + + public BackendAuthenticator(String user, String password) { + this(user, password, false); + } + + /** + * With {@code scramOnly}, only SCRAM-SHA-256 is answered: a cleartext or MD5 request is + * refused, as a server that stores SCRAM verifiers never asks for them and a peer that does is + * not that server. A login accepted before any request (trust) discloses nothing and is + * accepted; one accepted after SASL started but before its signature was verified is not. + */ + public BackendAuthenticator(String user, String password, boolean scramOnly) { + this(user, password, newNonce(), "", scramOnly); + } + + /** For the RFC 7677 vector, whose client-first message names the user and fixes the nonce. */ + BackendAuthenticator(String user, String password, String clientNonce, String scramUserName) { + this(user, password, clientNonce, scramUserName, false); + } + + BackendAuthenticator(String user, String password, String clientNonce, String scramUserName, + boolean scramOnly) { + this.user = user; + this.password = password; + this.clientNonce = clientNonce; + this.scramUserName = scramUserName; + this.scramOnly = scramOnly; + } + + private static String newNonce() { + SecureRandom random = new SecureRandom(); + byte[] bytes = new byte[NONCE_BYTES]; + random.nextBytes(bytes); + return Base64.getEncoder().encodeToString(bytes); + } + + /** + * The answer to an authentication request ({@code R}), or empty when none is due. An + * AuthenticationOk that comes while a SCRAM exchange has not yet proved the server's signature + * is refused, as the server would then be one that never knew the password. + */ + public Optional answer(PostgresWire.Message authRequest) throws IOException { + byte[] body = authRequest.body(); + if (authRequest.type() != 'R' || body.length < 4) { + throw new IOException("unexpected backend authentication message"); + } + int code = PostgresWire.int32(body, 0); + return switch (code) { + case 0 -> { + // Before any request it is a trusting server, which got no password; once SASL has + // started, only a verified server signature lets the login through. + if (clientFirstBare != null && !scramVerified) { + throw new IOException("backend accepted the login before proving its SCRAM signature"); + } + yield Optional.empty(); + } + case 3 -> { + refusePasswordRequest("a cleartext password"); + yield Optional.of(new PostgresWire.Message((byte) 'p', PostgresWire.cStringBytes(password))); + } + case 5 -> { + refusePasswordRequest("an MD5 password"); + yield Optional.of(md5(body)); + } + case 10 -> { + if (started) { + // A second exchange would let the first one's verified signature vouch for it. + throw new IOException("backend starts a second authentication exchange"); + } + PostgresWire.Message initial = saslInitial(body); + started = true; + yield Optional.of(initial); + } + case 11 -> Optional.of(saslContinue(body)); + case 12 -> { + saslFinal(body); + yield Optional.empty(); + } + default -> throw new IOException("unsupported backend authentication method: " + code); + }; + } + + /** + * Refuses a cleartext or MD5 request that would be a downgrade. In SCRAM-only mode, any such + * request is. In every mode, one that comes once an authentication has started is: a server + * asks for one method, so a peer that switches mid-SCRAM wants the password without proving it + * knows it. + */ + private void refusePasswordRequest(String method) throws IOException { + if (scramOnly) { + throw new IOException("backend asks for " + method + " where only SCRAM-SHA-256 is accepted"); + } + if (started) { + throw new IOException("backend asks for " + method + " after the authentication started"); + } + started = true; + } + + private PostgresWire.Message md5(byte[] body) throws IOException { + if (body.length < 8) { + throw new IOException("malformed backend MD5 authentication request"); + } + String hashed = md5Answer(user, password, Arrays.copyOfRange(body, 4, 8)); + return new PostgresWire.Message((byte) 'p', PostgresWire.cStringBytes(hashed)); + } + + private PostgresWire.Message saslInitial(byte[] body) throws IOException { + boolean offered = false; + int offset = 4; + while (offset < body.length && body[offset] != 0) { + PostgresWire.CString mechanism = PostgresWire.cString(body, offset); + offered |= SCRAM.equals(mechanism.value()); + offset = mechanism.next(); + } + if (!offered) { + throw new IOException("backend offers no supported SASL mechanism"); + } + clientFirstBare = "n=" + scramUserName + ",r=" + clientNonce; + byte[] clientFirst = ("n,," + clientFirstBare).getBytes(StandardCharsets.UTF_8); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.writeBytes(PostgresWire.cStringBytes(SCRAM)); + out.writeBytes(PostgresWire.int32(clientFirst.length)); + out.writeBytes(clientFirst); + return new PostgresWire.Message((byte) 'p', out.toByteArray()); + } + + private PostgresWire.Message saslContinue(byte[] body) throws IOException { + if (clientFirstBare == null || serverSignature != null) { + throw new IOException("unexpected SASL continue from the backend"); + } + String serverFirst = scramMessage(body); + String nonce = null; + byte[] salt = null; + Integer iterations = null; + try { + for (String attribute : serverFirst.split(",")) { + if (attribute.startsWith("m=")) { + // RFC 5802, section 5.1: an extension the client does not support must fail it. + throw new IOException("backend SCRAM message asks for a mandatory extension"); + } + if (attribute.startsWith("r=")) { + requireFirst(nonce); + nonce = attribute.substring(2); + } else if (attribute.startsWith("s=")) { + requireFirst(salt); + salt = decodeSalt(attribute.substring(2)); + } else if (attribute.startsWith("i=")) { + requireFirst(iterations); + iterations = Integer.parseInt(attribute.substring(2)); + } + } + } catch (IllegalArgumentException e) { + throw new IOException("malformed SCRAM message from the backend", e); + } + if (nonce == null || salt == null || iterations == null || iterations <= 0) { + throw new IOException("malformed SCRAM message from the backend"); + } + if (salt.length == 0) { + // PBKDF2 refuses an empty salt with an unchecked exception; PostgreSQL never sends one. + throw new IOException("backend SCRAM salt is empty"); + } + if (iterations > MAX_ITERATIONS) { + throw new IOException("backend asks for " + iterations + " SCRAM iterations, more than " + + MAX_ITERATIONS); + } + // The server appends its own part (RFC 5802, section 5.1); the client's nonce alone is not one. + if (nonce.length() <= clientNonce.length() || !nonce.startsWith(clientNonce)) { + throw new IOException("backend SCRAM nonce does not extend the client nonce"); + } + String withoutProof = "c=biws,r=" + nonce; + byte[] authMessage = (clientFirstBare + "," + serverFirst + "," + withoutProof) + .getBytes(StandardCharsets.UTF_8); + try { + byte[] salted = saltedPassword(password, salt, iterations); + byte[] clientKey = hmac(salted, "Client Key".getBytes(StandardCharsets.UTF_8)); + byte[] storedKey = Digests.sha256(clientKey); + byte[] clientSignature = hmac(storedKey, authMessage); + byte[] proof = new byte[clientKey.length]; + for (int i = 0; i < proof.length; i++) { + proof[i] = (byte) (clientKey[i] ^ clientSignature[i]); + } + byte[] serverKey = hmac(salted, "Server Key".getBytes(StandardCharsets.UTF_8)); + serverSignature = hmac(serverKey, authMessage); + String clientFinal = withoutProof + ",p=" + Base64.getEncoder().encodeToString(proof); + return new PostgresWire.Message((byte) 'p', clientFinal.getBytes(StandardCharsets.UTF_8)); + } catch (GeneralSecurityException e) { + throw new IOException("SCRAM-SHA-256 is not available", e); + } + } + + /** The SCRAM message of a SASL continue or final, refused when larger than {@link #MAX_SCRAM_MESSAGE}. */ + private static String scramMessage(byte[] body) throws IOException { + int length = body.length - 4; + if (length > MAX_SCRAM_MESSAGE) { + throw new IOException("backend SCRAM message is " + length + " bytes, more than " + MAX_SCRAM_MESSAGE); + } + return new String(body, 4, length, StandardCharsets.UTF_8); + } + + /** + * The salt, refused when longer than {@link #MAX_SALT_BYTES}: by its encoded length before it + * is decoded, then exactly, as padding lets two lengths share one encoded length. + */ + private static byte[] decodeSalt(String encoded) throws IOException { + if (encoded.length() > (MAX_SALT_BYTES + 2) / 3 * 4) { + throw new IOException("backend SCRAM salt is longer than " + MAX_SALT_BYTES + " bytes"); + } + byte[] salt = Base64.getDecoder().decode(encoded); + if (salt.length > MAX_SALT_BYTES) { + throw new IOException("backend SCRAM salt is longer than " + MAX_SALT_BYTES + " bytes"); + } + return salt; + } + + /** A server-first attribute given twice makes the message malformed. */ + private static void requireFirst(Object earlier) throws IOException { + if (earlier != null) { + throw new IOException("malformed SCRAM message from the backend"); + } + } + + private void saslFinal(byte[] body) throws IOException { + String serverFinal = scramMessage(body); + if (scramVerified) { + throw new IOException("unexpected SASL final from the backend"); + } + if (serverSignature == null || !serverFinal.startsWith("v=")) { + throw new IOException("backend server signature mismatch"); + } + byte[] received; + try { + received = Base64.getDecoder().decode(serverFinal.substring(2)); + } catch (IllegalArgumentException e) { + throw new IOException("backend server signature mismatch", e); + } + if (!MessageDigest.isEqual(serverSignature, received)) { + throw new IOException("backend server signature mismatch"); + } + scramVerified = true; + } + + /** + * The answer PostgreSQL expects to an MD5 password request: {@code "md5"} followed by the hex + * MD5 of the hex MD5 of the password and user name, and the request's 4-byte salt. + */ + public static String md5Answer(String user, String password, byte[] salt) { + MessageDigest md5 = Digests.md5Digest(); + md5.update(password.getBytes(StandardCharsets.UTF_8)); + md5.update(user.getBytes(StandardCharsets.UTF_8)); + String inner = HexFormat.of().formatHex(md5.digest()); + md5.update(inner.getBytes(StandardCharsets.US_ASCII)); + md5.update(salt); + return "md5" + HexFormat.of().formatHex(md5.digest()); + } + + /** + * SCRAM's SaltedPassword: PBKDF2 with HMAC-SHA256 (RFC 5802, section 3) of the password after + * SASLprep, as PostgreSQL derives it both when it stores a verifier and when it logs in. + */ + public static byte[] saltedPassword(String password, byte[] salt, int iterations) throws GeneralSecurityException { + PBEKeySpec spec = new PBEKeySpec(SaslPrep.prepare(password).toCharArray(), salt, iterations, 256); + try { + return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded(); + } finally { + spec.clearPassword(); + } + } + + public static byte[] hmac(byte[] key, byte[] data) throws GeneralSecurityException { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(data); + } +} diff --git a/src/main/java/io/floci/aws/core/common/SaslPrep.java b/src/main/java/io/floci/aws/core/common/SaslPrep.java new file mode 100644 index 0000000000..05ff37f1ce --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/SaslPrep.java @@ -0,0 +1,116 @@ +package io.floci.aws.core.common; + +import java.text.Normalizer; + +/** + * SASLprep (RFC 4013) as PostgreSQL applies it to a SCRAM password ({@code pg_saslprep}): an + * all-ASCII password is taken as it is; any other is mapped (RFC 3454 table B.1 to nothing, table + * C.1.2 spaces to U+0020), the mapped code points are checked for prohibited and unassigned + * characters and the bidirectional rules, and the result is their NFKC normalization. As in + * {@code pg_saslprep}, the checks run before NFKC rather than on its output, so a prohibited + * character that NFKC would replace, such as U+0341, still fails them. Where PostgreSQL finds the + * password invalid, it derives the key from the password as given, and so does this. + * + *

The JDK's character data is of a later Unicode version than RFC 3454's 3.2. A code point + * unassigned in 3.2 but assigned since, such as most emoji, is prohibited by PostgreSQL, so it + * falls back to the password as given, while here only code points unassigned in the JDK's version + * are: a password holding such a character and a mapped or NFKC-changed one prepares differently. + * The bidirectional categories are likewise the JDK's rather than tables D.1 and D.2. + */ +final class SaslPrep { + + /** RFC 3454 table C.1.2, non-ASCII spaces, mapped to U+0020. */ + private static final int[][] NON_ASCII_SPACES = { + {0x00A0, 0x00A0}, {0x1680, 0x1680}, {0x2000, 0x200B}, {0x202F, 0x202F}, {0x205F, 0x205F}, + {0x3000, 0x3000}, + }; + + /** RFC 3454 table B.1, commonly mapped to nothing. */ + private static final int[][] MAPPED_TO_NOTHING = { + {0x00AD, 0x00AD}, {0x034F, 0x034F}, {0x1806, 0x1806}, {0x180B, 0x180D}, {0x200B, 0x200D}, + {0x2060, 0x2060}, {0xFE00, 0xFE0F}, {0xFEFF, 0xFEFF}, + }; + + /** RFC 4013 section 2.3: RFC 3454 tables C.1.2, C.2.1, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8 and C.9. */ + private static final int[][] PROHIBITED = { + // C.1.2 non-ASCII spaces + {0x00A0, 0x00A0}, {0x1680, 0x1680}, {0x2000, 0x200B}, {0x202F, 0x202F}, {0x205F, 0x205F}, + {0x3000, 0x3000}, + // C.2.1 ASCII controls + {0x0000, 0x001F}, {0x007F, 0x007F}, + // C.2.2 non-ASCII controls + {0x0080, 0x009F}, {0x06DD, 0x06DD}, {0x070F, 0x070F}, {0x180E, 0x180E}, {0x200C, 0x200D}, + {0x2028, 0x2029}, {0x2060, 0x2063}, {0x206A, 0x206F}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFC}, + {0x1D173, 0x1D17A}, + // C.3 private use + {0xE000, 0xF8FF}, {0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD}, + // C.4 non-characters + {0xFDD0, 0xFDEF}, {0xFFFE, 0xFFFF}, {0x1FFFE, 0x1FFFF}, {0x2FFFE, 0x2FFFF}, {0x3FFFE, 0x3FFFF}, + {0x4FFFE, 0x4FFFF}, {0x5FFFE, 0x5FFFF}, {0x6FFFE, 0x6FFFF}, {0x7FFFE, 0x7FFFF}, {0x8FFFE, 0x8FFFF}, + {0x9FFFE, 0x9FFFF}, {0xAFFFE, 0xAFFFF}, {0xBFFFE, 0xBFFFF}, {0xCFFFE, 0xCFFFF}, {0xDFFFE, 0xDFFFF}, + {0xEFFFE, 0xEFFFF}, {0xFFFFE, 0xFFFFF}, {0x10FFFE, 0x10FFFF}, + // C.5 surrogates + {0xD800, 0xDFFF}, + // C.6 inappropriate for plain text + {0xFFF9, 0xFFFD}, + // C.7 inappropriate for canonical representation + {0x2FF0, 0x2FFB}, + // C.8 change display properties or deprecated + {0x0340, 0x0341}, {0x200E, 0x200F}, {0x202A, 0x202E}, {0x206A, 0x206F}, + // C.9 tagging characters + {0xE0001, 0xE0001}, {0xE0020, 0xE007F}, + }; + + private SaslPrep() { + } + + /** The password PostgreSQL derives a SCRAM key from: prepared, or as given where that fails. */ + static String prepare(String password) { + if (password.chars().allMatch(c -> c < 0x80)) { + return password; + } + StringBuilder mapped = new StringBuilder(password.length()); + password.codePoints().forEach(codePoint -> { + if (in(NON_ASCII_SPACES, codePoint)) { + mapped.append(' '); + } else if (!in(MAPPED_TO_NOTHING, codePoint)) { + mapped.appendCodePoint(codePoint); + } + }); + if (mapped.isEmpty()) { + return password; + } + int[] codePoints = mapped.codePoints().toArray(); + boolean rightToLeft = false; + boolean leftToRight = false; + for (int codePoint : codePoints) { + if (in(PROHIBITED, codePoint) || Character.getType(codePoint) == Character.UNASSIGNED) { + return password; + } + rightToLeft |= isRightToLeft(codePoint); + leftToRight |= Character.getDirectionality(codePoint) == Character.DIRECTIONALITY_LEFT_TO_RIGHT; + } + // RFC 3454 section 6: a string with a right-to-left character holds no left-to-right one, + // and starts and ends with a right-to-left character. + if (rightToLeft && (leftToRight || !isRightToLeft(codePoints[0]) + || !isRightToLeft(codePoints[codePoints.length - 1]))) { + return password; + } + return Normalizer.normalize(mapped, Normalizer.Form.NFKC); + } + + private static boolean isRightToLeft(int codePoint) { + byte directionality = Character.getDirectionality(codePoint); + return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT + || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; + } + + private static boolean in(int[][] ranges, int codePoint) { + for (int[] range : ranges) { + if (codePoint >= range[0] && codePoint <= range[1]) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java index 7b37c9cc8c..88cf7b24a7 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java @@ -1,17 +1,12 @@ package io.floci.aws.services.rds.proxy; -import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.BackendAuthenticator; import io.floci.aws.core.common.PostgresWire; import io.floci.aws.core.common.auth.SigV4RequestValidator; import org.jboss.logging.Logger; -import javax.crypto.Mac; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.SSLSocket; import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -19,17 +14,14 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.SecureRandom; import java.sql.SQLException; 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; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; @@ -43,7 +35,7 @@ import java.util.function.BiConsumer; *

  • Challenge client with AuthenticationCleartextPassword *
  • Read client password *
  • Validate (IAM SigV4 or plain password) - *
  • Connect to backend with MD5 or SCRAM-SHA-256 auth + *
  • Connect to backend with cleartext, MD5 or SCRAM-SHA-256 auth, checking SCRAM's server signature *
  • Buffer backend messages until ReadyForQuery *
  • For IAM logins, hand the session over to the role named in the token, then apply the * client's startup parameters as that role @@ -768,52 +760,44 @@ public class PostgresProtocolHandler { return responseMessage('E', "FATAL", "08006", "Backend database authentication failed"); } + /** + * Answers the backend's authentication requests through {@link BackendAuthenticator}, in its + * general mode: trust, cleartext, MD5 or SCRAM-SHA-256, whose server signature must be proved + * before an AuthenticationOk is taken. False, with the cause logged but no secret, when the + * backend asks for something the proxy cannot or will not answer. + */ private static boolean authenticateWithBackend(InputStream in, OutputStream out, String username, String password) throws IOException { - int type = readAuthenticationType(in); - if (type != 'R') { - LOG.warnv("Expected Authentication ('R') from backend, got type={0}", type); - return false; + BackendAuthenticator authenticator = new BackendAuthenticator(username, password); + String packetName = "backend authentication message"; + while (true) { + int type = readAuthenticationType(in); + if (type != 'R') { + LOG.warnv("Expected Authentication ('R') from backend, got type={0}", type); + return false; + } + byte[] body = PostgresWire.readBody(in, 8, MAX_HANDSHAKE_PACKET_LENGTH, packetName); + Optional answer; + try { + answer = authenticator.answer(new PostgresWire.Message((byte) 'R', body)); + } catch (IOException e) { + LOG.warnv("Backend PostgreSQL authentication failed: {0}", e.getMessage()); + return false; + } + int authType = PostgresWire.int32(body, 0); + if (authType == 0) { + return true; + } + if (answer.isPresent()) { + PostgresWire.write(out, answer.get()); + out.flush(); + } + packetName = switch (authType) { + case 10 -> "SASL continue message"; + case 11 -> "SASL final message"; + default -> "authentication response"; + }; } - - int length = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "backend authentication message"); - int authType = PostgresWire.readInt32(in); - - if (authType == 0) { - // Trust auth — no password needed - return true; - } - - if (authType == 3) { - // CleartextPassword - sendPasswordMessage(out, password); - out.flush(); - return readAuthOk(in); - } - - if (authType == 5) { - // MD5Password — read 4-byte salt - byte[] salt = new byte[4]; - PostgresWire.readFully(in, salt); - String md5pw = computeMd5Password(password, username, salt); - sendPasswordMessage(out, md5pw); - out.flush(); - return readAuthOk(in); - } - - if (authType == 10) { - // SCRAM-SHA-256 — drain the mechanisms list and perform SCRAM handshake - byte[] mechanismsBytes = new byte[length - 8]; - PostgresWire.readFully(in, mechanismsBytes); - return performScramSha256(in, out, username, password); - } - - LOG.warnv("Unsupported backend PostgreSQL auth type: {0}", authType); - if (length > 8) { - byte[] extra = new byte[length - 8]; - PostgresWire.readFully(in, extra); - } - return false; } /** @@ -843,168 +827,6 @@ public class PostgresProtocolHandler { } } - // ── SCRAM-SHA-256 ───────────────────────────────────────────────────────── - - private static boolean performScramSha256(InputStream in, OutputStream out, - String username, String password) throws IOException { - // Step 1: Send SASLInitialResponse with client-first-message - String clientNonce = generateNonce(); - String clientFirstMessageBare = "n=" + username + ",r=" + clientNonce; - String clientFirstMessage = "n,," + clientFirstMessageBare; - byte[] firstMsgBytes = clientFirstMessage.getBytes(StandardCharsets.UTF_8); - - // Body: mechanism-name '\0' Int32(msg-length) msg-bytes - ByteArrayOutputStream saslInit = new ByteArrayOutputStream(); - saslInit.write("SCRAM-SHA-256".getBytes(StandardCharsets.UTF_8)); - saslInit.write(0); - saslInit.write((firstMsgBytes.length >> 24) & 0xFF); - saslInit.write((firstMsgBytes.length >> 16) & 0xFF); - saslInit.write((firstMsgBytes.length >> 8) & 0xFF); - saslInit.write(firstMsgBytes.length & 0xFF); - saslInit.write(firstMsgBytes); - PostgresWire.write(out, 'p', saslInit.toByteArray()); - out.flush(); - - // Step 2: Read AuthenticationSASLContinue (authType=11) - if (readAuthenticationType(in) != 'R') { - return false; - } - int len2 = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "SASL continue message"); - if (PostgresWire.readInt32(in) != 11) { - return false; - } - byte[] serverFirstBytes = new byte[len2 - 8]; - PostgresWire.readFully(in, serverFirstBytes); - String serverFirstMessage = new String(serverFirstBytes, StandardCharsets.UTF_8); - - // Parse server-first-message: r=,s=,i= - Map sp = parseScramParams(serverFirstMessage); - String serverNonce = sp.get("r"); - byte[] salt = Base64.getDecoder().decode(sp.get("s")); - int iterations = Integer.parseInt(sp.get("i")); - - if (serverNonce == null || !serverNonce.startsWith(clientNonce)) { - LOG.warn("SCRAM: server nonce does not start with client nonce"); - return false; - } - - // Step 3: Compute client-final-message with proof - // c = base64("n,,") = "biws" (GS2 header, no channel binding) - String clientFinalWithoutProof = "c=biws,r=" + serverNonce; - String authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalWithoutProof; - - byte[] saltedPassword = pbkdf2HmacSha256(password, salt, iterations); - byte[] clientKey = hmacSha256(saltedPassword, "Client Key"); - byte[] storedKey = Digests.sha256(clientKey); - byte[] clientSignature = hmacSha256(storedKey, authMessage.getBytes(StandardCharsets.UTF_8)); - byte[] clientProof = xor(clientKey, clientSignature); - - String clientFinalMessage = clientFinalWithoutProof - + ",p=" + Base64.getEncoder().encodeToString(clientProof); - - // Send SASLResponse: just the final message bytes - PostgresWire.write(out, 'p', clientFinalMessage.getBytes(StandardCharsets.UTF_8)); - out.flush(); - - // Step 4: Read AuthenticationSASLFinal (authType=12) — server signature (ignored) - if (readAuthenticationType(in) != 'R') { - return false; - } - int len3 = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "SASL final message"); - if (PostgresWire.readInt32(in) != 12) { - return false; - } - byte[] serverFinalBytes = new byte[len3 - 8]; - PostgresWire.readFully(in, serverFinalBytes); - - // Step 5: Read final AuthenticationOK - return readAuthOk(in); - } - - private static String generateNonce() { - byte[] bytes = new byte[18]; - new SecureRandom().nextBytes(bytes); - return Base64.getEncoder().withoutPadding().encodeToString(bytes); - } - - private static Map parseScramParams(String msg) { - Map params = new HashMap<>(); - for (String part : msg.split(",")) { - int eq = part.indexOf('='); - if (eq > 0) { - params.put(part.substring(0, eq), part.substring(eq + 1)); - } - } - return params; - } - - private static byte[] pbkdf2HmacSha256(String password, byte[] salt, int iterations) { - try { - PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, 256); - SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); - return skf.generateSecret(spec).getEncoded(); - } catch (Exception e) { - throw new RuntimeException("PBKDF2-HMAC-SHA256 failed", e); - } - } - - private static byte[] hmacSha256(byte[] key, String data) { - return hmacSha256(key, data.getBytes(StandardCharsets.UTF_8)); - } - - private static byte[] hmacSha256(byte[] key, byte[] data) { - try { - Mac mac = Mac.getInstance("HmacSHA256"); - mac.init(new SecretKeySpec(key, "HmacSHA256")); - return mac.doFinal(data); - } catch (Exception e) { - throw new RuntimeException("HMAC-SHA256 failed", e); - } - } - - private static byte[] xor(byte[] a, byte[] b) { - byte[] result = new byte[a.length]; - for (int i = 0; i < a.length; i++) { - result[i] = (byte) (a[i] ^ b[i]); - } - return result; - } - - // ── MD5 password ────────────────────────────────────────────────────────── - - private static boolean readAuthOk(InputStream in) throws IOException { - int type = readAuthenticationType(in); - if (type != 'R') { - LOG.warnv("Expected AuthenticationOK from backend, got type={0}", type); - return false; - } - int length = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "authentication response"); - int authType = PostgresWire.readInt32(in); - if (length > 8) { - byte[] extra = new byte[length - 8]; - PostgresWire.readFully(in, extra); - } - return authType == 0; - } - - private static void sendPasswordMessage(OutputStream out, String password) throws IOException { - byte[] pwBytes = password.getBytes(StandardCharsets.UTF_8); - // 'p' + Int32(4 + pwLen + 1) + password + null - PostgresWire.write(out, 'p', pwBytes, new byte[]{0}); - } - - private static String computeMd5Password(String password, String username, byte[] salt) { - MessageDigest md5 = Digests.md5Digest(); - md5.update(password.getBytes(StandardCharsets.UTF_8)); - md5.update(username.getBytes(StandardCharsets.UTF_8)); - String hex1 = HexFormat.of().formatHex(md5.digest()); - - md5.reset(); - md5.update(hex1.getBytes(StandardCharsets.UTF_8)); - md5.update(salt); - return "md5" + HexFormat.of().formatHex(md5.digest()); - } - // ── Post-auth buffering ─────────────────────────────────────────────────── private static List readUntilReadyForQuery(InputStream in) throws IOException { diff --git a/src/test/java/io/floci/aws/core/common/BackendAuthenticatorTest.java b/src/test/java/io/floci/aws/core/common/BackendAuthenticatorTest.java new file mode 100644 index 0000000000..09cdbbc7bc --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/BackendAuthenticatorTest.java @@ -0,0 +1,369 @@ +package io.floci.aws.core.common; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BackendAuthenticatorTest { + + private static final String NONCE = "rOprNGfwEbeRWgbNEkqO"; + private static final String SERVER_FIRST = + "r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096"; + private static final String CLIENT_FINAL = + "c=biws,r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0," + + "p=dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ="; + private static final String SERVER_FINAL = "v=6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="; + + private static PostgresWire.Message auth(int code, byte[]... parts) { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.writeBytes(PostgresWire.int32(code)); + for (byte[] part : parts) { + body.writeBytes(part); + } + return new PostgresWire.Message((byte) 'R', body.toByteArray()); + } + + private static byte[] text(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] saslMechanisms(String... mechanisms) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (String mechanism : mechanisms) { + out.writeBytes(PostgresWire.cStringBytes(mechanism)); + } + out.write(0); + return out.toByteArray(); + } + + @Test + void scramMatchesRfc7677Vector() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + + PostgresWire.Message initial = authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))).orElseThrow(); + assertEquals('p', initial.type()); + PostgresWire.CString mechanism = PostgresWire.cString(initial.body(), 0); + assertEquals("SCRAM-SHA-256", mechanism.value()); + int length = PostgresWire.int32(initial.body(), mechanism.next()); + String clientFirst = new String(initial.body(), mechanism.next() + 4, length, StandardCharsets.UTF_8); + assertEquals("n,,n=user,r=" + NONCE, clientFirst); + assertEquals(mechanism.next() + 4 + length, initial.body().length); + + PostgresWire.Message response = authenticator.answer(auth(11, text(SERVER_FIRST))).orElseThrow(); + assertEquals('p', response.type()); + assertEquals(CLIENT_FINAL, new String(response.body(), StandardCharsets.UTF_8)); + + assertTrue(authenticator.answer(auth(12, text(SERVER_FINAL))).isEmpty()); + } + + @Test + void wrongServerSignatureFails() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + authenticator.answer(auth(11, text(SERVER_FIRST))); + + IOException failure = assertThrows(IOException.class, + () -> authenticator.answer(auth(12, text("v=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")))); + assertEquals("backend server signature mismatch", failure.getMessage()); + } + + @Test + void foreignServerNonceFails() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text("r=other,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096")))); + } + + @Test + void aServerNonceEqualToTheClientNonceFails() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text("r=" + NONCE + ",s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096")))); + assertEquals("backend SCRAM nonce does not extend the client nonce", refused.getMessage()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void authenticationOkBeforeTheServerSignatureIsRefused(boolean scramOnly) throws Exception { + BackendAuthenticator afterInitial = new BackendAuthenticator("user", "pencil", NONCE, "user", scramOnly); + afterInitial.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + assertThrows(IOException.class, () -> afterInitial.answer(auth(0))); + + BackendAuthenticator afterContinue = new BackendAuthenticator("user", "pencil", NONCE, "user", scramOnly); + afterContinue.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + afterContinue.answer(auth(11, text(SERVER_FIRST))); + IOException refused = assertThrows(IOException.class, () -> afterContinue.answer(auth(0))); + assertEquals("backend accepted the login before proving its SCRAM signature", refused.getMessage()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void authenticationOkAfterAVerifiedServerSignatureIsAccepted(boolean scramOnly) throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user", scramOnly); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + PostgresWire.Message response = authenticator.answer(auth(11, text(SERVER_FIRST))).orElseThrow(); + assertEquals(CLIENT_FINAL, new String(response.body(), StandardCharsets.UTF_8)); + authenticator.answer(auth(12, text(SERVER_FINAL))); + + assertTrue(authenticator.answer(auth(0)).isEmpty()); + } + + @Test + void tooManyServerIterationsAreRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(11, + text("r=" + NONCE + "x,s=W22ZaJ0SNY7soEsUEjb6gQ==,i=" + (BackendAuthenticator.MAX_ITERATIONS + 1))))); + assertEquals("backend asks for 1000001 SCRAM iterations, more than 1000000", refused.getMessage()); + } + + @Test + void anEmptySaltIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text("r=" + NONCE + "x,s=,i=4096")))); + assertEquals("backend SCRAM salt is empty", refused.getMessage()); + } + + @Test + void aMandatoryExtensionIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text("m=ext," + SERVER_FIRST)))); + assertEquals("backend SCRAM message asks for a mandatory extension", refused.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {",r=" + NONCE + "y", ",s=QUJD", ",i=1"}) + void aRepeatedServerFirstAttributeIsRefused(String repeated) throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text(SERVER_FIRST + repeated)))); + assertEquals("malformed SCRAM message from the backend", refused.getMessage()); + } + + @Test + void anOptionalServerFirstExtensionIsIgnored() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + assertTrue(authenticator.answer(auth(11, text(SERVER_FIRST + ",x=future"))).isPresent()); + } + + @Test + void anOversizedServerFirstMessageIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + String padded = SERVER_FIRST + ",x=" + "a".repeat(BackendAuthenticator.MAX_SCRAM_MESSAGE); + + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(11, text(padded)))); + assertEquals("backend SCRAM message is " + padded.length() + " bytes, more than 4096", refused.getMessage()); + } + + @Test + void aServerFirstMessageAtTheLimitIsAnswered() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + String prefix = SERVER_FIRST + ",x="; + String padded = prefix + "a".repeat(BackendAuthenticator.MAX_SCRAM_MESSAGE - prefix.length()); + + assertTrue(authenticator.answer(auth(11, text(padded))).isPresent()); + } + + @ParameterizedTest + @ValueSource(ints = {BackendAuthenticator.MAX_SALT_BYTES + 1, BackendAuthenticator.MAX_SALT_BYTES * 2}) + void anOversizedSaltIsRefused(int bytes) throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + String salt = Base64.getEncoder().encodeToString(new byte[bytes]); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(11, text("r=" + NONCE + "x,s=" + salt + ",i=4096")))); + assertEquals("backend SCRAM salt is longer than 1024 bytes", refused.getMessage()); + } + + @Test + void aSaltAtTheLimitIsTaken() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + String salt = Base64.getEncoder().encodeToString(new byte[BackendAuthenticator.MAX_SALT_BYTES]); + + assertTrue(authenticator.answer(auth(11, text("r=" + NONCE + "x,s=" + salt + ",i=1"))).isPresent()); + } + + @Test + void anOversizedServerFinalMessageIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + authenticator.answer(auth(11, text(SERVER_FIRST))); + + assertThrows(IOException.class, () -> authenticator.answer(auth(12, + text(SERVER_FINAL + "a".repeat(BackendAuthenticator.MAX_SCRAM_MESSAGE))))); + } + + @Test + void unsupportedMechanismFails() { + BackendAuthenticator authenticator = new BackendAuthenticator("u", "p"); + + assertThrows(IOException.class, + () -> authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256-PLUS")))); + } + + @Test + void productionClientFirstUsesAnEmptyUserNameAndAFreshNonce() throws Exception { + PostgresWire.Message first = new BackendAuthenticator("u", "p") + .answer(auth(10, saslMechanisms("SCRAM-SHA-256"))).orElseThrow(); + PostgresWire.CString mechanism = PostgresWire.cString(first.body(), 0); + String clientFirst = new String(first.body(), mechanism.next() + 4, + first.body().length - mechanism.next() - 4, StandardCharsets.UTF_8); + + assertTrue(clientFirst.startsWith("n,,n=,r=")); + assertTrue(clientFirst.length() > "n,,n=,r=".length() + 20); + } + + @Test + void md5AnswerMatchesPostgresFormula() throws Exception { + byte[] salt = {1, 2, 3, 4}; + MessageDigest md5 = MessageDigest.getInstance("MD5"); + String inner = HexFormat.of().formatHex(md5.digest(text("pu"))); + byte[] outerInput = new byte[inner.length() + 4]; + System.arraycopy(text(inner), 0, outerInput, 0, inner.length()); + System.arraycopy(salt, 0, outerInput, inner.length(), 4); + String expected = "md5" + HexFormat.of().formatHex(md5.digest(outerInput)); + + PostgresWire.Message answer = new BackendAuthenticator("u", "p").answer(auth(5, salt)).orElseThrow(); + + assertEquals('p', answer.type()); + assertArrayEquals(PostgresWire.cStringBytes(expected), answer.body()); + } + + @Test + void cleartextAnswerSendsThePassword() throws Exception { + PostgresWire.Message answer = new BackendAuthenticator("u", "secret").answer(auth(3)).orElseThrow(); + + assertEquals('p', answer.type()); + assertArrayEquals(PostgresWire.cStringBytes("secret"), answer.body()); + } + + @Test + void authenticationOkNeedsNoAnswer() throws Exception { + assertTrue(new BackendAuthenticator("u", "p").answer(auth(0)).isEmpty()); + } + + @Test + void scramOnlyRefusesACleartextRequestWithoutSendingThePassword() { + BackendAuthenticator authenticator = new BackendAuthenticator("u", "secret", true); + + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(3))); + + assertEquals("backend asks for a cleartext password where only SCRAM-SHA-256 is accepted", + refused.getMessage()); + assertFalse(refused.getMessage().contains("secret")); + } + + @Test + void scramOnlyRefusesAnMd5Request() { + BackendAuthenticator authenticator = new BackendAuthenticator("u", "p", true); + + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(5, new byte[] {1, 2, 3, 4}))); + + assertEquals("backend asks for an MD5 password where only SCRAM-SHA-256 is accepted", refused.getMessage()); + } + + @Test + void scramOnlyAcceptsATrustingServerThatAsksForNothing() throws Exception { + assertTrue(new BackendAuthenticator("u", "p", true).answer(auth(0)).isEmpty()); + } + + @Test + void theGeneralModeStillAnswersEveryMethod() throws Exception { + assertTrue(new BackendAuthenticator("u", "p", false).answer(auth(3)).isPresent()); + assertTrue(new BackendAuthenticator("u", "p", false).answer(auth(5, new byte[] {1, 2, 3, 4})).isPresent()); + assertTrue(new BackendAuthenticator("u", "p", false).answer(auth(0)).isEmpty()); + } + + @ParameterizedTest + @ValueSource(ints = {3, 5}) + void aPasswordRequestMidScramIsRefusedWithoutSendingThePassword(int code) throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user", false); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + + IOException afterInitial = assertThrows(IOException.class, + () -> authenticator.answer(auth(code, new byte[] {1, 2, 3, 4}))); + assertTrue(afterInitial.getMessage().endsWith("after the authentication started")); + assertFalse(afterInitial.getMessage().contains("pencil")); + + authenticator.answer(auth(11, text(SERVER_FIRST))); + assertThrows(IOException.class, () -> authenticator.answer(auth(code, new byte[] {1, 2, 3, 4}))); + } + + @Test + void aSecondPasswordRequestIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("u", "secret"); + authenticator.answer(auth(5, new byte[] {1, 2, 3, 4})); + + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(3))); + assertEquals("backend asks for a cleartext password after the authentication started", refused.getMessage()); + } + + @Test + void aSecondSaslExchangeIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + authenticator.answer(auth(11, text(SERVER_FIRST))); + authenticator.answer(auth(12, text(SERVER_FINAL))); + + IOException refused = assertThrows(IOException.class, + () -> authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256")))); + assertEquals("backend starts a second authentication exchange", refused.getMessage()); + } + + @Test + void aSaslExchangeAfterAPasswordIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("u", "secret"); + authenticator.answer(auth(3)); + + assertThrows(IOException.class, () -> authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256")))); + } + + @Test + void aRepeatedSaslContinueOrFinalIsRefused() throws Exception { + BackendAuthenticator authenticator = new BackendAuthenticator("user", "pencil", NONCE, "user"); + authenticator.answer(auth(10, saslMechanisms("SCRAM-SHA-256"))); + authenticator.answer(auth(11, text(SERVER_FIRST))); + assertThrows(IOException.class, () -> authenticator.answer(auth(11, text(SERVER_FIRST)))); + + authenticator.answer(auth(12, text(SERVER_FINAL))); + IOException refused = assertThrows(IOException.class, () -> authenticator.answer(auth(12, text(SERVER_FINAL)))); + assertEquals("unexpected SASL final from the backend", refused.getMessage()); + } + + @Test + void unknownAuthenticationCodeFails() { + assertThrows(IOException.class, () -> new BackendAuthenticator("u", "p").answer(auth(7))); + } +} diff --git a/src/test/java/io/floci/aws/core/common/SaslPrepTest.java b/src/test/java/io/floci/aws/core/common/SaslPrepTest.java new file mode 100644 index 0000000000..40059b6b98 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/SaslPrepTest.java @@ -0,0 +1,75 @@ +package io.floci.aws.core.common; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +class SaslPrepTest { + + @ParameterizedTest + @ValueSource(strings = {"pencil", "", "with space", "tab\there", "ctl\u0007"}) + void anAsciiPasswordIsTakenAsItIs(String password) { + assertSame(password, SaslPrep.prepare(password)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + // C.1.2 spaces become U+0020 + "pass word|pass word", + "pass word|pass word", + // B.1 characters are mapped to nothing + "pa­ss‍word|password", + "I­X|IX", + // NFKC + "fix|fix", + "Ⅸ|IX", + "ª|a", + "Café|Café", + "été|été", + }) + void aNonAsciiPasswordIsMappedAndNormalized(String password, String prepared) { + assertEquals(prepared, SaslPrep.prepare(password)); + } + + @ParameterizedTest + @ValueSource(strings = { + // a prohibited character after the mapping: a control, private use, a non-character + "é\u0007", + "é", + "é﷐", + // left-to-right and right-to-left characters together + "אa", + // right-to-left, but not first and last + "א1", + // C.8 prohibits U+0341 and U+0340, checked before NFKC replaces them with U+0301 and U+0300 + "pa\u00E9s\u015B\u0341", + "\u00E9\u0340", + // nothing left after the mapping + "­", + }) + void anInvalidPreparationFallsBackToThePasswordAsGiven(String password) { + assertSame(password, SaslPrep.prepare(password)); + } + + @Test + void aRightToLeftPasswordThatStartsAndEndsRightToLeftIsPrepared() { + assertEquals("א1ב", SaslPrep.prepare("א1ב")); + } + + @Test + void theSaltedPasswordIsDerivedFromThePreparedPassword() throws Exception { + byte[] salt = {1, 2, 3, 4, 5, 6, 7, 8}; + PBEKeySpec spec = new PBEKeySpec("pass word".toCharArray(), salt, 4096, 256); + byte[] expected = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded(); + + assertArrayEquals(expected, BackendAuthenticator.saltedPassword("pass word", salt, 4096)); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java index be9ac4cc5e..74ec68355f 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.rds.proxy; import io.floci.aws.config.FlociCertificateAuthority; +import io.floci.aws.core.common.BackendAuthenticator; import io.floci.aws.core.common.PostgresWire; import io.floci.aws.services.acm.CertificateGenerator; import io.floci.aws.services.acm.model.KeyAlgorithm; @@ -33,11 +34,13 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; +import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -46,6 +49,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.LogRecord; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -209,9 +213,12 @@ class PostgresProtocolHandlerTest { void rejectsOversizedSaslContinuationMessage() throws Exception { ByteArrayOutputStream backendInput = new ByteArrayOutputStream(); DataOutputStream backendOut = new DataOutputStream(backendInput); + byte[] mechanisms = PostgresWire.cStringBytes("SCRAM-SHA-256"); backendOut.writeByte('R'); - backendOut.writeInt(8); + backendOut.writeInt(8 + mechanisms.length + 1); backendOut.writeInt(10); + backendOut.write(mechanisms); + backendOut.writeByte(0); backendOut.writeByte('R'); backendOut.writeInt(1_048_577); @@ -225,6 +232,50 @@ class PostgresProtocolHandlerTest { error.getMessage()); } + @Test + void logsInToAScramBackendThatProvesItsSignature() throws Exception { + MemorySocket client = new MemorySocket(startupAndPassword()); + + PostgresProtocolHandler.AuthenticatedSession session = authenticateAgainst(client, + server -> mockScramBackend(server, "adminpass", false)); + + assertNotNull(session); + DataInputStream clientIn = new DataInputStream( + new ByteArrayInputStream(client.getOutputStream().toByteArray())); + readCleartextPasswordChallenge(clientIn); + readAuthenticationOk(clientIn); + readReadyForQuery(clientIn); + session.backend().close(); + } + + @Test + void refusesAScramBackendWhoseServerSignatureIsWrong() throws Exception { + MemorySocket client = new MemorySocket(startupAndPassword()); + + PostgresProtocolHandler.AuthenticatedSession session = authenticateAgainst(client, + server -> mockScramBackend(server, "adminpass", true)); + + assertNull(session); + DataInputStream clientIn = new DataInputStream( + new ByteArrayInputStream(client.getOutputStream().toByteArray())); + readCleartextPasswordChallenge(clientIn); + Map error = readErrorResponse(clientIn); + assertEquals("FATAL", error.get('S')); + assertEquals("08006", error.get('C')); + assertEquals("Backend database authentication failed", error.get('M')); + } + + @Test + void logsInToAnMd5Backend() throws Exception { + MemorySocket client = new MemorySocket(startupAndPassword()); + + PostgresProtocolHandler.AuthenticatedSession session = authenticateAgainst(client, + server -> mockMd5Backend(server, "dbadmin", "adminpass")); + + assertNotNull(session); + session.backend().close(); + } + @ParameterizedTest @CsvSource({ "auth_db, postgres, auth_db", @@ -2514,6 +2565,120 @@ class PostgresProtocolHandlerTest { } } + @FunctionalInterface + private interface MockBackend { + void serve(ServerSocket server) throws Exception; + } + + /** Authenticates {@code client} with the proxy against {@code backend}, and fails on the backend's failure. */ + private PostgresProtocolHandler.AuthenticatedSession authenticateAgainst(MemorySocket client, + MockBackend backend) throws Exception { + try (ServerSocket server = new ServerSocket(0)) { + AtomicReference backendFailure = new AtomicReference<>(); + Thread backendThread = Thread.ofVirtual().start(() -> { + try { + backend.serve(server); + } catch (Throwable e) { + backendFailure.set(e); + } + }); + PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate( + client, () -> connectTestSocket("localhost", server.getLocalPort()), + "dbadmin", "adminpass", "postgres", + false, testSigV4Validator(), testBinding(), testTlsCertificates(), + (user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000); + backendThread.join(5_000); + assertFalse(backendThread.isAlive(), "backend thread did not terminate"); + assertNull(backendFailure.get(), () -> "backend failed: " + backendFailure.get()); + return session; + } + } + + private static void writeAuthentication(DataOutputStream out, int code, byte[]... parts) throws IOException { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.write(PostgresWire.int32(code)); + for (byte[] part : parts) { + body.write(part); + } + writeMessage(out, 'R', body.toByteArray()); + } + + private static byte[] readPasswordMessageBody(DataInputStream in) throws IOException { + assertEquals('p', in.readByte()); + return in.readNBytes(in.readInt() - 4); + } + + private static void readBackendStartup(DataInputStream in) throws IOException { + int length = in.readInt(); + assertEquals(STARTUP_PROTOCOL_VERSION, in.readInt()); + in.readNBytes(length - 8); + } + + /** + * A backend that logs the proxy in with SCRAM-SHA-256: it checks the client's proof, then sends + * its own signature, or, with {@code forgeSignature}, one that does not match and nothing after. + */ + private static void mockScramBackend(ServerSocket server, String password, boolean forgeSignature) + throws Exception { + try (Socket socket = acceptTestSocket(server)) { + DataInputStream in = new DataInputStream(socket.getInputStream()); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + readBackendStartup(in); + writeAuthentication(out, 10, PostgresWire.cStringBytes("SCRAM-SHA-256"), new byte[] {0}); + + byte[] initial = readPasswordMessageBody(in); + PostgresWire.CString mechanism = PostgresWire.cString(initial, 0); + assertEquals("SCRAM-SHA-256", mechanism.value()); + String clientFirst = new String(initial, mechanism.next() + 4, initial.length - mechanism.next() - 4, + StandardCharsets.UTF_8); + String clientFirstBare = clientFirst.substring("n,,".length()); + String nonce = clientFirstBare.substring(clientFirstBare.indexOf("r=") + 2) + "backend"; + byte[] salt = "floci-test-salt!".getBytes(StandardCharsets.UTF_8); + String serverFirst = "r=" + nonce + ",s=" + Base64.getEncoder().encodeToString(salt) + ",i=4096"; + writeAuthentication(out, 11, serverFirst.getBytes(StandardCharsets.UTF_8)); + + String clientFinal = new String(readPasswordMessageBody(in), StandardCharsets.UTF_8); + int proofAt = clientFinal.indexOf(",p="); + byte[] proof = Base64.getDecoder().decode(clientFinal.substring(proofAt + 3)); + byte[] authMessage = (clientFirstBare + "," + serverFirst + "," + clientFinal.substring(0, proofAt)) + .getBytes(StandardCharsets.UTF_8); + byte[] salted = BackendAuthenticator.saltedPassword(password, salt, 4096); + byte[] clientKey = BackendAuthenticator.hmac(salted, "Client Key".getBytes(StandardCharsets.UTF_8)); + byte[] clientSignature = BackendAuthenticator.hmac( + MessageDigest.getInstance("SHA-256").digest(clientKey), authMessage); + for (int i = 0; i < clientKey.length; i++) { + assertEquals(clientKey[i], (byte) (proof[i] ^ clientSignature[i]), "client proof"); + } + byte[] serverSignature = forgeSignature ? new byte[32] : BackendAuthenticator.hmac( + BackendAuthenticator.hmac(salted, "Server Key".getBytes(StandardCharsets.UTF_8)), authMessage); + writeAuthentication(out, 12, + ("v=" + Base64.getEncoder().encodeToString(serverSignature)).getBytes(StandardCharsets.UTF_8)); + if (forgeSignature) { + // The proxy refuses the login here and closes the connection, so no AuthenticationOk is sent. + in.readAllBytes(); + return; + } + writeAuthentication(out, 0); + writeReadyForQuery(out); + } + } + + /** A backend that logs the proxy in with MD5, checking its answer. */ + private static void mockMd5Backend(ServerSocket server, String user, String password) throws Exception { + try (Socket socket = acceptTestSocket(server)) { + DataInputStream in = new DataInputStream(socket.getInputStream()); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + readBackendStartup(in); + byte[] salt = {9, 8, 7, 6}; + writeAuthentication(out, 5, salt); + + String expected = BackendAuthenticator.md5Answer(user, password, salt); + assertArrayEquals(PostgresWire.cStringBytes(expected), readPasswordMessageBody(in)); + writeAuthentication(out, 0); + writeReadyForQuery(out); + } + } + private static void mockBackendClosesDuringBridge(ServerSocket server) throws IOException { try (Socket socket = acceptTestSocket(server)) { DataInputStream in = new DataInputStream(socket.getInputStream());