'Checkmarx XSS while using htmlpurifier
I have a php page that echoes something like this:
echo "<div>" . $_REQUEST["id"] . "</div>";
This leads to XSS issue, which i tried to fix using htmlpurifier through a function that cleans $_REQUEST by reference, leading to this code:
function sanitizer(array &array) {
foreach ($array as $key => $value) {
$array[$key] = htmlpurifierInstance->purify($value);
}
}
sanitizer($_REQUEST);
echo "<div>" . $_REQUEST["id"] . "</div>";
After another checkmarx test, the issue stills pops up, what's the fix to this issue?
Solution 1:[1]
Sanitising HTML should be a very rare requirement, not something you do regularly on all input.
- Whenever a value has a limited range of valid values, validate it. Reject it or unset it if it's not valid. So if "id" is supposed to be a number, reject non-numeric input.
- Whenever outputting or sending any variable somewhere, escape it for the relevant context. In this case, you are outputting in an HTML context, so use
htmlspecialchars. This is not something you can do ahead of time, because the same variable might be used in multiple contexts. - For the particular case of database queries, don't use escaping, use parameterised queries.
- In the rare cases where you really need the user to be able to enter HTML, come up with a strict whitelist of tags and attributes they can use, and sanitise the particular variable based on that, as part of your input processing. (This is what HTMLPurifier is for.)
Never, ever, try to write a "universal" sanitising or escaping function. At best, you will end up mangling data by applying too many things at once; at worst, you'll defeat your own security.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
