BUG/MEDIUM: sample: fix risk of overflow when replacing multiple regex back-refs
authorWilly Tarreau <w@1wt.eu>
Mon, 7 Apr 2025 13:30:43 +0000 (15:30 +0200)
committerAdrian Bunk <bunk@debian.org>
Wed, 23 Apr 2025 17:55:00 +0000 (20:55 +0300)
commit07da7519a003b65c0863ef7106fa1ed5215d8acc
treede75048efc04bad2adc7e0b1e7c98ca087993c8e
parentc10b7ff987c07fea945027b462ea7fc29b4b4680
BUG/MEDIUM: sample: fix risk of overflow when replacing multiple regex back-refs

Aleandro Prudenzano of Doyensec and Edoardo Geraci of Codean Labs
reported a bug in sample_conv_regsub(), which can cause replacements
of multiple back-references to overflow the temporary trash buffer.

The problem happens when doing "regsub(match,replacement,g)": we're
replacing every occurrence of "match" with "replacement" in the input
sample, which requires a length check. For this, a max is applied, so
that a replacement may not use more than the remaining length in the
buffer. However, the length check is made on the replaced pattern and
not on the temporary buffer used to carry the new string. This results
in the remaining size to be usable for each input match, which can go
beyond the temporary buffer size if more than one occurrence has to be
replaced with something that's larger than the remaining room.

The fix proposed by Aleandro and Edoardo is the correct one (check on
"trash" not "output"), and is the one implemented in this patch.

While it is very unlikely that a config will replace multiple short
patterns each with a larger one in a request, this possibility cannot
be entirely ruled out (e.g. mask a known, short IP address using
"XXX.XXX.XXX.XXX").  However when this happens, the replacement pattern
will be static, and not be user-controlled, which is why this patch is
marked as medium.

The bug was introduced in 2.2 with commit 07e1e3c93e ("MINOR: sample:
regsub now supports backreferences"), so it must be backported to all
versions.

Special thanks go to Aleandro and Edoardo for reporting this bug with
a simple reproducer and a fix.

Gbp-Pq: Name 0001-BUG-MEDIUM-sample-fix-risk-of-overflow-when-replacin.patch
src/sample.c