Skip to content

Misc security fixes from review - #3

Merged
sehrope merged 150 commits into
pgjdbc:mainfrom
sehrope:misc-security-fixes-post-review-20261129
Nov 29, 2026
Merged

sehrope merged 150 commits into
pgjdbc:mainfrom
sehrope:misc-security-fixes-post-review-20261129

Conversation

@sehrope

@sehrope sehrope commented Nov 29, 2026

Copy link
Copy Markdown
Member

Series of security fixes from automated review. Some of which came about after identifying related items in pgjdbc.

Plan is to have this run through CI and merge it. And then get a snapshot release finally published out.

The orchestration accepted AuthenticationOk at any point, so a peer that
answered the SCRAM client-first or client-final with Ok instead of
AuthenticationSASLFinal completed the login without ever proving it knew
the password. Below verify-ca that is anyone in the middle of the TLS
session, and channelBinding=require and require_auth=scram-sha-256 did
not stop it, since both pass once SCRAM has started.

Track completion in ScramMechanism, and give Authenticator a hook the
orchestration calls on Ok so StandardAuthenticator can refuse it while a
started exchange is unfinished, as libpq does.
Covers Ok after the client-first and after the client-final, the
accepted case after a verified server signature, and the same refusal
end to end through the startup orchestration.
PGConnectionPoolDataSource built its native counterpart from the server,
port and database alone, the same defect 5ea2655 fixed for the XA
source. A pool configured with sslmode=verify-full therefore fell back
to plaintext against a server that declined TLS and sent the startup
message, where the simple and XA sources refused. This is the entry
point application servers instantiate, so it is the common one.

Mirror the XA source: the compat defaults, then the bag. Both now also
forward the login timeout, which neither did.
A loopback server that declines TLS must see no plaintext startup
message from the simple, pooling or XA source under sslmode=require.
A peer that answered the startup message with ParameterStatus,
BackendKeyData and ReadyForQuery and no authentication message at all
completed the handshake. require_auth and channelBinding=require are
enforced in the AuthenticationOk arm, so they never ran: a MITM below
verify-ca, or a hostile pooler, could downgrade a connection configured
to insist on SCRAM to no authentication.

Refuse those three messages until AuthenticationOk has arrived, matching
libpq's "expected authentication request from server".
PgEncodings.toCharset throws for an encoding the driver cannot decode,
and the throw came out of the read loop with the rest of the response
still on the wire and the connection still usable. On a pre-14 server,
which reports client_encoding before CommandComplete, the next statement
then read the SET's tail and the one after it received the previous
statement's rows: a silent one-statement result shift. On 14 and later
the next statement tripped over a stale ReadyForQuery instead.

Mark the connection broken before rethrowing.
The text array parser recursed once per '{' with no limit, so a server,
pooler or MITM could send an array value of a few thousand nested
braces, well inside every SizeLimits bound, and the getter threw
StackOverflowError instead of a PgException. The binary decoder already
refuses more than PostgreSQL's six dimensions; apply the same bound to
the text parser.
PgSimpleDataSource spliced serverName and databaseName into a URL
unencoded, and the URL's query values outrank the data source's own
properties. A database name such as "app?sslmode=disable&user=x&
application_name=" therefore turned off the configured TLS policy and
replaced the user, and a server name of the same shape could also
redirect the connection, from whoever supplies the bean properties (an
admin UI, JNDI, a multi-tenant host).

Percent-encode the database name, as PgDriver already does for query
values, and refuse a server name containing a character that would end
the host part of the URL.
When the driver declined the URL (no jdbc: prefix, a scheme typo, or
claimPostgresqlScheme=never), the SQLException quoted it verbatim, and
a URL carries a password in its userinfo or as password= often enough
for that to leak it into logs (ADR-0010). Run it through the same
redactor the compat data source uses.
BaseDataSource.getUrl spliced the server names and the bag keys into the
URL raw. A server name such as "h/realdb?sslmode=disable&x=" replaced the
database, and its trailing "x=" swallowed the first bag property after
it, which in the reproduction was the explicitly configured
sslmode=verify-full: the compat driver then connected to a non-TLS
server and, with its pgjdbc credential defaults, sent the password in
the clear. Upstream pgjdbc concatenates serverName the same way.

Refuse a server name containing a character that would end the host
part, keeping brackets and colons for IPv6 literals, and encode bag keys
the way values already are (and decode them in setUrl to match).
The core parser accepts jdbc:postgresql://user:pw@host/db, but setUrl
split the host list on ':' with the userinfo still attached. Without a
port the result was a NumberFormatException quoting "pw@host"; with one,
"user:pw@host" became the server name, exposed through getServerName,
getUrl and anything that printed the bean. The server-name check from
the previous fix refuses that now, which is safer but still rejects a
URL the native driver accepts.

Take the userinfo off first and feed it to setUser and setPassword,
decoded as the core parser decodes it, and report a malformed port by
quoting only the port text.
TypeCache.lookupOid put the type name of a bound PgComposite or Struct
into a simple Query as '...' with only the quotes doubled. That is safe
only while standard_conforming_strings is on, and the driver refuses
"off" only at connect time: after a runtime SET, a function or a role
default turns it off, a name such as \' || NULL); DROP TABLE t; --
closed the literal early and the rest ran as SQL. The DROP ran on 14
and 17, and the caller's own query still returned normally.

Use an escape-string literal, doubling backslashes as well as quotes,
which reads the same under either setting. Binding the name would need
the extended protocol, and this lookup also runs in SIMPLE query mode.
… standard

PGConnection.escapeLiteral doubled quotes only, on the premise that
SessionBootstrap refuses standard_conforming_strings=off. That holds at
connect time and no later: after a runtime SET, a function or a role
default turns it off, escapeLiteral("\'; DROP TABLE v; --") spliced into
'...' dropped the table on 17. pgjdbc doubles backslashes when the
setting is off, so ported code that relied on it became injectable on a
jar swap.

Read the session's current setting on each call and double backslashes
when it is off, as pgjdbc does.
The ongres SCRAM client throws IllegalArgumentException for a bad base64
salt or a non-positive iteration count, and only ScramException was
caught, so a server or a MITM below verify-ca could make connect fail
with a raw IllegalArgumentException that PgDriver does not turn into an
SQLException (ADR-0007). Wrap it the same way, and keep the send outside
the try so an I/O failure still passes through as itself.
sslrootcert, sslcert, sslkey, sslcrl and the pgpass path were read with
no check of what the path named. /dev/zero or /dev/urandom ran the heap
out (or spun), and a FIFO or /dev/stdin blocked the connect forever,
since loginTimeout does not interrupt a file read. The pgpass path was
partly covered by its 0600 check, which an owner-only special file
passes.

Route every such read through one helper that refuses an existing path
that is not a regular file and caps the size at 16 MiB. A missing file
still fails as before, from the open. The unused service-file reader
goes through it too.
The property names a class that is loaded and constructed per connection
attempt. The type check runs before initialization, so only a
SocketFactory subclass ever runs, but which one, and with what argument,
is up to whoever sets the property. Say so where the property is
documented, so it is not wired to a source less trusted than the rest of
the deployment's configuration. pgjdbc's socketFactory has the same
shape.
A repeated AuthenticationSASL replaced the in-flight SCRAM exchange.
The first exchange's driver-owned secret was then unreachable, so
cleanup() never zeroed it (ADR-0010), and a provider was asked for a
fresh token each time. No server restarts the exchange; refuse it.
PullResultStream allocated its transient row only when the
RowDescription declared columns, so SELECT FROM t, whose description is
empty but which still sends a DataRow per row, threw a
NullPointerException from next() and left the connection busy until the
stream was closed. The pipeline stream already handles this.

Allocate the row for every result still open after priming; one that
ended there (a command, a zero-row result, an empty query) still skips
it.
A typname match could pick a domain named hstore in any schema, another
session's temp schema included.
The entry's settings, sslmode included, were silently dropped.
ProtocolException is not a PgException, so it escaped the markBroken
catches and left the connection busy but not broken.
…ocommit

The synced windows were reported as succeeded, and their keys kept,
though the failed transaction block rolls them back.
…as the backend does

Each put placeholders where the server saw a literal, or the reverse.
…in keyword search

x$returning matched RETURNING, so generated keys were not requested.
Near the cap the buffer doubled to Integer.MAX_VALUE, which the JVM
refuses with an OutOfMemoryError. The default cap now admits the
largest message a server builds.
A server repeating password requests or notices kept the handshake open
forever; loginTimeout is off by default.
Until AuthenticationOk any message could be as long as the 1 GiB cap,
so an unauthenticated peer could make the driver buffer that much.
The driver refused every statement once the transaction failed, ROLLBACK
included. Under autocommit, after the caller's own BEGIN, rollback() is
refused too, so the session could not recover. The refusal also carried
no SQLSTATE, so JDBC reported it as a connection failure; the server's
25P02 is an ordinary error. Autosave recovery is unchanged.
The test encrypted the key at runtime and re-wrapped the cipher's
parameters as generic PBES2. On JDK 25 that drops the PRF, so the key
decoded as PBEWithHmacSHA1AndAES_256 and would not decrypt. The driver
reads openssl's output fine on both JDKs.
@sehrope

sehrope commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Test failure in CI running on JDK25 due to changes which algos are supported. Fix was to scrap generating the cert on the fly in the test and having it generated in advance with openssl.

VirtualThreadPinningIT keeps failing on JDK 25 and its report cut each
stack to eight frames with no event fields, which is not enough to tell
where the pin comes from. On failure it now reports every field the
running JDK records for jdk.VirtualThreadPinned (pinning reason,
blocking operation, duration, threads where present, and says which
are absent), the full stack with line, bci and frame type plus whether
JFR truncated it, and the JVM version.

The failsafe argLine raises the JFR stack depth to 128 frames. The
recording is now dumped under target/jfr and kept when the test fails,
and the integration jobs upload it as an artifact on failure.

Diagnostics only: the workload, event filter and assertion are
unchanged.
@sehrope
sehrope force-pushed the misc-security-fixes-post-review-20261129 branch from 71ab74c to 9018c39 Compare November 29, 2026 18:06
The recurring JDK 25 failures were all virtual threads waiting on the
class initializer of sun.nio.ch.Poller, which the JDK sets up lazily on
the first virtual-thread socket park. Fifty threads reaching it at once
pin their carriers there (JDK-8369238), which is not a driver pin.

Run the same blocking-read workload on one virtual thread before the
recording starts so the poller is already initialized. The zero-pin
assertion, the event filter and the diagnostics are unchanged.
@sehrope

sehrope commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Some more flakiness in the thread pinning check. Added a commit to resolve that too. So looks good now.

@sehrope
sehrope merged commit 6a9b735 into pgjdbc:main Nov 29, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant