pg.ddx.io  GitHub: pgjdbc/pgjdbc (issues + PRs as email threads)  
help / color / mirror / Atom feed
From: artemgavrilov (@artemgavrilov) <noreply+artemgavrilov@github.com>
To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>
Subject: [pgjdbc/pgjdbc] PR #4513: fix: requireAuth no longer requires gss on every GSS-encrypted connection
Date: Sat, 31 Oct 2026 14:41:46 +0000
Message-ID: <gh-pgjdbc-pgjdbc-4513@github.com> (raw)

`requireAuth` has refused valid connections since it was added in 42.7.11:

  - `requireAuth=scram-sha-256` with `gssEncMode=require` was refused even after the client authenticated with SCRAM.
  - `requireAuth=gss` was refused when the server asked for Kerberos authentication without GSS encryption.

Establishing GSS encryption marked authentication as finished, so AuthenticationOk required `gss` whenever the connection was encrypted. The JGSS path, on the other hand, never marked authentication as finished.

This PR follows libpq (`check_expected_areq` in `fe-auth.c`): a completed authentication exchange satisfies `requireAuth`, and GSS encryption counts as `gss` when the server sends no authentication request.

The SSPI path had a similar problem: it marked authentication as finished on every AuthenticationGSSContinue and never after the first token. It now does so once the security context is established, as libpq
  does. This change is not tested: no test in the project runs SSPI, which needs a Windows client and a server set up for it.

### Changes in behaviour

  - A list of `!` options such as `requireAuth=!gss` allows `none`, so it now accepts a GSS-encrypted connection that the server lets in without a request. libpq does the same. `!gss,!none` or `gssEncMode=disable`
  refuses it.
  - With `gss` allowed on a GSS-encrypted connection, an exchange of another method that the server started and did not finish is accepted, as in libpq.
  - The driver cannot see which `pg_hba.conf` rule matched, so with `gss` allowed it also accepts a `trust` rule over GSS encryption. libpq has the same limit. The docs say this.
  - `PGStream.isFinishedAuthenticationRequests()` and `setFinishedAuthenticationRequests()` are removed. They are public, but `org.postgresql.core` is internal, and they only arrived in 42.7.11.
  - `ISSPIClient` gets a new abstract method. The driver loads only its own `SSPIClient`, so I don't expect this to affect anyone.
  - The refusal at AuthenticationOk used to say "Authentication method is not allowed by requireAuth". It now says what happened: the server requested nothing, it ended the exchange early, or it accepted a
  GSS-encrypted connection without a request.

### All Submissions:

* [x] Have you followed the guidelines in our [Contributing](https://github.com/pgjdbc/pgjdbc/blob/master/CONTRIBUTING.md) document?
* [x] Have you checked to ensure there aren't other open [Pull Requests](../../pulls) for the same update/change?

<!-- You can erase any parts of this template not applicable to your Pull Request. -->

### New Feature Submissions:

1. [x] Does your submission pass tests?
2. [x] Does `./gradlew styleCheck` pass ?

### Changes to Existing Features:

* [x] Does this break existing behaviour? If so please explain.
* [x] Have you added an explanation of what your changes do and why you'd like us to include them?
* [x] Have you written new tests for your core changes, as applicable?
* [x] Have you successfully run tests with your changes locally?


inline patch 1: CHANGELOG.md, docs/content/documentation/use.md, pgjdbc-gss-test/src/test/java/org/postgresql/test/gss/GssEncryptionTest.java and 7 more (+325/-27 lines) download inline-1.patchdiff --git a/CHANGELOG.md b/CHANGELOG.md index 121da767b5..c14f287188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). ## [Unreleased] ### Fixed +* fix: `requireAuth` no longer requires `gss` on every GSS-encrypted connection. `requireAuth=scram-sha-256` with `gssEncMode=require` was refused even after the client authenticated with SCRAM, and `requireAuth=gss` was refused when the server asked for Kerberos authentication without GSS encryption. As in libpq, a completed authentication exchange now satisfies `requireAuth`, and GSS encryption counts as `gss` when the server sends no authentication request. A list of `!` options such as `requireAuth=!gss` allows `none`, so it now accepts a GSS-encrypted connection that the server lets in without a request, as libpq does. Use `!gss,!none` or `gssEncMode=disable` to refuse it. This affects 42.7.11 through 42.7.14 +* fix: with `requireAuth` set, an SSPI exchange now counts as finished only once the security context is established. Before, a connection was refused when SSPI finished in its first round, and accepted when the server sent AuthenticationOk before the exchange was complete. This affects 42.7.11 through 42.7.14 * fix: `PGStream.skip` no longer loops forever when the connection ends while the driver is discarding bytes, and no longer mistakes a stream that skips nothing for one that has ended. `InputStream.skip` may return zero with more data still coming, which a stream supplied through the `socketFactory` property is free to do; the driver now reads a byte in that case and treats only `-1` as the end [PR #4358](https://github.com/pgjdbc/pgjdbc/pull/4358) * fix: `LargeObjectManager` operations now work inside an active XA transaction. Since 42.7.13 an XA branch keeps the caller's `autoCommit=true`, and the guard rejected large objects as if the connection were idle. It now checks the server transaction state (`getTransactionState()`) instead of `autoCommit`, so a genuine auto-commit connection with no open transaction is still refused [Issue #4309](https://github.com/pgjdbc/pgjdbc/issues/4309) [PR #4310](https://github.com/pgjdbc/pgjdbc/pull/4310) * fix: batch update counts are no longer secured as committed inside an XA transaction. `BatchResultHandler` treated per-statement progress as durable whenever `autoCommit=true`, but an XA branch keeps `autoCommit=true` while the transaction is open, so a batch that flushed mid-way and then failed could report rolled-back statements as succeeded. Progress is now secured only when no server transaction is open [Issue #4309](https://github.com/pgjdbc/pgjdbc/issues/4309) [PR #4311](https://github.com/pgjdbc/pgjdbc/pull/4311) diff --git a/docs/content/documentation/use.md b/docs/content/documentation/use.md index dd4d097d82..979e0fd2d4 100644 --- a/docs/content/documentation/use.md +++ b/docs/content/documentation/use.md @@ -534,6 +534,12 @@ value in the connection properties will be used. Comma-separated list of acceptable authentication methods. Use '!' prefix to reject methods (e.g., '!password' to reject cleartext). Supported methods: `password`, `md5`, `gss`, `sspi`, `scram-sha-256`, `none`. Cannot mix positive and negative options. Examples: `requireAuth=md5,scram-sha-256` (allow only MD5 or SCRAM-SHA-256), `requireAuth=!password,!none` (reject cleartext and trust authentication). +If the server lets the client in without asking it to authenticate, as with a `trust` rule in `pg_hba.conf`, the +connection fails unless `requireAuth` allows `none`. A list of `!` options allows `none` unless it includes `!none`. +One exception: on a GSS-encrypted connection (see `gssEncMode`), allowing `gss` is enough when the server sends no +authentication request, as with a `gss` rule, because setting up the encryption already authenticated the client with +Kerberos. The driver cannot see which `pg_hba.conf` rule matched, so, as in libpq, this also accepts a `trust` rule +over GSS encryption. * **`scramMaxIterations (`*int*`)`** *Default `100000`*\ Maximum PBKDF2 iteration count that pgjdbc will accept from the server during SCRAM authentication. diff --git a/pgjdbc-gss-test/src/test/java/org/postgresql/test/gss/GssEncryptionTest.java b/pgjdbc-gss-test/src/test/java/org/postgresql/test/gss/GssEncryptionTest.java index ff3ae98e94..5a1048c7f2 100644 --- a/pgjdbc-gss-test/src/test/java/org/postgresql/test/gss/GssEncryptionTest.java +++ b/pgjdbc-gss-test/src/test/java/org/postgresql/test/gss/GssEncryptionTest.java @@ -5,10 +5,13 @@ package org.postgresql.test.gss; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.postgresql.PGProperty; import org.postgresql.jdbc.GSSEncMode; +import org.postgresql.util.PSQLState; import org.junit.jupiter.api.Test; @@ -88,6 +91,34 @@ void gssAuthenticationAndEncryption() throws Exception { assertGssConnection(client, postgres, "test", "test1", "secret1", "SELECT gss_authenticated AND not encrypted from pg_stat_gssapi where pid = pg_backend_pid()", "GSS authenticated and not encrypted"); + + // requireAuth: without GSS encryption the server sends AuthenticationGSS, and the Kerberos + // exchange that answers it meets requireAuth=gss. + client.addProperty(PGProperty.REQUIRE_AUTH, "gss"); + assertGssConnection(client, postgres, "test", "test1", "secret1", + "SELECT gss_authenticated AND not encrypted from pg_stat_gssapi where pid = pg_backend_pid()", + "requireAuth=gss, GSS authenticated and not encrypted"); + + // With GSS encryption and a gss rule the server sends no authentication request at all. + // The encryption meets requireAuth=gss, and nothing meets a requireAuth that leaves gss out. + postgres.enableGss("127.0.0.1", "hostgssenc"); + postgres.reload(); + client.addProperty(PGProperty.GSS_ENC_MODE, GSSEncMode.REQUIRE.value); + assertGssConnection(client, postgres, "test", "test1", "secret1", + "SELECT gss_authenticated AND encrypted from pg_stat_gssapi where pid = pg_backend_pid()", + "requireAuth=gss, GSS authenticated and encrypted"); + client.addProperty(PGProperty.REQUIRE_AUTH, "scram-sha-256"); + assertRefusedByRequireAuth(client, postgres, "test", "test1", "secret1"); + + // GSS encryption followed by a SCRAM exchange meets requireAuth=scram-sha-256: the + // encryption does not have to be allowed as well. + postgres.writePgHba("hostgssenc all all 127.0.0.1/32 scram-sha-256"); + postgres.reload(); + assertGssConnection(client, postgres, "test", "test1", "secret1", + "SELECT encrypted AND NOT gss_authenticated from pg_stat_gssapi where pid = pg_backend_pid()", + "requireAuth=scram-sha-256, SCRAM over GSS encryption"); + // null removes the property, so a later step connects without requireAuth + client.addProperty(PGProperty.REQUIRE_AUTH, null); } finally { if (pg != null) { pg.destroy(); @@ -96,6 +127,15 @@ void gssAuthenticationAndEncryption() throws Exception { } } + private static void assertRefusedByRequireAuth(PgGssConnection client, Postgres postgres, + String database, String user, String password) throws Exception { + SQLException ex = assertThrows(SQLException.class, + () -> client.tryConnect(database, KERBEROS_HOST, postgres.getPort(), user, password).close(), + "requireAuth should refuse the connection; pg_hba.conf:\n" + postgres.readPgHba()); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState(), ex.toString()); + assertTrue(ex.getMessage().contains("GSS-encrypted connection"), ex.getMessage()); + } + private static void assertGssConnection(PgGssConnection client, Postgres postgres, String database, String user, String password, String query, String description) throws Exception { try (Connection connection = diff --git a/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java b/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java index 66de4f6dce..fc88eafd8d 100644 --- a/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java +++ b/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java @@ -107,4 +107,51 @@ public static void checkAuth(@Nullable EnumSet<AuthMethod> allowedMethods, AuthM throw new PSQLException(GT.tr("Authentication method is not allowed by requireAuth"), PSQLState.CONNECTION_REJECTED); } } + + /** + * Refuses an AuthenticationOk that {@code requireAuth} does not allow. Every + * request the server sent was checked by {@link #checkAuth} as it arrived, + * so what is left is a server that lets the client in without a finished + * exchange: it requested nothing, or it sent AuthenticationOk before the + * exchange it requested was complete. libpq makes the same check on + * AUTH_REQ_OK in {@code check_expected_areq}. + * + * @param allowedMethods the methods to allow, or {@code null} to allow + * every method; an empty set refuses every method + * @param requested whether the server sent an authentication request + * @param finished whether the client finished the exchange it was asked for + * @param gssEncrypted whether the connection is GSS-encrypted + * @throws PSQLException with {@link PSQLState#CONNECTION_REJECTED} if the + * connection is not allowed + */ + public static void checkAuthCompleted(@Nullable EnumSet<AuthMethod> allowedMethods, + boolean requested, boolean finished, boolean gssEncrypted) throws PSQLException { + if (allowedMethods == null || finished) { + return; + } + // As in libpq, this also accepts an exchange of another method that the + // server started and did not finish. + if (allowedMethods.contains(NONE) || (gssEncrypted && allowedMethods.contains(GSS))) { + return; + } + if (requested) { + throw new PSQLException( + GT.tr("The server accepted the connection before the authentication exchange was " + + "complete, which requireAuth does not allow."), + PSQLState.CONNECTION_REJECTED); + } + if (gssEncrypted) { + throw new PSQLException( + GT.tr("The server accepted the GSS-encrypted connection without requesting further " + + "authentication, which requireAuth does not allow. Allow ''gss'' in requireAuth " + + "to accept the Kerberos authentication done while setting up GSS encryption, or " + + "set gssEncMode to disable to authenticate without it."), + PSQLState.CONNECTION_REJECTED); + } + throw new PSQLException( + GT.tr("The server accepted the connection without requesting authentication, which " + + "requireAuth does not allow. Check the pg_hba.conf entry the server matched, or " + + "allow ''none'' in requireAuth to accept an unauthenticated connection."), + PSQLState.CONNECTION_REJECTED); + } } diff --git a/pgjdbc/src/main/java/org/postgresql/core/PGStream.java b/pgjdbc/src/main/java/org/postgresql/core/PGStream.java index 78b7363977..e85f116944 100644 --- a/pgjdbc/src/main/java/org/postgresql/core/PGStream.java +++ b/pgjdbc/src/main/java/org/postgresql/core/PGStream.java @@ -120,20 +120,10 @@ public void run() { }; } - private boolean finishedAuthenticationRequests = false; - public boolean isGssEncrypted() { return gssEncrypted; } - public boolean isFinishedAuthenticationRequests() { - return finishedAuthenticationRequests; - } - - public void setFinishedAuthenticationRequests() { - this.finishedAuthenticationRequests = true; - } - boolean gssEncrypted; public void setSecContext(GSSContext secContext) throws GSSException { diff --git a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java index 0ed56e576e..7613257c91 100644 --- a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java +++ b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java @@ -637,7 +637,6 @@ private static PGStream enableGSSEncrypted(PGStream pgStream, GSSEncMode gssEncM PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info)); return void.class; }); - pgStream.setFinishedAuthenticationRequests(); return pgStream; } catch (PSQLException ex) { // allow the connection to proceed @@ -807,8 +806,10 @@ private static void doAuthentication(PGStream pgStream, String host, String user ChannelBinding channelBinding = ChannelBinding.of(info); // Parse requireAuth property for authentication method validation - String requireAuth = PGProperty.REQUIRE_AUTH.getOrDefault(info); - @Nullable EnumSet<AuthMethod> authMethods = AuthMethod.parseRequireAuth(requireAuth); + @Nullable EnumSet<AuthMethod> authMethods = + AuthMethod.parseRequireAuth(PGProperty.REQUIRE_AUTH.getOrDefault(info)); + boolean authRequested = false; + boolean authFinished = false; try { int messages = 0; @@ -903,6 +904,11 @@ private static void doAuthentication(PGStream pgStream, String host, String user } } + // Any authentication message other than AuthenticationOk is a request + if (areq != AUTH_REQ_OK) { + authRequested = true; + } + // Process the request. switch (areq) { case AUTH_REQ_MD5: { @@ -931,7 +937,7 @@ private static void doAuthentication(PGStream pgStream, String host, String user } pgStream.sendChar(0); pgStream.flush(); - pgStream.setFinishedAuthenticationRequests(); + authFinished = true; break; } @@ -948,7 +954,7 @@ private static void doAuthentication(PGStream pgStream, String host, String user }); pgStream.sendChar(0); pgStream.flush(); - pgStream.setFinishedAuthenticationRequests(); + authFinished = true; break; } @@ -1016,6 +1022,10 @@ private static void doAuthentication(PGStream pgStream, String host, String user if (useSSPI) { /* SSPI requested and detected as available */ castNonNull(sspiClient).startSSPI(); + // A one-round exchange ends here, and the server answers with AuthenticationOk + if (castNonNull(sspiClient).isComplete()) { + authFinished = true; + } } else { /* Use JGSS's GSSAPI for this request */ AuthenticationPluginManager.withPassword(AuthenticationRequestType.GSS, info, password -> { @@ -1027,6 +1037,7 @@ private static void doAuthentication(PGStream pgStream, String host, String user PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info)); return void.class; }); + authFinished = true; } break; @@ -1035,7 +1046,9 @@ private static void doAuthentication(PGStream pgStream, String host, String user * Only called for SSPI, as GSS is handled by an inner loop in MakeGSS. */ castNonNull(sspiClient).continueSSPI(msgLen - 8); - pgStream.setFinishedAuthenticationRequests(); + if (castNonNull(sspiClient).isComplete()) { + authFinished = true; + } break; case AUTH_REQ_SASL: @@ -1072,19 +1085,12 @@ private static void doAuthentication(PGStream pgStream, String host, String user case AUTH_REQ_SASL_FINAL: castNonNull(scramAuthenticator).handleAuthenticationSASLFinal(msgLen - 4 - 4); saslHandshakeCompleted = true; - pgStream.setFinishedAuthenticationRequests(); + authFinished = true; break; case AUTH_REQ_OK: - if (requireAuth != null) { - // this will happen if the authentication method is trust - if (!pgStream.isFinishedAuthenticationRequests()) { - AuthMethod.checkAuth(authMethods, AuthMethod.NONE); - } - if (pgStream.isGssEncrypted()) { - AuthMethod.checkAuth(authMethods, AuthMethod.GSS); - } - } + AuthMethod.checkAuthCompleted(authMethods, authRequested, + authFinished, pgStream.isGssEncrypted()); /* Cleanup after successful authentication */ LOGGER.log(Level.FINEST, " <=BE AuthenticationOk"); break authloop; // We're done. diff --git a/pgjdbc/src/main/java/org/postgresql/sspi/ISSPIClient.java b/pgjdbc/src/main/java/org/postgresql/sspi/ISSPIClient.java index 02798bebb4..9b9fa8ff22 100644 --- a/pgjdbc/src/main/java/org/postgresql/sspi/ISSPIClient.java +++ b/pgjdbc/src/main/java/org/postgresql/sspi/ISSPIClient.java @@ -22,5 +22,13 @@ public interface ISSPIClient { void continueSSPI(int msgLength) throws SQLException, IOException; + /** + * Returns whether the security context is established, so the server expects no further token + * from the client. + * + * @return true once SSPI negotiation is complete + */ + boolean isComplete(); + void dispose(); } diff --git a/pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java b/pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java index 67ab5e2027..a9dcd6ea2e 100644 --- a/pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java +++ b/pgjdbc/src/main/java/org/postgresql/sspi/SSPIClient.java @@ -265,6 +265,14 @@ public void continueSSPI(int msgLength) throws SQLException, IOException { } } + @Override + public boolean isComplete() { + // Waffle sets the continue flag while InitializeSecurityContext returns + // SEC_I_CONTINUE_NEEDED, and clears it once the context is established. + WindowsSecurityContextImpl sspiContext = this.sspiContext; + return sspiContext != null && !sspiContext.isContinue(); + } + private void sendSSPIResponse(byte[] outToken) throws IOException { /* * The sspiContext now contains a token we can send to the server to start the handshake. Send a diff --git a/pgjdbc/src/test/java/org/postgresql/core/CheckAuthCompletedTest.java b/pgjdbc/src/test/java/org/postgresql/core/CheckAuthCompletedTest.java new file mode 100644 index 0000000000..32571f0c91 --- /dev/null +++ b/pgjdbc/src/test/java/org/postgresql/core/CheckAuthCompletedTest.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2026, PostgreSQL Global Development Group + * See the LICENSE file in the project root for more information. + */ + +package org.postgresql.core; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +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; + +import org.postgresql.util.PSQLException; +import org.postgresql.util.PSQLState; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import java.util.EnumSet; + +/** + * Covers the {@code requireAuth} check the driver makes on AuthenticationOk, where what is left + * to rule out is a server that lets the client in without a finished authentication exchange. + */ +class CheckAuthCompletedTest { + + /** requireAuth is met by an authentication exchange the client completed, whatever it was. */ + @ParameterizedTest + @EnumSource(AuthMethod.class) + void aCompletedExchangeMeetsRequireAuth(AuthMethod method) throws Exception { + EnumSet<AuthMethod> allowed = EnumSet.of(method); + + AuthMethod.checkAuthCompleted(allowed, true, true, false); + AuthMethod.checkAuthCompleted(allowed, true, true, true); + } + + /** + * The server authenticating the connection without asking the client for anything is what + * requireAuth is there to rule out, unless none is among the methods it allows. + */ + @ParameterizedTest + @EnumSource(AuthMethod.class) + void onlyNoneMeetsRequireAuthWithoutAnExchange(AuthMethod method) { + EnumSet<AuthMethod> allowed = EnumSet.of(method); + + if (method == AuthMethod.NONE) { + assertDoesNotThrow(() -> AuthMethod.checkAuthCompleted(allowed, false, false, false)); + return; + } + + PSQLException ex = assertThrows(PSQLException.class, + () -> AuthMethod.checkAuthCompleted(allowed, false, false, false)); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState()); + } + + /** + * Establishing GSS encryption authenticates the client, so the server has no reason to send an + * AuthenticationGSS request, and requireAuth=gss holds all the same. + */ + @Test + void gssEncryptionMeetsRequireAuthGssWithoutAnExchange() throws Exception { + AuthMethod.checkAuthCompleted(EnumSet.of(AuthMethod.GSS), false, false, true); + } + + /** + * GSS encryption stands in for a GSS request only, not for whatever else was required. The + * refusal names gss as what would allow the connection, not none, which would also accept + * trust connections. + */ + @Test + void gssEncryptionDoesNotMeetRequireAuthForAnotherMethod() { + EnumSet<AuthMethod> allowed = EnumSet.of(AuthMethod.SCRAM_SHA_256, AuthMethod.MD5); + + PSQLException ex = assertThrows(PSQLException.class, + () -> AuthMethod.checkAuthCompleted(allowed, false, false, true)); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState()); + assertTrue(ex.getMessage().contains("GSS-encrypted connection"), ex.getMessage()); + assertTrue(ex.getMessage().contains("'gss'"), ex.getMessage()); + assertFalse(ex.getMessage().contains("none"), ex.getMessage()); + } + + /** + * As in libpq, GSS encryption with gss allowed also accepts an exchange of another method that + * the server started and did not finish, as with AuthenticationOk sent before SASLFinal. + */ + @Test + void gssEncryptionCoversAnIncompleteExchangeAsInLibpq() throws Exception { + AuthMethod.checkAuthCompleted( + EnumSet.of(AuthMethod.GSS, AuthMethod.SCRAM_SHA_256), true, false, true); + } + + /** + * A GSS-encrypted connection that then authenticated with, say, SCRAM meets a + * requireAuth naming that method: the encryption does not have to be named as well. + */ + @ParameterizedTest + @EnumSource(value = AuthMethod.class, names = {"SCRAM_SHA_256", "PASSWORD", "MD5"}) + void anExchangeOverGssEncryptionDoesNotAlsoRequireGss(AuthMethod method) throws Exception { + AuthMethod.checkAuthCompleted(EnumSet.of(method), true, true, true); + } + + /** + * The refusal for a server that requested nothing names {@code none} as what would allow the + * connection. Its quotes reach the user only if they are doubled in the source, since GT.tr + * runs every message through MessageFormat. + */ + @Test + void theRefusalWithoutARequestNamesNone() { + PSQLException ex = assertThrows(PSQLException.class, + () -> AuthMethod.checkAuthCompleted( + EnumSet.of(AuthMethod.SCRAM_SHA_256), false, false, false)); + + assertTrue(ex.getMessage().contains("without requesting authentication"), ex.getMessage()); + assertTrue(ex.getMessage().contains("'none'"), ex.getMessage()); + } + + /** + * A server that sends AuthenticationOk before the exchange it requested is complete is refused + * as well. The message says the exchange was not complete and does not suggest allowing none, + * which would let a server skip the rest of any exchange and so weaken requireAuth. + */ + @Test + void anIncompleteExchangeIsRefusedWithoutSuggestingNone() { + PSQLException ex = assertThrows(PSQLException.class, + () -> AuthMethod.checkAuthCompleted( + EnumSet.of(AuthMethod.SCRAM_SHA_256), true, false, false)); + + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState()); + assertTrue(ex.getMessage().contains("before the authentication exchange was complete"), + ex.getMessage()); + assertFalse(ex.getMessage().contains("none"), ex.getMessage()); + } + + /** With requireAuth unset there is nothing to check, however the connection was authenticated. */ + @Test + void anUnsetRequireAuthAllowsEveryOutcome() throws Exception { + AuthMethod.checkAuthCompleted(null, false, false, false); + AuthMethod.checkAuthCompleted(null, false, false, true); + AuthMethod.checkAuthCompleted(null, true, false, false); + AuthMethod.checkAuthCompleted(null, true, true, false); + } +} diff --git a/pgjdbc/src/test/java/org/postgresql/core/RequireAuthConnectTest.java b/pgjdbc/src/test/java/org/postgresql/core/RequireAuthConnectTest.java index ee118f5441..0c4f62b89f 100644 --- a/pgjdbc/src/test/java/org/postgresql/core/RequireAuthConnectTest.java +++ b/pgjdbc/src/test/java/org/postgresql/core/RequireAuthConnectTest.java @@ -7,7 +7,9 @@ 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; import org.postgresql.PGProperty; import org.postgresql.util.PSQLState; @@ -34,7 +36,9 @@ /** * A requireAuth value that excludes every method must refuse the connection * with {@link PSQLState#CONNECTION_REJECTED}, whatever the server asks for, - * and the driver must not send the password. + * and the driver must not send the password. A server that lets the client in + * without a finished exchange must be refused with a message that says which + * of the two happened. */ public class RequireAuthConnectTest { @@ -46,6 +50,15 @@ public class RequireAuthConnectTest { private static final byte[] AUTHENTICATION_OK = {'R', 0, 0, 0, 8, 0, 0, 0, 0}; + /** + * AuthenticationSASL offering SCRAM-SHA-256, then AuthenticationOk before + * the exchange is complete. + */ + private static final byte[] SASL_REQUEST_THEN_OK = + {'R', 0, 0, 0, 23, 0, 0, 0, 10, + 'S', 'C', 'R', 'A', 'M', '-', 'S', 'H', 'A', '-', '2', '5', '6', 0, 0, + 'R', 0, 0, 0, 8, 0, 0, 0, 0}; + private static final String PASSWORD = "secret"; /** The PasswordMessage that carries {@link #PASSWORD}. */ @@ -96,6 +109,40 @@ void refusesTrust() { "SQLState of the refusal"); } + /** + * A server that requests nothing gets a message that says so and names + * none as what would allow the connection. + */ + @Test + void refusesTrustWithAMessageThatNamesNone() { + FakeServer server = new FakeServer(AUTHENTICATION_OK); + SQLException e = assertThrows(SQLException.class, + () -> server.connect("scram-sha-256")); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), e.getSQLState(), + "SQLState of the refusal"); + assertTrue(e.getMessage().contains("without requesting authentication"), + e.getMessage()); + assertTrue(e.getMessage().contains("'none'"), e.getMessage()); + } + + /** + * A server that requests SCRAM and sends AuthenticationOk before the + * exchange is complete is refused. The message must not suggest allowing + * none: that would let a server skip the SCRAM server signature, which + * proves it knows the password, and so weaken requireAuth. + */ + @Test + void refusesAnIncompleteScramExchange() { + FakeServer server = new FakeServer(SASL_REQUEST_THEN_OK); + SQLException e = assertThrows(SQLException.class, + () -> server.connect("scram-sha-256")); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), e.getSQLState(), + "SQLState of the refusal"); + assertTrue(e.getMessage().contains("before the authentication exchange was complete"), + e.getMessage()); + assertFalse(e.getMessage().contains("none"), e.getMessage()); + } + /** Replies with a fixed message and records what the driver writes. */ private static final class FakeServer { /**

view thread (3+ messages)  latest in thread

Message-ID: <gh-pgjdbc-pgjdbc-4513@github.com>
Permalink:  ../gh-pgjdbc-pgjdbc-4513@github.com/

 ·  · 


This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox