Highlighted
Ram3
New Member.
3098 views

PHP XML Injection

Hello,

The fortify san we ran one of the PHP Application source code threw a XML injection error. We have been trying to resolve this for a few days now and have tried multiple options to no avail.

Some of the recommendations from Fortify we tried are to disable entity loader, check for any DOCTYPE/ENTITY tags and reject the XML as we dont expect these to appear in the data.

This function receives XML through various function calls (different XML elements for each call).

Appreciate if someone can help me with resolving this issue.

Here is the function below

function convertArrayToXML() {

$oldValue = libxml_disable_entity_loader(true);
$xmlIn = file_get_contents("php://input");

//playing with regex to check if fortify identifies this as a possible fix. Regex pattern used is just for testing
$regex = '/[A-Za-z0-9' . preg_quote( '.%^&()$#@!/-+/', '/') . ']+/';
if( !preg_match( $regex, $xmlin)) {
throw new \InvalidArgumentException(
'Invalid XML: Detected characters that are not allowed'
);
}

//reject xml for XXE
if (preg_match("/<!DOCTYPE|<!ENTITY/i", $xmlIn)) {
throw new \InvalidArgumentException(
'Invalid XML: Detected use of illegal DOCTYPE'
);
};


$xmldoc = new DOMDocument();
$xmldoc->resolveExternals = false;

$xmldoc->loadXML($xmlIn, LIBXML_NONET | LIBXML_DTDLOAD | LIBXML_DTDATTR);

foreach ($xmldoc->childNodes as $child) {
if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
throw new \InvalidArgumentException(
'Invalid XML: Detected use of illegal DOCTYPE'
);
}
}

$xml = simplexml_import_dom($xmldoc);
foreach ($xml->children() as $child) {
$regex = '/[A-Za-z0-9' . preg_quote( '.%^&()$#@!/-+/', '/') . ']+/';
if( !preg_match( $regex, $child)) {
throw new \InvalidArgumentException(
'Invalid XML: Detected characters not allowed'
);
}
$child = strip_tags($child);
}

libxml_disable_entity_loader($oldValue);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
return $array;

}

0 Likes
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.