mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
8e88ba0915
commit
1942378624
7 files changed
+1095
-217
No files matched your search
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
"password|password",
|
||||
"IX|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));
|
||||
}
|
||||
}
|
||||
@@ -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<Character, String> 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<Throwable> 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());
|
||||
|
||||
Reference in new issue
Block a user