From 24a2d196c148030bf84dc6c25838bdebcf168daa Mon Sep 17 00:00:00 2001 From: "Christoph M. Becker" Date: Mon, 10 Aug 2020 10:40:31 +0200 Subject: [PATCH] Fix #79922: Crash after multiple calls to xml_parser_free() We must not call `zend_list_delete()` in resource closer functions exposed to userland, because decreasing the refcount there leads to use-after-free scenarios. In this case, commit 4a42fbb worked for typical use-cases where `xml_parser_free()` has been called exactly once for the resource, because there is an internal zval (`->index`) referencing the same resource which already increased the refcount by one. However, when `xml_parser_free()` is called multiple times on the same XML parser resource, the resource would be freed prematurely. Instead we forcefully close the resource in `xml_parser_free()`. We also could decrease the refcount of the resource there, but that would require to call `xml_parser_free()` which is somewhat uncommon, and would be particularly bad wrt. PHP 8 where that function is a NOP, and as such doesn't have to be called. So we do no longer increase the refcount of the resource when copying it to the internal zval, and let the usualy refcounting semantics take care of the resource destruction. [1] --- ext/xml/tests/bug79922.phpt | 17 +++++++++++++++++ ext/xml/xml.c | 4 ++-- 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 ext/xml/tests/bug79922.phpt diff --git a/ext/xml/tests/bug79922.phpt b/ext/xml/tests/bug79922.phpt new file mode 100644 index 0000000000000..e578a5d2c4374 --- /dev/null +++ b/ext/xml/tests/bug79922.phpt @@ -0,0 +1,17 @@ +--TEST-- +Bug #79922 (Crash after multiple calls to xml_parser_free()) +--SKIPIF-- + +--FILE-- + +--EXPECTF-- +Warning: xml_parser_free(): supplied resource is not a valid XML Parser resource in %s on line %d +bool(false) diff --git a/ext/xml/xml.c b/ext/xml/xml.c index 8a5f7797ce148..7ca02755958e8 100644 --- a/ext/xml/xml.c +++ b/ext/xml/xml.c @@ -1132,7 +1132,7 @@ static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_supp XML_SetUserData(parser->parser, parser); RETVAL_RES(zend_register_resource(parser, le_xml_parser)); - ZVAL_COPY(&parser->index, return_value); + ZVAL_COPY_VALUE(&parser->index, return_value); } /* }}} */ @@ -1559,7 +1559,7 @@ PHP_FUNCTION(xml_parser_free) RETURN_FALSE; } - if (zend_list_delete(Z_RES(parser->index)) == FAILURE) { + if (zend_list_close(Z_RES(parser->index)) == FAILURE) { RETURN_FALSE; }