Re: psql: avoid over-reading unterminated prompt escapes

From: Ishjaap Singh II <ishjaap(dot)singh07(at)gmail(dot)com>
To: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
Cc: Kirill Reshke <reshkekirill(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: psql: avoid over-reading unterminated prompt escapes
Date: 2026-10-25 12:35:24
Message-ID: CA+Y2Bmei3iUnX2PjDCO9Jni8oDWgGP8EGaKuDFT0i0Cs07jafw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, Sep 21, 2026 at 07:35, Chao Li wrote:
> PFA v2 - addressed Kirill's comment.

Hi Chao,

I reviewed and tested v2.

I reproduced the over-read on master (0019a1ecf4c) with an
AddressSanitizer build. Without the patch, each of these prompts
triggers a heap-buffer-overflow at prompt.c:103:

%:aa %:x %: pre %:aa %`echo hi %`

With v2 applied, all of them run cleanly, and well-formed prompts
(%:aa:, %`echo hi`, %/%R%# and a few others) render exactly as
before. The psql TAP tests and the core regression tests also pass
under ASan.

The fix looks correct to me. Since strcspn() stops at either the
delimiter or the terminating NUL, p[1] is always one of the two, so
the pointer can no longer step past the end of the string.

For the back branches, v2 doesn't apply as-is because master changed
free() to pfree() next to these lines in 30652b356d. The attached
v2-backbranch-REL_14-19.patch.txt adjusts only that context; the
code change itself is identical. It applies to REL_14_STABLE through
REL_19_STABLE. I built and tested REL_14_STABLE with ASan: the same
six cases fail before the fix and run cleanly after it.

I've also attached an optional TAP test (0002, on top of v2), since
nothing currently exercises custom prompts. It passes with the fix,
and without it ASan aborts psql at the first unterminated case. In a
normal build it passed both with and without the fix, so it only
reliably catches this under ASan. Feel free to leave it out if you
don't think it's worth adding.

This looks ready for committer to me.

Thanks,
Ishjaap Singh

Attachment Content-Type Size
v2-backbranch-REL_14-19.patch.txt text/plain 1.5 KB
0002-psql-Add-test-for-unterminated-prompt-escapes.patch.txt text/plain 2.7 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Mohit Kumar 2026-10-25 13:32:38 Re: [PATCH] Disallow column lists on tables with REPLICA IDENTITY FULL when publishing updates/deletes
Previous Message Hannu Krosing 2026-10-25 11:48:41 Re: ANSI SQL proposal: SELECT DISTINCT ON (... ORDER BY ...) and UNION DISTINCT ON (... ORDER BY ...)