libpq minor TOCTOU violation

From: Peter Eisentraut <peter(at)eisentraut(dot)org>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: libpq minor TOCTOU violation
Date: 2024-08-10 07:10:16
Message-ID: a3356054-14ae-4e7a-acc6-249d19dac20b@eisentraut.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

I was playing with a static analyzer security scanner and it flagged a
time-of-check-time-of-use violation in libpq. I was going to propose a
fix for this on -hackers, since you probably can't do anything
interesting with this, but then I figured I'd better check here first.

libpq checks the permissions of the password file before opening it and
rejects it if the permissions are more permissive than 0600. It does
this in two separate steps, first stat(), then fopen(), which is what
triggers the static analyzer. The standard fix for this kind of thing
is to open the file first and then use fstat() on the file handle for
the permission check.

Note that libpq doesn't check who the owner of the file is or what
directory it is in. The location of the password file can be changed
from its default via libpq connection settings. So it seems to me that
if the location of the password file were a world-writable directory, an
"attacker" could supply a dummy file with 0600 permissions for the
stat() call and then swap it out for a world-readable file with
passwords for the fopen() call, both files owned by the attacker. And
so they could have the libpq application try out passwords on their
behalf. Obviously, this requires a number of unlikely circumstances,
including the ability to repeatedly exploit the gap between the stat()
and fopen() call. But it seems formally incorrect, so it seems good to
fix it, at least to make the code a better example.

Thoughts?

Attachment Content-Type Size
0001-libpq-Fix-minor-TOCTOU-violation.patch text/plain 1.6 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Kirill Reshke 2024-08-10 07:22:00 Re: EphemeralNamedRelation and materialized view
Previous Message Peter Eisentraut 2024-08-10 06:43:59 Re: Fix inappropriate uses of atol()