Harden our regex engine against integer overflow in size calculations.

The number of NFA states, number of NFA arcs, and number of colors
are all bounded to reasonably small values.  However, there are
places where we try to allocate arrays sized by products of those
quantities, and those calculations could overflow, enabling
buffer-overrun attacks.  In practice there's no problem on 64-bit
machines, but there are some live scenarios on 32-bit machines.

A related problem is that citerdissect() and creviterdissect()
allocate arrays based on the length of the input string, which
potentially could overflow.

To fix, invent MALLOC_ARRAY and REALLOC_ARRAY macros that rely on
palloc_array_extended and repalloc_array_extended with the NO_OOM
option, similarly to the existing MALLOC and REALLOC macros.
(Like those, they'll throw an error not return a NULL result for
oversize requests.  This doesn't really fit into the regex code's
view of error handling, but it'll do for now.  We can consider
whether to change that behavior in a non-security follow-up patch.)

I installed similar defenses in the colormap construction code.
It's not entirely clear whether integer overflow is possible
there, but analyzing the behavior in detail seems not worth
the trouble, as the risky spots are not in hot code paths.

I left a bunch of calls as-is after verifying that they can't
overflow given reasonable limits on nstates and narcs.  Those
limits were enforced already via REG_MAX_COMPILE_SPACE, but
add commentary to document the interactions.

In passing, also fix a related edge case, which is that the
special color numbers used in LACON carcs could overflow the
"color" data type, if ncolors is close to MAX_COLOR.

In v14 and v15, the regex engine calls malloc() directly instead
of using palloc(), so MALLOC_ARRAY and REALLOC_ARRAY do likewise.

Reported-by: Xint Code
Author: Tom Lane <[email protected]>
Reviewed-by: Masahiko Sawada <[email protected]>
Backpatch-through: 14
Security: CVE-2026-6473

Branch
------
REL_17_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/e3a2bea41c0c953feec0cc2468a434f12a60cc78
Author: Tom Lane <[email protected]>

Modified Files
--------------
src/backend/regex/regc_color.c | 17 +++++++----------
src/backend/regex/regc_cvec.c  |  3 +++
src/backend/regex/regc_nfa.c   | 10 ++++++++++
src/backend/regex/regcomp.c    |  5 +++--
src/backend/regex/rege_dfa.c   | 23 ++++++++++++++++-------
src/backend/regex/regexec.c    |  8 +++++---
src/include/regex/regcustom.h  |  2 ++
src/include/regex/regguts.h    | 13 +++++++++++++
8 files changed, 59 insertions(+), 22 deletions(-)

Reply via email to