alecpl
2010-06-23 be6f3a9d283198d6c6abb98fb540ab188b445f52
commit | author | age
45f56c 1 <?php
T 2 /*                Washtml, a HTML sanityzer.
3  *
4  * Copyright (c) 2007 Frederic Motte <fmotte@ubixis.com>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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.
26  */
27
28 /* Please send me your comments about this code if you have some, thanks, Fred. */
29
30 /* OVERVIEW:
31  *
32  * Wahstml take an untrusted HTML and return a safe html string.
33  *
34  * SYNOPSIS:
35  *
21e724 36  * $washer = new washtml($config);
T 37  * $washer->wash($html);
45f56c 38  * It return a sanityzed string of the $html parameter without html and head tags.
T 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.
21e724 46  * $washer->extlinks is a reference to a boolean that is set to true if remote images were removed. (FE: show remote images link)
45f56c 47  *
T 48  * INTERNALS:
49  *
21e724 50  * Only tags and attributes in the static lists $html_elements and $html_attributes
45f56c 51  * are kept, inline styles are also filtered: all style identifiers matching
T 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.
54  *
55  * BUGS: It MUST be safe !
56  *  - Check regexp
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 
62  *  - ...
63  *
64  * MISSING:
65  *  - relative links, can be implemented by prefixing an absolute path, ask me
66  *    if you need it...
67  *  - ...
68  *
69  * Dont be a fool:
70  *  - Dont alter data on a GET: '<img src="http://yourhost/mail?action=delete&uid=3267" />'
71  *  - ...
2337a8 72  *
A 73  * Roundcube Changes:
74  * - added $block_elements
75  * - changed $ignore_elements behaviour
0b7f3a 76  * - added RFC2397 support
b6f040 77  * - base URL support
45f56c 78  */
T 79
80 class washtml
81 {
21e724 82   /* Allowed HTML elements (default) */
f7fff8 83   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');
21e724 84   
2337a8 85   /* Ignore these HTML tags and their content */
A 86   static $ignore_elements = array('script', 'applet', 'embed', 'object', 'style');
21e724 87   
T 88   /* Allowed HTML attributes */
4cc74f 89   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');  
503e01 90
A 91   /* Block elements which could be empty but cannot be returned in short form (<tag />) */
be6f3a 92   static $block_elements = array('div', 'p', 'pre', 'blockquote', 'a', 'font', 'center', 'table', 'ul', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'dl');
21e724 93   
T 94   /* State for linked objects in HTML */
95   public $extlinks = false;
45f56c 96
21e724 97   /* Current settings */
T 98   private $config = array();
99
100   /* Registered callback functions for tags */
101   private $handlers = array();
102   
45f56c 103   /* Allowed HTML elements */
21e724 104   private $_html_elements = array();
T 105
106   /* Ignore these HTML tags but process their content */
107   private $_ignore_elements = array();
45f56c 108
503e01 109   /* Block elements which could be empty but cannot be returned in short form (<tag />) */
A 110   private $_block_elements = array();
111
45f56c 112   /* Allowed HTML attributes */
21e724 113   private $_html_attribs = array();
T 114   
45f56c 115
21e724 116   /* Constructor */
T 117   public function __construct($p = array()) {
118     $this->_html_elements = array_flip((array)$p['html_elements']) + array_flip(self::$html_elements) ;
119     $this->_html_attribs = array_flip((array)$p['html_attribs']) + array_flip(self::$html_attribs);
120     $this->_ignore_elements = array_flip((array)$p['ignore_elements']) + array_flip(self::$ignore_elements);
503e01 121     $this->_block_elements = array_flip((array)$p['block_elements']) + array_flip(self::$block_elements);
A 122     unset($p['html_elements'], $p['html_attribs'], $p['ignore_elements'], $p['block_elements']);
21e724 123     $this->config = $p + array('show_washed'=>true, 'allow_remote'=>false, 'cid_map'=>array());
T 124   }
125   
126   /* Register a callback function for a certain tag */
127   public function add_callback($tagName, $callback)
128   {
129     $this->handlers[$tagName] = $callback;
130   }
131   
45f56c 132   /* Check CSS style */
21e724 133   private function wash_style($style) {
45f56c 134     $s = '';
T 135
0b7f3a 136     foreach (explode(';', $style) as $declaration) {
A 137       if (preg_match('/^\s*([a-z\-]+)\s*:\s*(.*)\s*$/i', $declaration, $match)) {
45f56c 138         $cssid = $match[1];
T 139         $str = $match[2];
140         $value = '';
0b7f3a 141         while (sizeof($str) > 0 &&
45f56c 142           preg_match('/^(url\(\s*[\'"]?([^\'"\)]*)[\'"]?\s*\)'./*1,2*/
T 143                  '|rgb\(\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[0-9]+\s*\)'.
144                  '|-?[0-9.]+\s*(em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)?'.
145                  '|#[0-9a-f]{3,6}|[a-z0-9\-]+'.
146                  ')\s*/i', $str, $match)) {
0b7f3a 147           if ($match[2]) {
b6f040 148             if (($src = $this->config['cid_map'][$match[2]])
A 149                 || ($src = $this->config['cid_map'][$this->config['base_url'].$match[2]])) {
0b7f3a 150               $value .= ' url('.htmlspecialchars($src, ENT_QUOTES) . ')';
b6f040 151             }
0b7f3a 152             else if (preg_match('/^(http|https|ftp):.*$/i', $match[2], $url)) {
A 153               if ($this->config['allow_remote'])
154                 $value .= ' url('.htmlspecialchars($url[0], ENT_QUOTES).')';
45f56c 155               else
21e724 156                 $this->extlinks = true;
c505e5 157             }
a0d29e 158             else if (preg_match('/^data:.+/i', $match[2])) { // RFC2397
A 159               $value .= ' url('.htmlspecialchars($match[2], ENT_QUOTES).')';
0b7f3a 160             }
a0d29e 161           }
A 162           else if ($match[0] != 'url' && $match[0] != 'rbg') //whitelist ?
45f56c 163             $value .= ' ' . $match[0];
T 164           $str = substr($str, strlen($match[0]));
165         }
0b7f3a 166         if ($value)
45f56c 167           $s .= ($s?' ':'') . $cssid . ':' . $value . ';';
T 168       }
169     }
170     return $s;
171   }
172
173   /* Take a node and return allowed attributes and check values */
21e724 174   private function wash_attribs($node) {
45f56c 175     $t = '';
T 176     $washed;
177
0b7f3a 178     foreach ($node->attributes as $key => $plop) {
45f56c 179       $key = strtolower($key);
T 180       $value = $node->getAttribute($key);
0b7f3a 181       if (isset($this->_html_attribs[$key]) ||
e98f24 182          ($key == 'href' && preg_match('/^(http:|https:|ftp:|mailto:|#).+/i', $value)))
45f56c 183         $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
0b7f3a 184       else if ($key == 'style' && ($style = $this->wash_style($value)))
45f56c 185         $t .= ' style="' . $style . '"';
0b7f3a 186       else if ($key == 'background' || ($key == 'src' && strtolower($node->tagName) == 'img')) { //check tagName anyway
b6f040 187         if (($src = $this->config['cid_map'][$value])
A 188             || ($src = $this->config['cid_map'][$this->config['base_url'].$value])) {
c505e5 189           $t .= ' ' . $key . '="' . htmlspecialchars($src, ENT_QUOTES) . '"';
T 190         }
0b7f3a 191         else if (preg_match('/^(http|https|ftp):.+/i', $value)) {
A 192           if ($this->config['allow_remote'])
45f56c 193             $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
T 194           else {
21e724 195             $this->extlinks = true;
T 196             if ($this->config['blocked_src'])
4cc74f 197               $t .= ' ' . $key . '="' . htmlspecialchars($this->config['blocked_src'], ENT_QUOTES) . '"';
45f56c 198           }
c505e5 199         }
0b7f3a 200         else if (preg_match('/^data:.+/i', $value)) { // RFC2397
A 201           $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
202         }
45f56c 203       } else
T 204         $washed .= ($washed?' ':'') . $key;
205     }
21e724 206     return $t . ($washed && $this->config['show_washed']?' x-washed="'.$washed.'"':'');
45f56c 207   }
T 208
209   /* The main loop that recurse on a node tree.
210    * It output only allowed tags with allowed attributes
211    * and allowed inline styles */
21e724 212   private function dumpHtml($node) {
45f56c 213     if(!$node->hasChildNodes())
T 214       return '';
215
216     $node = $node->firstChild;
217     $dump = '';
218
219     do {
220       switch($node->nodeType) {
221       case XML_ELEMENT_NODE: //Check element
222         $tagName = strtolower($node->tagName);
b6f040 223         if ($callback = $this->handlers[$tagName]) {
21e724 224           $dump .= call_user_func($callback, $tagName, $this->wash_attribs($node), $this->dumpHtml($node));
b6f040 225         }
A 226         else if (isset($this->_html_elements[$tagName])) {
21e724 227           $content = $this->dumpHtml($node);
T 228           $dump .= '<' . $tagName . $this->wash_attribs($node) .
be6f3a 229             // create closing tag for block elements, but also for elements
A 230             // with content or with some attributes (eg. style, class) (#1486812)
231             ($content != '' || $node->hasAttributes() || isset($this->_block_elements[$tagName]) ? ">$content</$tagName>" : ' />');
b6f040 232         }
A 233         else if (isset($this->_ignore_elements[$tagName])) {
45f56c 234           $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' not allowed -->';
b6f040 235         }
A 236         else {
2337a8 237           $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' ignored -->';
A 238           $dump .= $this->dumpHtml($node); // ignore tags not its content
b6f040 239         }
21e724 240         break;
T 241       case XML_CDATA_SECTION_NODE:
242         $dump .= $node->nodeValue;
45f56c 243         break;
T 244       case XML_TEXT_NODE:
245         $dump .= htmlspecialchars($node->nodeValue);
246         break;
247       case XML_HTML_DOCUMENT_NODE:
21e724 248         $dump .= $this->dumpHtml($node);
45f56c 249         break;
21e724 250       case XML_DOCUMENT_TYPE_NODE:
T 251         break;
45f56c 252       default:
21e724 253         $dump . '<!-- node type ' . $node->nodeType . ' -->';
45f56c 254       }
T 255     } while($node = $node->nextSibling);
256
257     return $dump;
258   }
259
260   /* Main function, give it untrusted HTML, tell it if you allow loading
261    * remote images and give it a map to convert "cid:" urls. */
b6f040 262   public function wash($html)
A 263   {
264     // Charset seems to be ignored (probably if defined in the HTML document)
21e724 265     $node = new DOMDocument('1.0', $this->config['charset']);
T 266     $this->extlinks = false;
b6f040 267
A 268     // Find base URL for images
269     if (preg_match('/<base\s+href=[\'"]*([^\'"]+)/is', $html, $matches))
270       $this->config['base_url'] = $matches[1];
271     else
272       $this->config['base_url'] = '';
273
45f56c 274     @$node->loadHTML($html);
21e724 275     return $this->dumpHtml($node);
45f56c 276   }
T 277
278 }
279
2337a8 280 ?>