Escaping RFC for PHP Core
- 2012-09-18 Initial version edited from https://gist.github.com/gists/3066656
- 2013-09-27 Added ext/filter implementation as an option (Yasuo)
This RFC proposes the addition of an SPL class (and optionally a set of functions) dedicated to the secure escaping of untrusted values against Cross-Site Scripting (XSS) and related vulnerabilities. It recognises that this involves the partial duplication of certain existing functions but raises the argument that the current division of functionality, the disparate behaviour of that functionality and varied misunderstandings among programmers have served to enable widespread insecure practices in the absence of a unified approach in this area.
The OWASP Top 10 web security risks study lists XSS in second place. PHP's sole functionality against XSS is limited to two functions of which one is commonly misapplied so, while taking some steps towards preventing XSS, PHP's anti-XSS measures are clearly insufficient and need to be boosted in line with recommended practice.
A similar approach has already been taken in PHP code by Zend Framework 2.0 (Zend\Escaper) and, just recently, Symfony 2 (via Twig) adopted this functionality. While this can be done in PHP by individual frameworks, this has never historically been the case and programmers remain reliant on PHP to provide this functionality.
The Problem With Inconsistent Functionality
At present, programmers orient towards the following PHP functions for each common HTML context:
- HTML Body: htmlspecialchars() or htmlentities()
- HTML Attribute: htmlspecialchars() or htmlentities()
- CSS: n/a
- URL/URI: rawurlencode() or urlencode()
In practice, these decisions appear to depend more on what PHP offers, and if it can be interpreted as offering sufficient escaping safety, than it does on what is recommended in reality to defend against XSS. While these functions can prevent some forms of XSS, they do not cover all use cases or risks and are therefore insufficient defenses.
Using htmlspecialchars() in a perfectly valid HTML5 unquoted attribute value, for example, is completely useless since the value can be terminated by a space (among other things) which is never escaped. Thus, in this instance, we have a conflict between a widely used HTML escaper and a modern HTML specification, with no specific function available to cover this use case. While it's tempting to blame users, or the HTML specification authors, escaping just needs to deal with whatever HTML and browsers allow.
Inconsistencies with valid HTML, insecure default parameters, lack of character encoding awareness, and misrepresentations of what functions are capable of by some programmers - these all make escaping in PHP an unnecessarily convoluted quest for those who just want an escaping function that works across all HTML contexts. See links below.
Including more narrowly defined and specifically targeted functions or SPL class methods into PHP will simplify the whole situation for users, offer a cohesive approach to escaping, rectify PHP's situation as only offering a partial XSS defense and, by its presence in Core, displace function misuse and homegrown escaping functions.
Escape filter for ext/filter
Implementation option as filter.
|FILTER_ESCAPE_HTML||“escape_html”||Escape HTML document|
|FILTER_ESCAPE_HTML_ATTR||“escape_html_attr”||Escape HTML tag attribute|
|FILTER_ESCAPE_CSS||“escape_css”||Escape CSS attribute|
|FILTER_ESCAPE_URI||“escape_uri”||Escape URI parameters|
|FILTER_ESCAPE_XML||“escape_xml”||Escape XML document||Alias of FILTER_ESCAPE_HTML|
|FILTER_ESCAPE_XML_ATTR||“escape_xml_attr”||Escape XML tag attribute|
While it may well be advisable to do both, I have a strong preference for classes coming from a framework heavily dependent on them and would suggest a class structure that implements the following interface in addition to any standalone functions:
The benefits of the class are to allow the centralised setting of a character encoding once and then being able to pass around the object across an entire application or library allowing it to be configured from a single location. This could be created in userland PHP around a set of functions but it seems silly to skip an obviously beneficial step to users.
Functions may then be added along the following lines (names up for discussion):
- escape_html($value, $encoding);
- escape_html_attribute($value, $encoding);
- escape_javascipt($value, $encoding);
- escape_css($value, $encoding);
- escape_url($value, $encoding);
- escape_xml($value, $encoding);
- escape_xml_attribute($value, $encoding);
IMPORTANT: Since proper escape requires proper character encoding handling, multibyte string feature in core is mandatory for implementation.
I am strongly opposed to allowing these functions accept unpredictable character encoding directives via php.ini. That would require additional work to validate which is precisely what this RFC should seek to avoid. By validation, I mean having programmers determine how dependencies implement escaping, what encoding they enforce (usually the default), and then determining if it can be changed by the depending applications or if the library must be forked, re-edited, etc. Those who are concious of security will review dependencies for such issues rather than blindly trust dependencies.
As there is no means of globally configuring a character encoding allowed in this RFC proposal since it promotes unconfigurable-default assumptions (already evidenced by existing htmlspecialchars() usage - search Github), the second parameter to these functions is explicitly required and has no default value. This works to undo the common practice in PHP where htmlspecialchars() calls omit all or most of its optional parameters. An application containing anything from thousands to tens of thousands of such function calls is extremely difficult to reconfigure at a later date and abusing the notion that all character encodings are equivalent to UTF-8 for special characters is itself definitely subject to infrequent browser bugs (e.g. IE6 is susceptible to character deletion when UTF-8 strings are escaped to a ISO-8859 encoding).
I have assumed that the character encodings supported are limited to those presently allowed by htmlspecialchars() and that the internals of each method or function validate this fact or throw an Exception (or an error for function calls) to prevent continued insecure execution as is currently allowed by htmlspecialchars(). See links below.
The following is a sample implementation in PHP from Zend Framework 2.0: https://github.com/zendframework/zf2/raw/master/library/Zend/Escaper/Escaper.php
Symfony's Twig also recently added similar escaping options: https://github.com/fabpot/Twig/raw/master/lib/Twig/Extension/Core.php
Class Method Dissection
The matching functions would, of course, be along the same lines.
The escapeHtml() function is basically identical to htmlspecialchars() but provides a few additional tweaks (validating encoding option, ceasing execution where invalid encoding detected, etc.). It assumes a default encoding of UTF-8 and behaves as if the ENT_QUOTES and ENT_SUBTITUTE flags were both set. As it would not accept a Doctype flag, escaping is done to the lowest common denominator which is XML. HTML5 itself has an XML serialisation which does not recognise any of the usual HTML named entities.
Typical HTML escaping can replace this method but only if the attribute value can be guaranteed as being properly quoted. Where quoting is not guaranteed, this method performs additional escaping that escapes all space characters and their equivalents that might be used to break out of an attribute context in the absence of quotes. In effect, this means escaping everything except basic alphanumeric characters and the comma, period, hyhen and underscore characters. Anything else will be escaped as a hexadecimal entity unless a valid XML named entity can be substituted.
CSS escaping applies to property values, e.g. a colour or font size. Where CSS is being manipulated further by adding new properies or names, it must be seperately sanitised.
This method is basically an alias for rawurlencode() which has applied RFC 3986 since PHP 5.3. It is included primarily for consistency.
URL escaping applies to data being inserted into a URL and not to the whole URL itself.
Since the escapeHtml method uses a common denominator escaping strategy to cover the XML serialisation of HTML5, escapeXml and escapeXmlAttr are functionally equivalent aliases for the sake of being explicit.
Finding Holes For XSS In Existing Functions
In support of the inconsistency argument, I wrote a blog article a while ago about htmlspecialchars() and the circumstances of those use cases where its escaping functionality could be defeated:
The point of these two mentions is to make it clear that currently PHP may offer related functions for preventing XSS but these do not have the coverage or safety required of recommended practices. The RFC is not a case of ignoring existing functions, it simply proposes replacements and additions that are reliable, safe, in line with OWASP recommendations, and are easy to use properly by programmers.
Implementation for PHP Core?
As my C skills are beyond rusty (they are barnacle encrusted at the bottom of the Atlantic), implementation of a patch for this RFC would require another volunteer to write it. Countless virtual cookies await this individual.
The essence of this RFC is to propose including basic safe escaping functionality within PHP which addresses the need to apply context-specific escaping in web applications. By offering a simple consistent approach, it affords the opportunity to implement these specifically to target XSS and to omit other functionality that some native functions include, and which can be problematic to programmers or doesn't go far enough. Centralising escaping functionality into one consistent package would, I believe, be one more small step to improving the application of escaping in PHP.