Skip to content

Commit 8031612

Browse files
nielsdosderickr
authored andcommitted
Fix buffer mismanagement in phar_dir_read()
Fixes GHSA-jqcx-ccgc-xwhv.
1 parent be71cad commit 8031612

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

ext/phar/dirstream.c

+9-6
Original file line numberDiff line numberDiff line change
@@ -91,25 +91,28 @@ static int phar_dir_seek(php_stream *stream, zend_off_t offset, int whence, zend
9191
*/
9292
static ssize_t phar_dir_read(php_stream *stream, char *buf, size_t count) /* {{{ */
9393
{
94-
size_t to_read;
9594
HashTable *data = (HashTable *)stream->abstract;
9695
zend_string *str_key;
9796
zend_ulong unused;
9897

98+
if (count != sizeof(php_stream_dirent)) {
99+
return -1;
100+
}
101+
99102
if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key(data, &str_key, &unused)) {
100103
return 0;
101104
}
102105

103106
zend_hash_move_forward(data);
104-
to_read = MIN(ZSTR_LEN(str_key), count);
105107

106-
if (to_read == 0 || count < ZSTR_LEN(str_key)) {
108+
php_stream_dirent *dirent = (php_stream_dirent *) buf;
109+
110+
if (sizeof(dirent->d_name) <= ZSTR_LEN(str_key)) {
107111
return 0;
108112
}
109113

110-
memset(buf, 0, sizeof(php_stream_dirent));
111-
memcpy(((php_stream_dirent *) buf)->d_name, ZSTR_VAL(str_key), to_read);
112-
((php_stream_dirent *) buf)->d_name[to_read + 1] = '\0';
114+
memset(dirent, 0, sizeof(php_stream_dirent));
115+
PHP_STRLCPY(dirent->d_name, ZSTR_VAL(str_key), sizeof(dirent->d_name), ZSTR_LEN(str_key));
113116

114117
return sizeof(php_stream_dirent);
115118
}
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
--TEST--
2+
GHSA-jqcx-ccgc-xwhv (Buffer overflow and overread in phar_dir_read())
3+
--SKIPIF--
4+
<?php if (!extension_loaded("phar")) die("skip"); ?>
5+
--INI--
6+
phar.readonly=0
7+
--FILE--
8+
<?php
9+
$phar = new Phar(__DIR__. '/GHSA-jqcx-ccgc-xwhv.phar');
10+
$phar->startBuffering();
11+
$phar->addFromString(str_repeat('A', PHP_MAXPATHLEN - 1), 'This is the content of file 1.');
12+
$phar->addFromString(str_repeat('B', PHP_MAXPATHLEN - 1).'C', 'This is the content of file 2.');
13+
$phar->stopBuffering();
14+
15+
$handle = opendir('phar://' . __DIR__ . '/GHSA-jqcx-ccgc-xwhv.phar');
16+
var_dump(strlen(readdir($handle)));
17+
// Must not be a string of length PHP_MAXPATHLEN+1
18+
var_dump(readdir($handle));
19+
closedir($handle);
20+
?>
21+
--CLEAN--
22+
<?php
23+
unlink(__DIR__. '/GHSA-jqcx-ccgc-xwhv.phar');
24+
?>
25+
--EXPECTF--
26+
int(%d)
27+
bool(false)

0 commit comments

Comments
 (0)