Commit 33d678aa

33d678aa030aMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(regexp): re_utf8_decode rejects overlong + out-of-range cps (#780)

RFC 3629 + Ruby both treat overlong UTF-8 sequences as invalid (e.g. \xC0\x80 for NUL). spinel's decoder accepted them, which let an attacker bypass regex NUL checks via the overlong form.

Per length class:

  • 2-byte: cp must be >= 0x80
  • 3-byte: cp must be >= 0x800
  • 4-byte: cp must be in [0x10000, 0x10FFFF]

On detection: return U+FFFD (replacement) and consume just the lead byte so the caller can resync. Matches Ruby's invalid- sequence handling.

Closes #780

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
33d678aa030a
Parent
92cb004b9061

lib/regexp/re_utf8.cmodifiedView file

@@ -26,7 +26,11 @@
2626 }
2727
2828 /* Decode a UTF-8 character and return its codepoint.
29- *len is set to the byte length consumed. */
29+ *len is set to the byte length consumed.
30+ Issue #780: reject overlong sequences (where a multi-byte form
31+ encodes a codepoint that fits in fewer bytes). RFC 3629 + Ruby
32+ both treat these as invalid. Returns U+FFFD (replacement) and
33+ consumes just the lead byte so the caller can resync. */
3034 uint32_t
3135 re_utf8_decode(const char *s, int *len)
3236 {
@@ -39,12 +43,14 @@
3943 }
4044 else if (c < 0xc0) {
4145 *len = 1;
42- return c; /* invalid, return as-is */
46+ return c; /* invalid lead byte, return as-is */
4347 }
4448 else if (c < 0xe0) {
4549 *len = 2;
4650 cp = (c & 0x1f) << 6;
4751 cp |= ((uint8_t)s[1] & 0x3f);
52+ /* Overlong: 2-byte form valid only for cp >= 0x80. */
53+ if (cp < 0x80) { *len = 1; return 0xFFFD; }
4854 return cp;
4955 }
5056 else if (c < 0xf0) {
@@ -52,6 +58,8 @@
5258 cp = (c & 0x0f) << 12;
5359 cp |= ((uint8_t)s[1] & 0x3f) << 6;
5460 cp |= ((uint8_t)s[2] & 0x3f);
61+ /* Overlong: 3-byte form valid only for cp >= 0x800. */
62+ if (cp < 0x800) { *len = 1; return 0xFFFD; }
5563 return cp;
5664 }
5765 else {
@@ -60,6 +68,9 @@
6068 cp |= ((uint8_t)s[1] & 0x3f) << 12;
6169 cp |= ((uint8_t)s[2] & 0x3f) << 6;
6270 cp |= ((uint8_t)s[3] & 0x3f);
71+ /* Overlong: 4-byte form valid only for cp >= 0x10000. Also reject
72+ codepoints above the Unicode max (U+10FFFF). */
73+ if (cp < 0x10000 || cp > 0x10FFFF) { *len = 1; return 0xFFFD; }
6374 return cp;
6475 }
6576 }