source: subversion/trunk/roundcubemail/program/lib/washtml.php @ 1603

Last change on this file since 1603 was 1603, checked in by thomasb, 5 years ago

Improve HTML sanitization with washtml

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