Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd126494

Browse files
committed
With GB18030, prevent SIGSEGV from reading past end of allocation.
With GB18030 as source encoding, applications could crash the server viaSQL functions convert() or convert_from(). Applications themselvescould crash after passing unterminated GB18030 input to libpq functionsPQescapeLiteral(), PQescapeIdentifier(), PQescapeStringConn(), orPQescapeString(). Extension code could crash by passing unterminatedGB18030 input to jsonapi.h functions. All those functions have beenintended to handle untrusted, unterminated input safely.A crash required allocating the input such that the last byte of theallocation was the last byte of a virtual memory page. Some malloc()implementations take measures against that, making the SIGSEGV hard toreach. Back-patch to v13 (all supported versions).Author: Noah Misch <noah@leadboat.com>Author: Andres Freund <andres@anarazel.de>Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>Backpatch-through: 13Security:CVE-2025-4207
1 parentf3bb0b2 commitd126494

File tree

9 files changed

+188
-30
lines changed

9 files changed

+188
-30
lines changed

‎src/backend/utils/mb/mbutils.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,7 @@ pg_mbcliplen(const char *mbstr, int len, int limit)
10881088
}
10891089

10901090
/*
1091-
* pg_mbcliplen with specified encoding
1091+
* pg_mbcliplen with specified encoding; string must be valid in encoding
10921092
*/
10931093
int
10941094
pg_encoding_mbcliplen(intencoding,constchar*mbstr,
@@ -1699,12 +1699,12 @@ check_encoding_conversion_args(int src_encoding,
16991699
* report_invalid_encoding: complain about invalid multibyte character
17001700
*
17011701
* note: len is remaining length of string, not length of character;
1702-
* len must be greater than zero, as we always examine the first byte.
1702+
* len must be greater than zero (or we'd neglect initializing "buf").
17031703
*/
17041704
void
17051705
report_invalid_encoding(intencoding,constchar*mbstr,intlen)
17061706
{
1707-
intl=pg_encoding_mblen(encoding,mbstr);
1707+
intl=pg_encoding_mblen_or_incomplete(encoding,mbstr,len);
17081708
charbuf[8*5+1];
17091709
char*p=buf;
17101710
intj,
@@ -1731,18 +1731,26 @@ report_invalid_encoding(int encoding, const char *mbstr, int len)
17311731
* report_untranslatable_char: complain about untranslatable character
17321732
*
17331733
* note: len is remaining length of string, not length of character;
1734-
* len must be greater than zero, as we always examine the first byte.
1734+
* len must be greater than zero (or we'd neglect initializing "buf").
17351735
*/
17361736
void
17371737
report_untranslatable_char(intsrc_encoding,intdest_encoding,
17381738
constchar*mbstr,intlen)
17391739
{
1740-
intl=pg_encoding_mblen(src_encoding,mbstr);
1740+
intl;
17411741
charbuf[8*5+1];
17421742
char*p=buf;
17431743
intj,
17441744
jlimit;
17451745

1746+
/*
1747+
* We probably could use plain pg_encoding_mblen(), because
1748+
* gb18030_to_utf8() verifies before it converts. All conversions should.
1749+
* For src_encoding!=GB18030, len>0 meets pg_encoding_mblen() needs. Even
1750+
* so, be defensive, since a buggy conversion might pass invalid data.
1751+
* This is not a performance-critical path.
1752+
*/
1753+
l=pg_encoding_mblen_or_incomplete(src_encoding,mbstr,len);
17461754
jlimit=Min(l,len);
17471755
jlimit=Min(jlimit,8);/* prevent buffer overrun */
17481756

‎src/common/jsonapi.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -721,8 +721,11 @@ json_lex_string(JsonLexContext *lex)
721721
} while (0)
722722
#defineFAIL_AT_CHAR_END(code) \
723723
do { \
724-
char *term = s + pg_encoding_mblen(lex->input_encoding, s); \
725-
lex->token_terminator = (term <= end) ? term : end; \
724+
ptrdiff_tremaining = end - s; \
725+
intcharlen; \
726+
charlen = pg_encoding_mblen_or_incomplete(lex->input_encoding, \
727+
s, remaining); \
728+
lex->token_terminator = (charlen <= remaining) ? s + charlen : end; \
726729
return code; \
727730
} while (0)
728731

‎src/common/wchar.c

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
#include"c.h"
1414

15+
#include<limits.h>
16+
1517
#include"mb/pg_wchar.h"
1618
#include"utils/ascii.h"
1719

@@ -2169,10 +2171,27 @@ const pg_wchar_tbl pg_wchar_table[] = {
21692171
/*
21702172
* Returns the byte length of a multibyte character.
21712173
*
2172-
* Caution: when dealing with text that is not certainly valid in the
2173-
* specified encoding, the result may exceed the actual remaining
2174-
* string length. Callers that are not prepared to deal with that
2175-
* should use pg_encoding_mblen_bounded() instead.
2174+
* Choose "mblen" functions based on the input string characteristics.
2175+
* pg_encoding_mblen() can be used when ANY of these conditions are met:
2176+
*
2177+
* - The input string is zero-terminated
2178+
*
2179+
* - The input string is known to be valid in the encoding (e.g., string
2180+
* converted from database encoding)
2181+
*
2182+
* - The encoding is not GB18030 (e.g., when only database encodings are
2183+
* passed to 'encoding' parameter)
2184+
*
2185+
* encoding==GB18030 requires examining up to two bytes to determine character
2186+
* length. Therefore, callers satisfying none of those conditions must use
2187+
* pg_encoding_mblen_or_incomplete() instead, as access to mbstr[1] cannot be
2188+
* guaranteed to be within allocation bounds.
2189+
*
2190+
* When dealing with text that is not certainly valid in the specified
2191+
* encoding, the result may exceed the actual remaining string length.
2192+
* Callers that are not prepared to deal with that should use Min(remaining,
2193+
* pg_encoding_mblen_or_incomplete()). For zero-terminated strings, that and
2194+
* pg_encoding_mblen_bounded() are interchangeable.
21762195
*/
21772196
int
21782197
pg_encoding_mblen(intencoding,constchar*mbstr)
@@ -2183,8 +2202,28 @@ pg_encoding_mblen(int encoding, const char *mbstr)
21832202
}
21842203

21852204
/*
2186-
* Returns the byte length of a multibyte character; but not more than
2187-
* the distance to end of string.
2205+
* Returns the byte length of a multibyte character (possibly not
2206+
* zero-terminated), or INT_MAX if too few bytes remain to determine a length.
2207+
*/
2208+
int
2209+
pg_encoding_mblen_or_incomplete(intencoding,constchar*mbstr,
2210+
size_tremaining)
2211+
{
2212+
/*
2213+
* Define zero remaining as too few, even for single-byte encodings.
2214+
* pg_gb18030_mblen() reads one or two bytes; single-byte encodings read
2215+
* zero; others read one.
2216+
*/
2217+
if (remaining<1||
2218+
(encoding==PG_GB18030&&IS_HIGHBIT_SET(*mbstr)&&remaining<2))
2219+
returnINT_MAX;
2220+
returnpg_encoding_mblen(encoding,mbstr);
2221+
}
2222+
2223+
/*
2224+
* Returns the byte length of a multibyte character; but not more than the
2225+
* distance to the terminating zero byte. For input that might lack a
2226+
* terminating zero, use Min(remaining, pg_encoding_mblen_or_incomplete()).
21882227
*/
21892228
int
21902229
pg_encoding_mblen_bounded(intencoding,constchar*mbstr)

‎src/include/mb/pg_wchar.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,8 @@ extern intpg_valid_server_encoding_id(int encoding);
575575
*/
576576
externvoidpg_encoding_set_invalid(intencoding,char*dst);
577577
externintpg_encoding_mblen(intencoding,constchar*mbstr);
578+
externintpg_encoding_mblen_or_incomplete(intencoding,constchar*mbstr,
579+
size_tremaining);
578580
externintpg_encoding_mblen_bounded(intencoding,constchar*mbstr);
579581
externintpg_encoding_dsplen(intencoding,constchar*mbstr);
580582
externintpg_encoding_verifymbchar(intencoding,constchar*mbstr,intlen);

‎src/interfaces/libpq/fe-exec.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3967,7 +3967,8 @@ PQescapeStringInternal(PGconn *conn,
39673967
}
39683968

39693969
/* Slow path for possible multibyte characters */
3970-
charlen=pg_encoding_mblen(encoding,source);
3970+
charlen=pg_encoding_mblen_or_incomplete(encoding,
3971+
source,remaining);
39713972

39723973
if (remaining<charlen||
39733974
pg_encoding_verifymbchar(encoding,source,charlen)==-1)
@@ -4111,7 +4112,8 @@ PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
41114112
intcharlen;
41124113

41134114
/* Slow path for possible multibyte characters */
4114-
charlen=pg_encoding_mblen(conn->client_encoding,s);
4115+
charlen=pg_encoding_mblen_or_incomplete(conn->client_encoding,
4116+
s,remaining);
41154117

41164118
if (charlen>remaining)
41174119
{

‎src/interfaces/libpq/fe-misc.c

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1165,13 +1165,9 @@ pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
11651165
*/
11661166

11671167
/*
1168-
* Returns the byte length of the character beginning at s, using the
1169-
* specified encoding.
1170-
*
1171-
* Caution: when dealing with text that is not certainly valid in the
1172-
* specified encoding, the result may exceed the actual remaining
1173-
* string length. Callers that are not prepared to deal with that
1174-
* should use PQmblenBounded() instead.
1168+
* Like pg_encoding_mblen(). Use this in callers that want the
1169+
* dynamically-linked libpq's stance on encodings, even if that means
1170+
* different behavior in different startups of the executable.
11751171
*/
11761172
int
11771173
PQmblen(constchar*s,intencoding)
@@ -1180,8 +1176,9 @@ PQmblen(const char *s, int encoding)
11801176
}
11811177

11821178
/*
1183-
* Returns the byte length of the character beginning at s, using the
1184-
* specified encoding; but not more than the distance to end of string.
1179+
* Like pg_encoding_mblen_bounded(). Use this in callers that want the
1180+
* dynamically-linked libpq's stance on encodings, even if that means
1181+
* different behavior in different startups of the executable.
11851182
*/
11861183
int
11871184
PQmblenBounded(constchar*s,intencoding)

‎src/test/modules/test_escape/test_escape.c

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include<string.h>
1313
#include<stdio.h>
1414

15+
#include"common/jsonapi.h"
1516
#include"fe_utils/psqlscan.h"
1617
#include"fe_utils/string_utils.h"
1718
#include"getopt_long.h"
@@ -164,6 +165,91 @@ encoding_conflicts_ascii(int encoding)
164165
}
165166

166167

168+
/*
169+
* Confirm escaping doesn't read past the end of an allocation. Consider the
170+
* result of malloc(4096), in the absence of freelist entries satisfying the
171+
* allocation. On OpenBSD, reading one byte past the end of that object
172+
* yields SIGSEGV.
173+
*
174+
* Run this test before the program's other tests, so freelists are minimal.
175+
* len=4096 didn't SIGSEGV, likely due to free() calls in libpq. len=8192
176+
* did. Use 128 KiB, to somewhat insulate the outcome from distant new free()
177+
* calls and libc changes.
178+
*/
179+
staticvoid
180+
test_gb18030_page_multiple(pe_test_config*tc)
181+
{
182+
PQExpBuffertestname;
183+
size_tinput_len=0x20000;
184+
char*input;
185+
186+
/* prepare input */
187+
input=pg_malloc(input_len);
188+
memset(input,'-',input_len-1);
189+
input[input_len-1]=0xfe;
190+
191+
/* name to describe the test */
192+
testname=createPQExpBuffer();
193+
appendPQExpBuffer(testname,">repeat(%c, %zu)",input[0],input_len-1);
194+
escapify(testname,input+input_len-1,1);
195+
appendPQExpBuffer(testname,"< - GB18030 - PQescapeLiteral");
196+
197+
/* test itself */
198+
PQsetClientEncoding(tc->conn,"GB18030");
199+
report_result(tc,PQescapeLiteral(tc->conn,input,input_len)==NULL,
200+
testname->data,"",
201+
"input validity vs escape success","ok");
202+
203+
destroyPQExpBuffer(testname);
204+
pg_free(input);
205+
}
206+
207+
/*
208+
* Confirm json parsing doesn't read past the end of an allocation. This
209+
* exercises wchar.c infrastructure like the true "escape" tests do, but this
210+
* isn't an "escape" test.
211+
*/
212+
staticvoid
213+
test_gb18030_json(pe_test_config*tc)
214+
{
215+
PQExpBufferraw_buf;
216+
PQExpBuffertestname;
217+
constcharinput[]="{\"\\u\xFE";
218+
size_tinput_len=sizeof(input)-1;
219+
JsonLexContext*lex;
220+
JsonSemActionsem= {0};/* no callbacks */
221+
JsonParseErrorTypejson_error;
222+
char*error_str;
223+
224+
/* prepare input like test_one_vector_escape() does */
225+
raw_buf=createPQExpBuffer();
226+
appendBinaryPQExpBuffer(raw_buf,input,input_len);
227+
appendPQExpBufferStr(raw_buf,NEVER_ACCESS_STR);
228+
VALGRIND_MAKE_MEM_NOACCESS(&raw_buf->data[input_len],
229+
raw_buf->len-input_len);
230+
231+
/* name to describe the test */
232+
testname=createPQExpBuffer();
233+
appendPQExpBuffer(testname,">");
234+
escapify(testname,input,input_len);
235+
appendPQExpBuffer(testname,"< - GB18030 - pg_parse_json");
236+
237+
/* test itself */
238+
lex=makeJsonLexContextCstringLen(raw_buf->data,input_len,
239+
PG_GB18030, false);
240+
json_error=pg_parse_json(lex,&sem);
241+
error_str=psprintf("JsonParseErrorType %d",json_error);
242+
report_result(tc,json_error==JSON_UNICODE_ESCAPE_FORMAT,
243+
testname->data,"",
244+
"diagnosed",error_str);
245+
246+
pfree(error_str);
247+
pfree(lex);
248+
destroyPQExpBuffer(testname);
249+
destroyPQExpBuffer(raw_buf);
250+
}
251+
252+
167253
staticbool
168254
escape_literal(PGconn*conn,PQExpBuffertarget,
169255
constchar*unescaped,size_tunescaped_len,
@@ -454,8 +540,18 @@ static pe_test_vector pe_test_vectors[] =
454540
* Testcases that are not null terminated for the specified input length.
455541
* That's interesting to verify that escape functions don't read beyond
456542
* the intended input length.
543+
*
544+
* One interesting special case is GB18030, which has the odd behaviour
545+
* needing to read beyond the first byte to determine the length of a
546+
* multi-byte character.
457547
*/
458548
TV_LEN("gbk","\x80",1),
549+
TV_LEN("GB18030","\x80",1),
550+
TV_LEN("GB18030","\x80\0",2),
551+
TV_LEN("GB18030","\x80\x30",2),
552+
TV_LEN("GB18030","\x80\x30\0",3),
553+
TV_LEN("GB18030","\x80\x30\x30",3),
554+
TV_LEN("GB18030","\x80\x30\x30\0",4),
459555
TV_LEN("UTF-8","\xC3\xb6 ",1),
460556
TV_LEN("UTF-8","\xC3\xb6 ",2),
461557
};
@@ -864,6 +960,9 @@ main(int argc, char *argv[])
864960
exit(1);
865961
}
866962

963+
test_gb18030_page_multiple(&tc);
964+
test_gb18030_json(&tc);
965+
867966
for (inti=0;i<lengthof(pe_test_vectors);i++)
868967
{
869968
test_one_vector(&tc,&pe_test_vectors[i]);

‎src/test/regress/expected/conversion.out

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -508,10 +508,13 @@ insert into gb18030_inputs values
508508
('\x666f6f84309c38','valid, translates to UTF-8 by mapping function'),
509509
('\x666f6f84309c','incomplete char '),
510510
('\x666f6f84309c0a','incomplete char, followed by newline '),
511+
('\x666f6f84','incomplete char at end'),
511512
('\x666f6f84309c3800', 'invalid, NUL byte'),
512513
('\x666f6f84309c0038', 'invalid, NUL byte');
513-
-- Test GB18030 verification
514-
select description, inbytes, (test_conv(inbytes, 'gb18030', 'gb18030')).* from gb18030_inputs;
514+
-- Test GB18030 verification. Round-trip through text so the backing of the
515+
-- bytea values is palloc, not shared_buffers. This lets Valgrind detect
516+
-- reads past the end.
517+
select description, inbytes, (test_conv(inbytes::text::bytea, 'gb18030', 'gb18030')).* from gb18030_inputs;
515518
description | inbytes | result | errorat | error
516519
------------------------------------------------+--------------------+------------------+--------------+-------------------------------------------------------------------
517520
valid, pure ASCII | \x666f6f | \x666f6f | |
@@ -520,9 +523,10 @@ select description, inbytes, (test_conv(inbytes, 'gb18030', 'gb18030')).* from g
520523
valid, translates to UTF-8 by mapping function | \x666f6f84309c38 | \x666f6f84309c38 | |
521524
incomplete char | \x666f6f84309c | \x666f6f | \x84309c | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c
522525
incomplete char, followed by newline | \x666f6f84309c0a | \x666f6f | \x84309c0a | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c 0x0a
526+
incomplete char at end | \x666f6f84 | \x666f6f | \x84 | invalid byte sequence for encoding "GB18030": 0x84
523527
invalid, NUL byte | \x666f6f84309c3800 | \x666f6f84309c38 | \x00 | invalid byte sequence for encoding "GB18030": 0x00
524528
invalid, NUL byte | \x666f6f84309c0038 | \x666f6f | \x84309c0038 | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c 0x00
525-
(8 rows)
529+
(9 rows)
526530

527531
-- Test conversions from GB18030
528532
select description, inbytes, (test_conv(inbytes, 'gb18030', 'utf8')).* from gb18030_inputs;
@@ -534,9 +538,10 @@ select description, inbytes, (test_conv(inbytes, 'gb18030', 'utf8')).* from gb18
534538
valid, translates to UTF-8 by mapping function | \x666f6f84309c38 | \x666f6fefa8aa | |
535539
incomplete char | \x666f6f84309c | \x666f6f | \x84309c | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c
536540
incomplete char, followed by newline | \x666f6f84309c0a | \x666f6f | \x84309c0a | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c 0x0a
541+
incomplete char at end | \x666f6f84 | \x666f6f | \x84 | invalid byte sequence for encoding "GB18030": 0x84
537542
invalid, NUL byte | \x666f6f84309c3800 | \x666f6fefa8aa | \x00 | invalid byte sequence for encoding "GB18030": 0x00
538543
invalid, NUL byte | \x666f6f84309c0038 | \x666f6f | \x84309c0038 | invalid byte sequence for encoding "GB18030": 0x84 0x30 0x9c 0x00
539-
(8 rows)
544+
(9 rows)
540545

541546
--
542547
-- ISO-8859-5

‎src/test/regress/sql/conversion.sql

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,11 +300,14 @@ insert into gb18030_inputs values
300300
('\x666f6f84309c38','valid, translates to UTF-8 by mapping function'),
301301
('\x666f6f84309c','incomplete char'),
302302
('\x666f6f84309c0a','incomplete char, followed by newline'),
303+
('\x666f6f84','incomplete char at end'),
303304
('\x666f6f84309c3800','invalid, NUL byte'),
304305
('\x666f6f84309c0038','invalid, NUL byte');
305306

306-
-- Test GB18030 verification
307-
select description, inbytes, (test_conv(inbytes,'gb18030','gb18030')).*from gb18030_inputs;
307+
-- Test GB18030 verification. Round-trip through text so the backing of the
308+
-- bytea values is palloc, not shared_buffers. This lets Valgrind detect
309+
-- reads past the end.
310+
select description, inbytes, (test_conv(inbytes::text::bytea,'gb18030','gb18030')).*from gb18030_inputs;
308311
-- Test conversions from GB18030
309312
select description, inbytes, (test_conv(inbytes,'gb18030','utf8')).*from gb18030_inputs;
310313

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp