Commit e9be1f47
e9be1f479dcbMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified
Description
fix(regexp): re_utf8_decode validates continuation bytes (#754)
A multi-byte UTF-8 lead at end-of-string used to pull whatever followed -- typically the C string NUL terminator, which is in bounds but produces a wrong codepoint. With a non-terminated buffer (binary regex input), the read could go past the buffer end.
Pre-check each continuation byte for the 10xxxxxx pattern (0xc0-0xff mask == 0x80). On any continuation that fails the check (including NUL, which is 0x00), bail with U+FFFD and consume only the lead byte so the caller resyncs at the next position.
Closes #754
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- e9be1f479dcb
- Parent
- 33d678aa030a
lib/regexp/re_utf8.cmodifiedView file
@@ -46,30 +46,38 @@
4646
return c; /* invalid lead byte, return as-is */4747
}4848
else if (c < 0xe0) {49+
/* Issue #754: validate continuation byte before reading further.50+
NUL (0x00) is the C string terminator -- a 2-byte lead at51+
end-of-string would otherwise pull garbage. Also rejects any52+
byte without the 10xxxxxx continuation pattern. */53+
if (((uint8_t)s[1] & 0xc0) != 0x80) { *len = 1; return 0xFFFD; }4954
*len = 2;5055
cp = (c & 0x1f) << 6;5156
cp |= ((uint8_t)s[1] & 0x3f);52-
/* Overlong: 2-byte form valid only for cp >= 0x80. */5357
if (cp < 0x80) { *len = 1; return 0xFFFD; }5458
return cp;5559
}5660
else if (c < 0xf0) {61+
if (((uint8_t)s[1] & 0xc0) != 0x80 || ((uint8_t)s[2] & 0xc0) != 0x80) {62+
*len = 1; return 0xFFFD;63+
}5764
*len = 3;5865
cp = (c & 0x0f) << 12;5966
cp |= ((uint8_t)s[1] & 0x3f) << 6;6067
cp |= ((uint8_t)s[2] & 0x3f);61-
/* Overlong: 3-byte form valid only for cp >= 0x800. */6268
if (cp < 0x800) { *len = 1; return 0xFFFD; }6369
return cp;6470
}6571
else {72+
if (((uint8_t)s[1] & 0xc0) != 0x80 || ((uint8_t)s[2] & 0xc0) != 0x80 ||73+
((uint8_t)s[3] & 0xc0) != 0x80) {74+
*len = 1; return 0xFFFD;75+
}6676
*len = 4;6777
cp = (c & 0x07) << 18;6878
cp |= ((uint8_t)s[1] & 0x3f) << 12;6979
cp |= ((uint8_t)s[2] & 0x3f) << 6;7080
cp |= ((uint8_t)s[3] & 0x3f);71-
/* Overlong: 4-byte form valid only for cp >= 0x10000. Also reject72-
codepoints above the Unicode max (U+10FFFF). */7381
if (cp < 0x10000 || cp > 0x10FFFF) { *len = 1; return 0xFFFD; }7482
return cp;7583
}