Created
February 21, 2014 14:24
-
-
Save ezimuel/9135151 to your computer and use it in GitHub Desktop.
Tesing SimpleXML and DOMDocument to prevent XXE attacks on XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// The libxml entity loader is disabled by default | |
// even setting the libxml_disable_entity_loader to false doesn't works! | |
// | |
// @see http://uk3.php.net/manual/en/function.libxml-disable-entity-loader.php | |
// @see http://stackoverflow.com/a/10213239 | |
$dir = __DIR__; | |
$content = 'This is a remote content!'; | |
file_put_contents('content.txt', $content); | |
$xml = <<<EOD | |
<?xml version="1.0"?> | |
<!DOCTYPE root | |
[ | |
<!ENTITY foo SYSTEM "file://$dir/content.txt"> | |
]> | |
<test><testing>&foo;</testing></test> | |
EOD; | |
file_put_contents('content.xml', $xml); | |
printf ("PHP ver. %s\n", PHP_VERSION); | |
printf ("Libxml library ver. %s\n", LIBXML_DOTTED_VERSION); | |
printf("\nTesting simplexml_load_string\n"); | |
$doc = simplexml_load_string($xml); | |
printf("Default behaviour: %s\n", $doc->testing); | |
$oldValue = libxml_disable_entity_loader(false); // enable entity load? | |
$doc = simplexml_load_string($xml); | |
printf("libxml_disable_entity to false: %s\n", $doc->testing); | |
libxml_disable_entity_loader($oldValue); | |
$doc = simplexml_load_string($xml, null, LIBXML_NOENT); | |
printf("LIBXML_NOENT: %s\n", $doc->testing); | |
printf("\nTesting simplexml_load_file\n"); | |
$doc = simplexml_load_file('content.xml'); | |
printf("Default behaviour: %s\n", $doc->testing); | |
$oldValue = libxml_disable_entity_loader(false); // enable entity load? | |
$doc = simplexml_load_file('content.xml'); | |
printf("libxml_disable_entity to false: %s\n", $doc->testing); | |
libxml_disable_entity_loader($oldValue); | |
$doc = simplexml_load_file('content.xml', null, LIBXML_NOENT); | |
printf("LIBXML_NOENT: %s\n", $doc->testing); | |
printf("\nTesting DOM (loadXml)\n"); | |
$dom = new DOMDocument('1.0'); | |
$dom->loadXml($xml); | |
$testing = $dom->getElementsByTagName('testing')->item(0); | |
printf("Default behaviour: %s\n", $testing->nodeValue); | |
$oldValue = libxml_disable_entity_loader(false); // enable entity load? | |
$dom = new DOMDocument('1.0'); | |
$dom->loadXml($xml); | |
$testing = $dom->getElementsByTagName('testing')->item(0); | |
printf("libxml_disable_entity to false: %s\n", $testing->nodeValue); | |
libxml_disable_entity_loader($oldValue); | |
$dom->loadXml($xml, LIBXML_NOENT); | |
$testing = $dom->getElementsByTagName('testing')->item(0); | |
printf("LIBXML_NOENT: %s\n", $testing->nodeValue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment