feat(dsql): answer a PostgreSQL server's password challenge (#8690)

* feat(dsql): answer a PostgreSQL server's password challenge
* refactor(dsql): move BackendAuthenticator beside PostgresWire
* test(dsql): run the AuthenticationOk checks over both SCRAM modes
* fix(dsql): refuse an empty SCRAM salt
* fix(dsql): refuse a SCRAM mandatory extension and repeated attributes
* fix(dsql): refuse a password request once the authentication started
* fix(dsql): allow one SASL exchange per connection
* fix(dsql): require the server nonce to extend the client nonce
* fix(dsql): bound the SCRAM messages and salt a backend sends
* fix(dsql): prepare a SCRAM password with SASLprep as PostgreSQL does
* refactor(rds): log the proxy in to its backend through BackendAuthenticator
* fix(dsql): check a SCRAM password before NFKC, as PostgreSQL does
* test(rds): take the mock MD5 backend's expected answer from BackendAuthenticator
This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-17 19:03:32 -04:00
1 parent 8e88ba0915
commit 1942378624
7 files changed
+1095 -217

No files matched your search

@@ -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<PostgresWire.Message> 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);
}
}
@@ -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.
*
* <p>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;
}
}
@@ -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;
* <li>Challenge client with AuthenticationCleartextPassword
* <li>Read client password
* <li>Validate (IAM SigV4 or plain password)
* <li>Connect to backend with MD5 or SCRAM-SHA-256 auth
* <li>Connect to backend with cleartext, MD5 or SCRAM-SHA-256 auth, checking SCRAM's server signature
* <li>Buffer backend messages until ReadyForQuery
* <li>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<PostgresWire.Message> 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=<nonce>,s=<base64-salt>,i=<iterations>
Map<String, String> 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<String, String> parseScramParams(String msg) {
Map<String, String> 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<byte[]> readUntilReadyForQuery(InputStream in) throws IOException {