The Perils of Regex-Based XSS Filtering in PHP
You are likely aware that raw user input from forms needs sanitization before storage or display. However, finding a robust function for generic input filtering often leads to a debate between legacy tools like Zend_Filter_Input and heavyweights like HTML Purifier. While both have their place, you might encounter older tutorials suggesting a custom regular expression approach to strip out dangerous tags and event handlers.
Consider the following snippet often found in older PHP archives:
function sacarXss($val) {
$val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// Attempting to replace hex-encoded entities
$val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);
$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val);
}
// Lists of dangerous tags and event handlers
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true;
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
// Dynamic pattern construction based on character sets
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
$pattern .= '|(&#0{0,8}([9][10][13]);?)?';
$pattern .= ')?';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
// Replacing the tag name with a safe prefix
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
$val = preg_replace($pattern, $replacement, $val);
if ($val_before == $val) {
$found = false;
}
}
}
return $val;
}
While this function attempts to handle hex-encoded entities and lists common dangerous tags like javascript: or event handlers like onclick, relying on it as your primary defense is a flawed strategy. The core issue lies in the nature of XSS vectors. Attackers constantly evolve their payloads. Today, you might see encoded characters, Unicode bypasses, or obfuscated scripts that don't match a static list of keywords.
The approach shown above tries to catch specific patterns but misses the broader context. For instance, it relies on a finite list of tag names and event handlers. If an attacker uses onerror inside a dynamically generated object or a less common attribute, this filter might miss it entirely. Furthermore, the logic attempts to replace tags by stripping parts of the name, which can inadvertently break legitimate HTML attributes if not handled with extreme care regarding context-aware encoding.
In modern PHP development, especially within the Laravel ecosystem, the standard practice is to separate concerns: store data as received and encode it when displaying it. The htmlspecialchars function is your first line of defense for output contexts. It converts special characters like <, >, and & into their HTML entity equivalents, effectively neutralizing script injection regardless of the tag name or attribute used.
If you must sanitize input for storage or specific processing where encoding isn't enough (such as inserting content into a JavaScript string), use libraries designed for this purpose. The built-in HTMLPurifier library remains a robust choice, and while it has overhead, it is generally acceptable for application start-up costs unless you are processing millions of records per second in a high-frequency trading scenario. For real-time filtering, consider using the Laravel Illuminate\Support\Str helper methods or dedicated sanitization packages that handle context-aware escaping more reliably than regex blacklists.
Remember that security is not about finding a perfect filter function; it is about defense in depth. Relying on a custom regex to strip javascript: protocols is insufficient against modern injection techniques. Always validate input, sanitize for storage if necessary, and encode for output.