alecpl
2009-07-17 503e019a56b904a57171813f14db9ceaa81641cf
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  *  - ...
72  */
73
74 class washtml
75 {
21e724 76   /* Allowed HTML elements (default) */
f7fff8 77   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 78   
T 79   /* Ignore these HTML tags but process their content */
a47acc 80   static $ignore_elements = array('html', 'head', 'body');
21e724 81   
T 82   /* Allowed HTML attributes */
4cc74f 83   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 84
A 85   /* Block elements which could be empty but cannot be returned in short form (<tag />) */
86   static $block_elements = array('div', 'p', 'pre', 'blockquote');
21e724 87   
T 88   /* State for linked objects in HTML */
89   public $extlinks = false;
45f56c 90
21e724 91   /* Current settings */
T 92   private $config = array();
93
94   /* Registered callback functions for tags */
95   private $handlers = array();
96   
45f56c 97   /* Allowed HTML elements */
21e724 98   private $_html_elements = array();
T 99
100   /* Ignore these HTML tags but process their content */
101   private $_ignore_elements = array();
45f56c 102
503e01 103   /* Block elements which could be empty but cannot be returned in short form (<tag />) */
A 104   private $_block_elements = array();
105
45f56c 106   /* Allowed HTML attributes */
21e724 107   private $_html_attribs = array();
T 108   
45f56c 109
21e724 110   /* Constructor */
T 111   public function __construct($p = array()) {
112     $this->_html_elements = array_flip((array)$p['html_elements']) + array_flip(self::$html_elements) ;
113     $this->_html_attribs = array_flip((array)$p['html_attribs']) + array_flip(self::$html_attribs);
114     $this->_ignore_elements = array_flip((array)$p['ignore_elements']) + array_flip(self::$ignore_elements);
503e01 115     $this->_block_elements = array_flip((array)$p['block_elements']) + array_flip(self::$block_elements);
A 116     unset($p['html_elements'], $p['html_attribs'], $p['ignore_elements'], $p['block_elements']);
21e724 117     $this->config = $p + array('show_washed'=>true, 'allow_remote'=>false, 'cid_map'=>array());
T 118   }
119   
120   /* Register a callback function for a certain tag */
121   public function add_callback($tagName, $callback)
122   {
123     $this->handlers[$tagName] = $callback;
124   }
125   
45f56c 126   /* Check CSS style */
21e724 127   private function wash_style($style) {
45f56c 128     $s = '';
T 129
130     foreach(explode(';', $style) as $declaration) {
131       if(preg_match('/^\s*([a-z\-]+)\s*:\s*(.*)\s*$/i', $declaration, $match)) {
132         $cssid = $match[1];
133         $str = $match[2];
134         $value = '';
135         while(sizeof($str) > 0 &&
136           preg_match('/^(url\(\s*[\'"]?([^\'"\)]*)[\'"]?\s*\)'./*1,2*/
137                  '|rgb\(\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[0-9]+\s*\)'.
138                  '|-?[0-9.]+\s*(em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)?'.
139                  '|#[0-9a-f]{3,6}|[a-z0-9\-]+'.
140                  ')\s*/i', $str, $match)) {
141           if($match[2]) {
c505e5 142             if($src = $this->config['cid_map'][$match[2]])
T 143               $value .= ' url(\''.htmlspecialchars($src, ENT_QUOTES) . '\')';
144             else if(preg_match('/^(http|https|ftp):.*$/i', $match[2], $url)) {
21e724 145               if($this->config['allow_remote'])
45f56c 146                 $value .= ' url(\''.htmlspecialchars($url[0], ENT_QUOTES).'\')';
T 147               else
21e724 148                 $this->extlinks = true;
c505e5 149             }
45f56c 150           } else if($match[0] != 'url' && $match[0] != 'rbg')//whitelist ?
T 151             $value .= ' ' . $match[0];
152           $str = substr($str, strlen($match[0]));
153         }
154         if($value)
155           $s .= ($s?' ':'') . $cssid . ':' . $value . ';';
156       }
157     }
158     return $s;
159   }
160
161   /* Take a node and return allowed attributes and check values */
21e724 162   private function wash_attribs($node) {
45f56c 163     $t = '';
T 164     $washed;
165
166     foreach($node->attributes as $key => $plop) {
167       $key = strtolower($key);
168       $value = $node->getAttribute($key);
21e724 169       if(isset($this->_html_attribs[$key]) ||
4cc74f 170          ($key == 'href' && preg_match('/^(http|https|ftp|mailto):.+/i', $value)))
45f56c 171         $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
21e724 172       else if($key == 'style' && ($style = $this->wash_style($value)))
45f56c 173         $t .= ' style="' . $style . '"';
4cc74f 174       else if($key == 'background' || ($key == 'src' && strtolower($node->tagName) == 'img')) { //check tagName anyway
c505e5 175         if($src = $this->config['cid_map'][$value]) {
T 176           $t .= ' ' . $key . '="' . htmlspecialchars($src, ENT_QUOTES) . '"';
177         }
4cc74f 178         else if(preg_match('/^(http|https|ftp):.+/i', $value)) {
21e724 179           if($this->config['allow_remote'])
45f56c 180             $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
T 181           else {
21e724 182             $this->extlinks = true;
T 183             if ($this->config['blocked_src'])
4cc74f 184               $t .= ' ' . $key . '="' . htmlspecialchars($this->config['blocked_src'], ENT_QUOTES) . '"';
45f56c 185           }
c505e5 186         }
45f56c 187       } else
T 188         $washed .= ($washed?' ':'') . $key;
189     }
21e724 190     return $t . ($washed && $this->config['show_washed']?' x-washed="'.$washed.'"':'');
45f56c 191   }
T 192
193   /* The main loop that recurse on a node tree.
194    * It output only allowed tags with allowed attributes
195    * and allowed inline styles */
21e724 196   private function dumpHtml($node) {
45f56c 197     if(!$node->hasChildNodes())
T 198       return '';
199
200     $node = $node->firstChild;
201     $dump = '';
202
203     do {
204       switch($node->nodeType) {
205       case XML_ELEMENT_NODE: //Check element
206         $tagName = strtolower($node->tagName);
21e724 207         if($callback = $this->handlers[$tagName]) {
T 208           $dump .= call_user_func($callback, $tagName, $this->wash_attribs($node), $this->dumpHtml($node));
209         } else if(isset($this->_html_elements[$tagName])) {
210           $content = $this->dumpHtml($node);
211           $dump .= '<' . $tagName . $this->wash_attribs($node) .
503e01 212 //            ($content?">$content</$tagName>":' />');
A 213 // Roundcube Trac: #1485974
214             ($content || isset($this->_block_elements[$tagName]) ? ">$content</$tagName>" : ' />');
21e724 215         } else if(isset($this->_ignore_elements[$tagName])) {
T 216           $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' ignored -->';
217           $dump .= $this->dumpHtml($node); //Just ignored
45f56c 218         } else
T 219           $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' not allowed -->';
21e724 220         break;
T 221       case XML_CDATA_SECTION_NODE:
222         $dump .= $node->nodeValue;
45f56c 223         break;
T 224       case XML_TEXT_NODE:
225         $dump .= htmlspecialchars($node->nodeValue);
226         break;
227       case XML_HTML_DOCUMENT_NODE:
21e724 228         $dump .= $this->dumpHtml($node);
45f56c 229         break;
21e724 230       case XML_DOCUMENT_TYPE_NODE:
T 231         break;
45f56c 232       default:
21e724 233         $dump . '<!-- node type ' . $node->nodeType . ' -->';
45f56c 234       }
T 235     } while($node = $node->nextSibling);
236
237     return $dump;
238   }
239
240   /* Main function, give it untrusted HTML, tell it if you allow loading
241    * remote images and give it a map to convert "cid:" urls. */
21e724 242   public function wash($html) {
45f56c 243     //Charset seems to be ignored (probably if defined in the HTML document)
21e724 244     $node = new DOMDocument('1.0', $this->config['charset']);
T 245     $this->extlinks = false;
45f56c 246     @$node->loadHTML($html);
21e724 247     return $this->dumpHtml($node);
45f56c 248   }
T 249
250 }
251
252 ?>