system/core
修訂 | 92c238198805c3c846f017503e1deb8abcc8994b (tree) |
---|---|
時間 | 2017-09-21 04:24:05 |
作者 | Adam Vartanian <flooey@goog...> |
Commiter | Nikoli Cartagena |
Fix integer overflow in utf{16,32}_to_utf8_length
Without an explicit check, the return value can wrap around and return
a value that is far too small to hold the data from the resulting
conversion.
No CTS test is provided because it would need to allocate at least
SSIZE_MAX / 2 bytes of UTF-16 data, which is unreasonable on 64-bit
devices.
Bug: 37723026
Test: run cts -p android.security
Change-Id: Ie2606b92b9eab1acfe8ce4663b43b81156a4cad7
Merged-In: I56ba5e31657633b7f33685dd8839d4b3b998e586
(cherry picked from commit f0a43dede921178b3048d40c330a8b664e94cca3)
@@ -18,6 +18,7 @@ | ||
18 | 18 | #include <utils/Unicode.h> |
19 | 19 | |
20 | 20 | #include <stddef.h> |
21 | +#include <limits.h> | |
21 | 22 | |
22 | 23 | #if defined(_WIN32) |
23 | 24 | # undef nhtol |
@@ -178,7 +179,15 @@ ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len) | ||
178 | 179 | size_t ret = 0; |
179 | 180 | const char32_t *end = src + src_len; |
180 | 181 | while (src < end) { |
181 | - ret += utf32_codepoint_utf8_length(*src++); | |
182 | + size_t char_len = utf32_codepoint_utf8_length(*src++); | |
183 | + if (SSIZE_MAX - char_len < ret) { | |
184 | + // If this happens, we would overflow the ssize_t type when | |
185 | + // returning from this function, so we cannot express how | |
186 | + // long this string is in an ssize_t. | |
187 | + android_errorWriteLog(0x534e4554, "37723026"); | |
188 | + return -1; | |
189 | + } | |
190 | + ret += char_len; | |
182 | 191 | } |
183 | 192 | return ret; |
184 | 193 | } |
@@ -438,14 +447,23 @@ ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len) | ||
438 | 447 | size_t ret = 0; |
439 | 448 | const char16_t* const end = src + src_len; |
440 | 449 | while (src < end) { |
450 | + size_t char_len; | |
441 | 451 | if ((*src & 0xFC00) == 0xD800 && (src + 1) < end |
442 | 452 | && (*(src + 1) & 0xFC00) == 0xDC00) { |
443 | 453 | // surrogate pairs are always 4 bytes. |
444 | - ret += 4; | |
454 | + char_len = 4; | |
445 | 455 | src += 2; |
446 | 456 | } else { |
447 | - ret += utf32_codepoint_utf8_length((char32_t) *src++); | |
457 | + char_len = utf32_codepoint_utf8_length((char32_t)*src++); | |
458 | + } | |
459 | + if (SSIZE_MAX - char_len < ret) { | |
460 | + // If this happens, we would overflow the ssize_t type when | |
461 | + // returning from this function, so we cannot express how | |
462 | + // long this string is in an ssize_t. | |
463 | + android_errorWriteLog(0x534e4554, "37723026"); | |
464 | + return -1; | |
448 | 465 | } |
466 | + ret += char_len; | |
449 | 467 | } |
450 | 468 | return ret; |
451 | 469 | } |