Skip to content

Fix undefined behaviour in unpack() #10943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions ext/standard/pack.c
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,16 @@ PHP_FUNCTION(unpack)
c = *format;

if (c >= '0' && c <= '9') {
repetitions = atoi(format);
errno = 0;
long tmp = strtol(format, NULL, 10);
/* There is not strtoi. We have to check the range ourselves.
* On 32-bit the INT_{MIN,MAX} are useless because long == int, but on 64-bit they do limit us to 32-bit. */
if (errno || tmp < INT_MIN || tmp > INT_MAX) {
php_error_docref(NULL, E_WARNING, "Type %c: integer overflow", type);
zend_array_destroy(Z_ARR_P(return_value));
RETURN_FALSE;
}
repetitions = tmp;

while (formatlen > 0 && *format >= '0' && *format <= '9') {
format++;
Expand Down Expand Up @@ -800,7 +809,7 @@ PHP_FUNCTION(unpack)

case 'h':
case 'H':
size = (repetitions > 0) ? (repetitions + (repetitions % 2)) / 2 : repetitions;
size = (repetitions > 0) ? ((unsigned int) repetitions + 1) / 2 : repetitions;
repetitions = 1;
break;

Expand Down Expand Up @@ -865,12 +874,6 @@ PHP_FUNCTION(unpack)
RETURN_THROWS();
}

if (size != 0 && size != -1 && size < 0) {
php_error_docref(NULL, E_WARNING, "Type %c: integer overflow", type);
zend_array_destroy(Z_ARR_P(return_value));
RETURN_FALSE;
}


/* Do actual unpacking */
for (i = 0; i != repetitions; i++ ) {
Expand Down
9 changes: 9 additions & 0 deletions ext/standard/tests/strings/gh10940.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
--TEST--
Test unpacking at the 32-bit integer limit
--FILE--
<?php
$a = pack("AAAAAAAAAAAA", 1,2,3,4,5,6,7,8,9,10,11,12);
unpack('h2147483647', $a);
?>
--EXPECTF--
Warning: unpack(): Type h: not enough input, need 1073741824, have 12 in %s on line %d