Re: [PATCH] Fix out-of-bouds access (src/common/wchar.c) - Mailing list pgsql-hackers

From Ranier Vilela
Subject Re: [PATCH] Fix out-of-bouds access (src/common/wchar.c)
Date
Msg-id CAEudQAoEAmJg7RtZYy=aeumRksX_BeibpVhEH2gzxMePxQDL3g@mail.gmail.com
Whole thread Raw
In response to Re: [PATCH] Fix out-of-bouds access (src/common/wchar.c)  (Kyotaro Horiguchi <horikyota.ntt@gmail.com>)
Responses Re: [PATCH] Fix out-of-bouds access (src/common/wchar.c)  (Kyotaro Horiguchi <horikyota.ntt@gmail.com>)
Re: [PATCH] Fix out-of-bouds access (src/common/wchar.c)  (Kyotaro Horiguchi <horikyota.ntt@gmail.com>)
List pgsql-hackers
Em qua., 16 de fev. de 2022 às 00:12, Kyotaro Horiguchi <horikyota.ntt@gmail.com> escreveu:
At Tue, 15 Feb 2022 09:17:34 -0300, Ranier Vilela <ranier.vf@gmail.com> wrote in
> Per Coverity.

Thanks for the source:)

> Like the function pg_encoding_max_length_sql
> (src/backend/utils/mb/mbutils.c)
> Only assertion is insufficient to avoid accessing array out-of-bounds.
>
> This bug is live according Coverity at function: pg_verify_mbstr_len
> (src/backend/utils/mb/mbutils.c)
> CID 1469870 (#1 of 1): Out-of-bounds access (OVERRUN)7. overrun-call:
> Overrunning
> callee's array of size 42 by passing argument src_encoding (which evaluates
> to 63) in call to pg_verify_mbstr_len. [show details
> <https://scan6.scan.coverity.com/eventId=32693869-7&modelId=32693869-0&fileInstanceId=131415642&filePath=%2Fdll%2Fpostgres%2Fpostgres%2Fsrc%2Fbackend%2Futils%2Fmb%2Fmbutils.c&fileStart=1546&fileEnd=1605>

It returns 400..

> ]
> 633        retval = pg_verify_mbstr_len(src_encoding, src_str, len, false);
> 634
>
> Trivial patch attached.

Mmm? If the assert doesn't work, there should be inconcsistency
between pg_enc and pg_wchar_table. But AFAICS they are consistent.
The consistency is between pg_encname_tbl and pc_enc, and AFAICS are consistent.
 

The patch:
 pg_encoding_max_length(int encoding)
 {
-       Assert(PG_VALID_ENCODING(encoding));
-
-       return pg_wchar_table[encoding].maxmblen;
+       if (PG_VALID_ENCODING(encoding))
+               return pg_wchar_table[encoding].maxmblen;
+       else
+               return -1;

Returning -1 for invalid encoding is, I think, flat wrong.
Ok, if -1 is wrong, what should the value of return if
somebody calling this function like: 
pg_encoding_max_length(63);

Of course, with patch applied, because with original code
has memory corruption, if built and run without DEBUG.

regards,
Ranier Vilela

pgsql-hackers by date:

Previous
From: Amul Sul
Date:
Subject: minor code correction in typecmds.c
Next
From: John Naylor
Date:
Subject: Re: minor code correction in typecmds.c