|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72836 integer overflow in base64_decode caused heap corruption
Submitted: 2016-08-15 04:08 UTC Modified: 2017-02-13 01:46 UTC
From: minhrau dot vc dot 365 at gmail dot com Assigned: stas (profile)
Status: Closed Package: *General Issues
PHP Version: 5.6.24 OS: ALL
Private report: No CVE-ID: None
 [2016-08-15 04:08 UTC] minhrau dot vc dot 365 at gmail dot com
In php_base64_encode function, the safe_emalloc did not check value it alloc for string, which used to store the result of base64 encode function. This cause the length of string after encode > INT_MAX and caused the heap corruption some where else (example in this case is in chunk_split function)

PHPAPI unsigned char *php_base64_encode(const unsigned char *str, int length, int *ret_length) /* {{{ */
	const unsigned char *current = str;
	unsigned char *p;
	unsigned char *result;

	if (length < 0) {
		if (ret_length != NULL) {
			*ret_length = 0;
		return NULL;

	result = (unsigned char *) safe_emalloc((length + 2) / 3, 4 * sizeof(char), 1);  //<- muse check size of safe_emalloc here, must be < MAX_INT
	p = result;

Test script:

ini_set('memory_limit', -1);

$a = str_repeat('#', 0xffffffff/2-5);
$str1 = base64_encode($a);  
chunk_split($str1, 11, $str1);

Expected result:
No Crash

Actual result:
Starting program: /home/minhrau/PHP-5.6.24/sapi/cli/php testbase64encode_negativelength.php
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/".

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff49ebfd7 in __memcpy_avx_unaligned () from /usr/lib/
(gdb) bt
#0  0x00007ffff49ebfd7 in __memcpy_avx_unaligned () from /usr/lib/
#1  0x000000000067c14f in zif_chunk_split (ht=<optimized out>, return_value=0x7ffff7fa8158, return_value_ptr=<optimized out>, this_ptr=<optimized out>, return_value_used=<optimized out>) at /home/minhrau/PHP-5.6.24/ext/standard/string.c:2221
#2  0x00000000007c4c9d in zend_do_fcall_common_helper_SPEC (execute_data=<optimized out>) at /home/minhrau/PHP-5.6.24/Zend/zend_vm_execute.h:558
#3  0x000000000074f75e in execute_ex (execute_data=0x7ffff7f73260) at /home/minhrau/PHP-5.6.24/Zend/zend_vm_execute.h:363
#4  0x000000000071a951 in zend_execute_scripts (type=type@entry=8, retval=retval@entry=0x0, file_count=file_count@entry=3) at /home/minhrau/PHP-5.6.24/Zend/zend.c:1341
#5  0x00000000006b8ce0 in php_execute_script (primary_file=primary_file@entry=0x7fffffffd0e0) at /home/minhrau/PHP-5.6.24/main/main.c:2613
#6  0x00000000007c66a7 in do_cli (argc=2, argv=0xf27d50) at /home/minhrau/PHP-5.6.24/sapi/cli/php_cli.c:994
#7  0x000000000042b8a4 in main (argc=2, argv=0xf27d50) at /home/minhrau/PHP-5.6.24/sapi/cli/php_cli.c:1378


Add a Patch

Pull Requests

Add a Pull Request