2 /* Washtml, a HTML sanityzer.
4 * Copyright (c) 2007 Frederic Motte <fmotte@ubixis.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 /* Please send me your comments about this code if you have some, thanks, Fred. */
32 * Wahstml take an untrusted HTML and return a safe html string.
36 * $washer = new washtml($config);
37 * $washer->wash($html);
38 * It return a sanityzed string of the $html parameter without html and head tags.
39 * $html is a string containing the html code to wash.
40 * $config is an array containing options:
41 * $config['allow_remote'] is a boolean to allow link to remote images.
42 * $config['blocked_src'] string with image-src to be used for blocked remote images
43 * $config['show_washed'] is a boolean to include washed out attributes as x-washed
44 * $config['cid_map'] is an array where cid urls index urls to replace them.
45 * $config['charset'] is a string containing the charset of the HTML document if it is not defined in it.
46 * $washer->extlinks is a reference to a boolean that is set to true if remote images were removed. (FE: show remote images link)
50 * Only tags and attributes in the static lists $html_elements and $html_attributes
51 * are kept, inline styles are also filtered: all style identifiers matching
52 * /[a-z\-]/i are allowed. Values matching colors, sizes, /[a-z\-]/i and safe
53 * urls if allowed and cid urls if mapped are kept.
55 * BUGS: It MUST be safe !
57 * - urlencode URLs instead of htmlspecials
58 * - Check is a 3 bytes utf8 first char can eat '">'
59 * - Update PCRE: CVE-2007-1659 - CVE-2007-1660 - CVE-2007-1661 - CVE-2007-1662
60 * CVE-2007-4766 - CVE-2007-4767 - CVE-2007-4768
61 * http://lists.debian.org/debian-security-announce/debian-security-announce-2007/msg00177.html
65 * - relative links, can be implemented by prefixing an absolute path, ask me
70 * - Dont alter data on a GET: '<img src="http://yourhost/mail?action=delete&uid=3267" />'
74 * - added $block_elements
75 * - changed $ignore_elements behaviour
76 * - added RFC2397 support
78 * - invalid HTML comments removal before parsing
83 /* Allowed HTML elements (default) */
84 static $html_elements = array('a', 'abbr', 'acronym', 'address', 'area', 'b', 'basefont', 'bdo', 'big', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'label', 'legend', 'li', 'map', 'menu', 'nobr', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'wbr', 'img');
86 /* Ignore these HTML tags and their content */
87 static $ignore_elements = array('script', 'applet', 'embed', 'object', 'style');
89 /* Allowed HTML attributes */
90 static $html_attribs = array('name', 'class', 'title', 'alt', 'width', 'height', 'align', 'nowrap', 'col', 'row', 'id', 'rowspan', 'colspan', 'cellspacing', 'cellpadding', 'valign', 'bgcolor', 'color', 'border', 'bordercolorlight', 'bordercolordark', 'face', 'marginwidth', 'marginheight', 'axis', 'border', 'abbr', 'char', 'charoff', 'clear', 'compact', 'coords', 'vspace', 'hspace', 'cellborder', 'size', 'lang', 'dir');
92 /* Block elements which could be empty but cannot be returned in short form (<tag />) */
93 static $block_elements = array('div', 'p', 'pre', 'blockquote', 'a', 'font', 'center', 'table', 'ul', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'dl', 'strong', 'i', 'b');
95 /* State for linked objects in HTML */
96 public $extlinks = false;
98 /* Current settings */
99 private $config = array();
101 /* Registered callback functions for tags */
102 private $handlers = array();
104 /* Allowed HTML elements */
105 private $_html_elements = array();
107 /* Ignore these HTML tags but process their content */
108 private $_ignore_elements = array();
110 /* Block elements which could be empty but cannot be returned in short form (<tag />) */
111 private $_block_elements = array();
113 /* Allowed HTML attributes */
114 private $_html_attribs = array();
118 public function __construct($p = array()) {
119 $this->_html_elements = array_flip((array)$p['html_elements']) + array_flip(self::$html_elements) ;
120 $this->_html_attribs = array_flip((array)$p['html_attribs']) + array_flip(self::$html_attribs);
121 $this->_ignore_elements = array_flip((array)$p['ignore_elements']) + array_flip(self::$ignore_elements);
122 $this->_block_elements = array_flip((array)$p['block_elements']) + array_flip(self::$block_elements);
123 unset($p['html_elements'], $p['html_attribs'], $p['ignore_elements'], $p['block_elements']);
124 $this->config = $p + array('show_washed'=>true, 'allow_remote'=>false, 'cid_map'=>array());
127 /* Register a callback function for a certain tag */
128 public function add_callback($tagName, $callback)
130 $this->handlers[$tagName] = $callback;
133 /* Check CSS style */
134 private function wash_style($style) {
137 foreach (explode(';', $style) as $declaration) {
138 if (preg_match('/^\s*([a-z\-]+)\s*:\s*(.*)\s*$/i', $declaration, $match)) {
142 while (sizeof($str) > 0 &&
143 preg_match('/^(url\(\s*[\'"]?([^\'"\)]*)[\'"]?\s*\)'./*1,2*/
144 '|rgb\(\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[0-9]+\s*\)'.
145 '|-?[0-9.]+\s*(em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)?'.
146 '|#[0-9a-f]{3,6}|[a-z0-9\-]+'.
147 ')\s*/i', $str, $match)) {
149 if (($src = $this->config['cid_map'][$match[2]])
150 || ($src = $this->config['cid_map'][$this->config['base_url'].$match[2]])) {
151 $value .= ' url('.htmlspecialchars($src, ENT_QUOTES) . ')';
153 else if (preg_match('/^(http|https|ftp):.*$/i', $match[2], $url)) {
154 if ($this->config['allow_remote'])
155 $value .= ' url('.htmlspecialchars($url[0], ENT_QUOTES).')';
157 $this->extlinks = true;
159 else if (preg_match('/^data:.+/i', $match[2])) { // RFC2397
160 $value .= ' url('.htmlspecialchars($match[2], ENT_QUOTES).')';
163 else if ($match[0] != 'url' && $match[0] != 'rbg') //whitelist ?
164 $value .= ' ' . $match[0];
165 $str = substr($str, strlen($match[0]));
168 $s .= ($s?' ':'') . $cssid . ':' . $value . ';';
174 /* Take a node and return allowed attributes and check values */
175 private function wash_attribs($node) {
179 foreach ($node->attributes as $key => $plop) {
180 $key = strtolower($key);
181 $value = $node->getAttribute($key);
182 if (isset($this->_html_attribs[$key]) ||
183 ($key == 'href' && preg_match('/^(http:|https:|ftp:|mailto:|#).+/i', $value)))
184 $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
185 else if ($key == 'style' && ($style = $this->wash_style($value)))
186 $t .= ' style="' . $style . '"';
187 else if ($key == 'background' || ($key == 'src' && strtolower($node->tagName) == 'img')) { //check tagName anyway
188 if (($src = $this->config['cid_map'][$value])
189 || ($src = $this->config['cid_map'][$this->config['base_url'].$value])) {
190 $t .= ' ' . $key . '="' . htmlspecialchars($src, ENT_QUOTES) . '"';
192 else if (preg_match('/^(http|https|ftp):.+/i', $value)) {
193 if ($this->config['allow_remote'])
194 $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
196 $this->extlinks = true;
197 if ($this->config['blocked_src'])
198 $t .= ' ' . $key . '="' . htmlspecialchars($this->config['blocked_src'], ENT_QUOTES) . '"';
201 else if (preg_match('/^data:.+/i', $value)) { // RFC2397
202 $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
205 $washed .= ($washed?' ':'') . $key;
207 return $t . ($washed && $this->config['show_washed']?' x-washed="'.$washed.'"':'');
210 /* The main loop that recurse on a node tree.
211 * It output only allowed tags with allowed attributes
212 * and allowed inline styles */
213 private function dumpHtml($node) {
214 if(!$node->hasChildNodes())
217 $node = $node->firstChild;
221 switch($node->nodeType) {
222 case XML_ELEMENT_NODE: //Check element
223 $tagName = strtolower($node->tagName);
224 if ($callback = $this->handlers[$tagName]) {
225 $dump .= call_user_func($callback, $tagName, $this->wash_attribs($node), $this->dumpHtml($node));
227 else if (isset($this->_html_elements[$tagName])) {
228 $content = $this->dumpHtml($node);
229 $dump .= '<' . $tagName . $this->wash_attribs($node) .
230 // create closing tag for block elements, but also for elements
231 // with content or with some attributes (eg. style, class) (#1486812)
232 ($content != '' || $node->hasAttributes() || isset($this->_block_elements[$tagName]) ? ">$content</$tagName>" : ' />');
234 else if (isset($this->_ignore_elements[$tagName])) {
235 $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' not allowed -->';
238 $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' ignored -->';
239 $dump .= $this->dumpHtml($node); // ignore tags not its content
242 case XML_CDATA_SECTION_NODE:
243 $dump .= $node->nodeValue;
246 $dump .= htmlspecialchars($node->nodeValue);
248 case XML_HTML_DOCUMENT_NODE:
249 $dump .= $this->dumpHtml($node);
251 case XML_DOCUMENT_TYPE_NODE:
254 $dump . '<!-- node type ' . $node->nodeType . ' -->';
256 } while($node = $node->nextSibling);
261 /* Main function, give it untrusted HTML, tell it if you allow loading
262 * remote images and give it a map to convert "cid:" urls. */
263 public function wash($html)
265 // Charset seems to be ignored (probably if defined in the HTML document)
266 $node = new DOMDocument('1.0', $this->config['charset']);
267 $this->extlinks = false;
269 // Find base URL for images
270 if (preg_match('/<base\s+href=[\'"]*([^\'"]+)/is', $html, $matches))
271 $this->config['base_url'] = $matches[1];
273 $this->config['base_url'] = '';
275 // Remove invalid HTML comments (#1487759)
276 // Don't remove valid conditional comments
277 $html = preg_replace('/<!--[^->[\n]*>/', '', $html);
279 @$node->loadHTML($html);
280 return $this->dumpHtml($node);