]> git.donarmstrong.com Git - roundcube.git/blob - program/lib/washtml.php
Imported Upstream version 0.2~alpha
[roundcube.git] / program / lib / washtml.php
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  * washtml::wash($html, $config, $full);
37  * It return a sanityzed string of the $html parameter without html and head tags.
38  * $html is a string containing the html code to wash.
39  * $config is an array containing options:
40  *   $config['allow_remote'] is a boolean to allow link to remote images.
41  *   $config['blocked_src'] string with image-src to be used for blocked remote images
42  *   $config['show_washed'] is a boolean to include washed out attributes as x-washed
43  *   $config['cid_map'] is an array where cid urls index urls to replace them.
44  *   $config['charset'] is a string containing the charset of the HTML document if it is not defined in it.
45  * $full is a reference to a boolean that is set to true if no remote images are removed. (FE: show remote images link)
46  *
47  * INTERNALS:
48  *
49  * Only tags and attributes in the globals $html_elements and $html_attributes
50  * are kept, inline styles are also filtered: all style identifiers matching
51  * /[a-z\-]/i are allowed. Values matching colors, sizes, /[a-z\-]/i and safe
52  * urls if allowed and cid urls if mapped are kept.
53  *
54  * BUGS: It MUST be safe !
55  *  - Check regexp
56  *  - urlencode URLs instead of htmlspecials
57  *  - Check is a 3 bytes utf8 first char can eat '">'
58  *  - Update PCRE: CVE-2007-1659 - CVE-2007-1660 - CVE-2007-1661 - CVE-2007-1662 
59  *                 CVE-2007-4766 - CVE-2007-4767 - CVE-2007-4768  
60  *    http://lists.debian.org/debian-security-announce/debian-security-announce-2007/msg00177.html 
61  *  - ...
62  *
63  * MISSING:
64  *  - relative links, can be implemented by prefixing an absolute path, ask me
65  *    if you need it...
66  *  - ...
67  *
68  * Dont be a fool:
69  *  - Dont alter data on a GET: '<img src="http://yourhost/mail?action=delete&uid=3267" />'
70  *  - ...
71  */
72
73 class washtml
74 {
75
76   /* Allowed HTML elements */
77   static $html_elements = array('a', 'abbr', 'acronym', 'address', 'area', 'b', 'basefont', 'bdo', 'big', 'blockquote', 'body', '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', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'img');
78
79   /* Allowed HTML attributes */
80   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');
81
82   /* Check CSS style */
83   static function wash_style($style, $config, &$full) {
84     $s = '';
85
86     foreach(explode(';', $style) as $declaration) {
87       if(preg_match('/^\s*([a-z\-]+)\s*:\s*(.*)\s*$/i', $declaration, $match)) {
88         $cssid = $match[1];
89         $str = $match[2];
90         $value = '';
91         while(sizeof($str) > 0 &&
92           preg_match('/^(url\(\s*[\'"]?([^\'"\)]*)[\'"]?\s*\)'./*1,2*/
93                  '|rgb\(\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[0-9]+\s*\)'.
94                  '|-?[0-9.]+\s*(em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)?'.
95                  '|#[0-9a-f]{3,6}|[a-z0-9\-]+'.
96                  ')\s*/i', $str, $match)) {
97           if($match[2]) {
98             if(preg_match('/^(http|https|ftp):.*$/i', $match[2], $url)) {
99               if($config['allow_remote'])
100                 $value .= ' url(\''.htmlspecialchars($url[0], ENT_QUOTES).'\')';
101               else
102                 $full = false;
103             } else if(preg_match('/^cid:(.*)$/i', $match[2], $cid))
104               $value .= ' url(\''.htmlspecialchars($config['cid_map']['cid:'.$cid[1]], ENT_QUOTES) . '\')';
105           } else if($match[0] != 'url' && $match[0] != 'rbg')//whitelist ?
106             $value .= ' ' . $match[0];
107           $str = substr($str, strlen($match[0]));
108         }
109         if($value)
110           $s .= ($s?' ':'') . $cssid . ':' . $value . ';';
111       }
112     }
113     return $s;
114   }
115
116   /* Take a node and return allowed attributes and check values */
117   static function wash_attribs($node, $config, &$full) {
118     $t = '';
119     $washed;
120
121     foreach($node->attributes as $key => $plop) {
122       $key = strtolower($key);
123       $value = $node->getAttribute($key);
124       if((in_array($key, self::$html_attribs)) ||
125          ($key == 'href' && preg_match('/^(http|https|ftp|mailto):.*/i', $value)))
126         $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
127       else if($key == 'style' && ($style = self::wash_style($value, $config, $full)))
128         $t .= ' style="' . $style . '"';
129       else if($key == 'src' && strtolower($node->tagName) == 'img') { //check tagName anyway
130         if(preg_match('/^(http|https|ftp):.*/i', $value)) {
131           if($config['allow_remote'])
132             $t .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
133           else {
134             $full = false;
135             if ($config['blocked_src'])
136               $t .= ' src="' . htmlspecialchars($config['blocked_src'], ENT_QUOTES) . '"';
137           }
138         } else if(preg_match('/^cid:(.*)$/i', $value, $cid))
139           $t .= ' ' . $key . '="' . htmlspecialchars($config['cid_map']['cid:'.$cid[1]], ENT_QUOTES) . '"';
140       } else
141         $washed .= ($washed?' ':'') . $key;
142     }
143     return $t . ($washed && $config['show_washed']?' x-washed="'.$washed.'"':'');
144   }
145
146   /* The main loop that recurse on a node tree.
147    * It output only allowed tags with allowed attributes
148    * and allowed inline styles */
149   static function dumpHtml($node, $config, &$full) {
150     if(!$node->hasChildNodes())
151       return '';
152
153     $node = $node->firstChild;
154     $dump = '';
155
156     do {
157       switch($node->nodeType) {
158       case XML_ELEMENT_NODE: //Check element
159         $tagName = strtolower($node->tagName);
160         if(in_array($tagName, self::$html_elements)) {
161           $content = self::dumpHtml($node, $config, $full);
162           $dump .= '<' . $tagName . self::wash_attribs($node, $config, $full) .
163             ($content?">$content</$tagName>":' />');
164         } else if($tagName == 'html' || $tagName == 'body') {
165           $dump .= self::dumpHtml($node, $config, $full); //Just ignored
166         } else
167           $dump .= '<!-- ' . htmlspecialchars($tagName, ENT_QUOTES) . ' not allowed -->';
168         break;
169       case XML_TEXT_NODE:
170         $dump .= htmlspecialchars($node->nodeValue);
171         break;
172       case XML_HTML_DOCUMENT_NODE:
173         $dump .= self::dumpHtml($node, $config, $full);
174         break;
175       case XML_DOCUMENT_TYPE_NODE: break;
176       default:
177       }
178     } while($node = $node->nextSibling);
179
180     return $dump;
181   }
182
183   /* Main function, give it untrusted HTML, tell it if you allow loading
184    * remote images and give it a map to convert "cid:" urls. */
185   static function wash($html, $config=array(), &$full=true) {
186     $config += array('show_washed'=>true, 'allow_remote'=>false, 'cid_map'=>array());
187     //Charset seems to be ignored (probably if defined in the HTML document)
188     $node = new DOMDocument('1.0', $config['charset']);
189     $full = true;
190     @$node->loadHTML($html);
191     return self::dumpHtml($node, $config, $full);
192   }
193
194 }
195
196 ?>