3 # kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
4 # Copyright (C) 2002, 2003, 2005 Ulf Harnhammar
6 # This program is free software and open source software; you can redistribute
7 # it and/or modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; either version 2 of the License,
9 # or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but WITHOUT
12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit
19 # http://www.gnu.org/licenses/gpl.html
21 # *** CONTACT INFORMATION ***
23 # E-mail: metaur at users dot sourceforge dot net
24 # Web page: http://sourceforge.net/projects/kses
25 # Paper mail: Ulf Harnhammar
30 # [kses strips evil scripts!]
35 # * 2008-01-18 Tatsuki Sugiura <sugi@osdn.jp>
36 # * add callback attribute filter
40 function kses($string, $allowed_html, $allowed_protocols =
41 array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
43 ###############################################################################
44 # This function makes sure that only the allowed HTML element names, attribute
45 # names and attribute values plus only sane HTML entities will occur in
46 # $string. You have to remove any slashes from PHP's magic quotes before you
48 ###############################################################################
50 $string = kses_no_null($string);
51 $string = kses_js_entities($string);
52 $string = kses_normalize_entities($string);
53 $string = kses_hook($string);
54 $allowed_html_fixed = kses_array_lc($allowed_html);
55 return kses_split($string, $allowed_html_fixed, $allowed_protocols);
59 function kses_hook($string)
60 ###############################################################################
61 # You add any kses hooks here.
62 ###############################################################################
65 } # function kses_hook
68 function kses_version()
69 ###############################################################################
70 # This function returns kses' version number.
71 ###############################################################################
74 } # function kses_version
77 function kses_split($string, $allowed_html, $allowed_protocols)
78 ###############################################################################
79 # This function searches for HTML tags, no matter how malformed. It also
80 # matches stray ">" characters.
81 ###############################################################################
83 return preg_replace_callback('%(<'. # EITHER: <
84 '[^>]*'. # things that aren't >
85 '(>|$)'. # > or end of string
86 '|>)%', # OR: just a >
87 function ($m) use ($allowed_html, $allowed_protocols) { return kses_split2($m[1], $allowed_html, $allowed_protocols); },
89 } # function kses_split
92 function kses_split2($string, $allowed_html, $allowed_protocols)
93 ###############################################################################
94 # This function does a lot of work. It rejects some very malformed things
95 # like <:::>. It returns an empty string, if the element isn't allowed (look
96 # ma, no strip_tags()!). Otherwise it splits the tag into an element and an
98 ###############################################################################
100 $string = kses_stripslashes($string);
102 if (substr($string, 0, 1) != '<')
104 # It matched a ">" character
106 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
108 # It's seriously malformed
110 $slash = trim($matches[1]);
112 $attrlist = $matches[3];
114 if (!@isset($allowed_html[strtolower($elem)]))
116 # They are using a not allowed HTML element
119 return "<$slash$elem>";
120 # No attributes are allowed for closing elements
122 return kses_attr("$slash$elem", $attrlist, $allowed_html,
124 } # function kses_split2
127 function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
128 ###############################################################################
129 # This function removes all attributes, if none are allowed for this element.
130 # If some are allowed it calls kses_hair() to split them further, and then it
131 # builds up new HTML code from the data that kses_hair() returns. It also
132 # removes "<" and ">" characters, if there are any left. One more thing it
133 # does is to check if the tag has a closing XHTML slash, and if it does,
134 # it puts one in the returned code as well.
135 ###############################################################################
137 # Is there a closing XHTML slash at the end of the attributes?
140 if (preg_match('%\s/\s*$%', $attr))
143 # Are any attributes allowed at all for this element?
145 if (@count($allowed_html[strtolower($element)]) == 0)
146 return "<$element$xhtml_slash>";
150 $attrarr = kses_hair($attr, $allowed_protocols);
152 # Go through $attrarr, and save the allowed attributes for this element
157 foreach ($attrarr as $arreach)
159 if (!@isset($allowed_html[strtolower($element)]
160 [strtolower($arreach['name'])]))
161 continue; # the attribute is not allowed
163 $current = $allowed_html[strtolower($element)]
164 [strtolower($arreach['name'])];
166 if (!is_array($current))
167 $attr2 .= ' '.$arreach['whole'];
168 # there are no checks
172 # there are some checks
174 foreach ($current as $currkey => $currval)
175 if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
177 { $ok = false; break; }
180 $attr2 .= ' '.$arreach['whole']; # it passed them
181 } # if !is_array($current)
184 # Remove any "<" or ">" characters
186 $attr2 = preg_replace('/[<>]/', '', $attr2);
188 return "<$element$attr2$xhtml_slash>";
189 } # function kses_attr
192 function kses_hair($attr, $allowed_protocols)
193 ###############################################################################
194 # This function does a lot of work. It parses an attribute list into an array
195 # with attribute data, and tries to do the right thing even if it gets weird
196 # input. It will add quotes around attribute values that don't have any quotes
197 # or apostrophes around them, to make it easier to produce HTML code that will
198 # conform to W3C's HTML specification. It will also remove bad URL protocols
199 # from attribute values.
200 ###############################################################################
206 # Loop through the whole attribute list
208 while (strlen($attr) != 0)
210 $working = 0; # Was the last operation successful?
214 case 0: # attribute name, href for instance
216 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
218 $attrname = $match[1];
219 $working = $mode = 1;
220 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
225 case 1: # equals sign or valueless ("selected")
227 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
229 $working = 1; $mode = 2;
230 $attr = preg_replace('/^\s*=\s*/', '', $attr);
234 if (preg_match('/^\s+/', $attr)) # valueless
236 $working = 1; $mode = 0;
238 ('name' => $attrname,
240 'whole' => $attrname,
242 $attr = preg_replace('/^\s+/', '', $attr);
247 case 2: # attribute value, a URL after href= for instance
249 if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
252 if (strtolower($attrname) !== "style") {
253 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
255 $thisval = $match[1];
259 ('name' => $attrname,
261 'whole' => "$attrname=\"$thisval\"",
263 $working = 1; $mode = 0;
264 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
268 if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
271 if (strtolower($attrname) !== "style") {
272 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
274 $thisval = $match[1];
278 ('name' => $attrname,
280 'whole' => "$attrname='$thisval'",
282 $working = 1; $mode = 0;
283 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
287 if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
290 if (strtolower($attrname) !== "style") {
291 $thisval = kses_bad_protocol($match[1], $allowed_protocols);
293 $thisval = $match[1];
297 ('name' => $attrname,
299 'whole' => "$attrname=\"$thisval\"",
301 # We add quotes to conform to W3C's HTML spec.
302 $working = 1; $mode = 0;
303 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
309 if ($working == 0) # not well formed, remove and try again
311 $attr = kses_html_error($attr);
317 # special case, for when the attribute list ends with a valueless
318 # attribute like "selected"
320 ('name' => $attrname,
322 'whole' => $attrname,
326 } # function kses_hair
329 function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
330 ###############################################################################
331 # This function performs different checks for attribute values. The currently
332 # implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
333 # with even more checks to come soon.
334 ###############################################################################
338 switch (strtolower($checkname))
341 # The maxlen check makes sure that the attribute value has a length not
342 # greater than the given value. This can be used to avoid Buffer Overflows
343 # in WWW clients and various Internet servers.
345 if (strlen($value) > $checkvalue)
350 # The minlen check makes sure that the attribute value has a length not
351 # smaller than the given value.
353 if (strlen($value) < $checkvalue)
358 # The maxval check does two things: it checks that the attribute value is
359 # an integer from 0 and up, without an excessive amount of zeroes or
360 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
361 # value is not greater than the given value.
362 # This check can be used to avoid Denial of Service attacks.
364 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
366 if ($value > $checkvalue)
371 # The minval check checks that the attribute value is a positive integer,
372 # and that it is not smaller than the given value.
374 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
376 if ($value < $checkvalue)
381 # The valueless check checks if the attribute has a value
382 # (like <a href="blah">) or not (<option selected>). If the given value
383 # is a "y" or a "Y", the attribute must not have a value.
384 # If the given value is an "n" or an "N", the attribute must have one.
386 if (strtolower($checkvalue) != $vless)
391 # The value is checked CSS expression
392 $ok = $checkvalue ? kses_verify_css($value) : true;
396 # The value is checked specified function
397 if (is_callable($checkvalue))
399 $ok = call_user_func($checkvalue, $value);
404 trigger_error("can't call callback function '$checkvalue'");
410 } # function kses_check_attr_val
413 function kses_bad_protocol($string, $allowed_protocols)
414 ###############################################################################
415 # This function removes all non-allowed protocols from the beginning of
416 # $string. It ignores whitespace and the case of the letters, and it does
417 # understand HTML entities. It does its work in a while loop, so it won't be
418 # fooled by a string like "javascript:javascript:alert(57)".
419 ###############################################################################
421 $string = kses_no_null($string);
422 # commented out to stop breaking multibyte chars
423 # see http://groups.google.com/group/wp-ja-pkg/browse_thread/thread/36c994dbd9276754/c3c0adb86a8b725d for details.
426 #$string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
427 $string2 = $string.'a';
429 while ($string != $string2)
432 $string = kses_bad_protocol_once($string, $allowed_protocols);
436 } # function kses_bad_protocol
439 function kses_no_null($string)
440 ###############################################################################
441 # This function removes any NULL characters in $string.
442 ###############################################################################
444 $string = preg_replace('/\0+/', '', $string);
445 $string = preg_replace('/(\\\\0)+/', '', $string);
448 } # function kses_no_null
451 function kses_stripslashes($string)
452 ###############################################################################
453 # This function changes the character sequence \" to just "
454 # It leaves all other slashes alone. It's really weird, but the quoting from
455 # preg_replace(//e) seems to require this.
456 ###############################################################################
458 return preg_replace('%\\\\"%', '"', $string);
459 } # function kses_stripslashes
462 function kses_array_lc($inarray)
463 ###############################################################################
464 # This function goes through an array, and changes the keys to all lower case.
465 ###############################################################################
469 foreach ($inarray as $inkey => $inval)
471 $outkey = strtolower($inkey);
472 $outarray[$outkey] = array();
474 foreach ($inval as $inkey2 => $inval2)
476 $outkey2 = strtolower($inkey2);
477 $outarray[$outkey][$outkey2] = $inval2;
482 } # function kses_array_lc
485 function kses_js_entities($string)
486 ###############################################################################
487 # This function removes the HTML JavaScript entities found in early versions of
489 ###############################################################################
491 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
492 } # function kses_js_entities
495 function kses_html_error($string)
496 ###############################################################################
497 # This function deals with parsing errors in kses_hair(). The general plan is
498 # to remove everything to and including some whitespace, but it deals with
499 # quotes and apostrophes as well.
500 ###############################################################################
502 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
503 } # function kses_html_error
506 function kses_bad_protocol_once($string, $allowed_protocols)
507 ###############################################################################
508 # This function searches for URL protocols at the beginning of $string, while
509 # handling whitespace and HTML entities.
510 ###############################################################################
512 return preg_replace_callback('/^((&[^;]*;|[\sA-Za-z0-9])*)'.
513 '(:|:|&#[Xx]3[Aa];)\s*/',
514 function ($m) { return kses_bad_protocol_once2($m[1], $allowed_protocols); },
516 } # function kses_bad_protocol_once
519 function kses_bad_protocol_once2($string, $allowed_protocols)
520 ###############################################################################
521 # This function processes URL protocols, checks to see if they're in the white-
522 # list or not, and returns different data depending on the answer.
523 ###############################################################################
525 $string2 = kses_decode_entities($string);
526 $string2 = preg_replace('/\s/', '', $string2);
527 $string2 = kses_no_null($string2);
528 $string2 = preg_replace('/\xad+/', '', $string2);
529 # deals with Opera "feature"
530 $string2 = strtolower($string2);
533 foreach ($allowed_protocols as $one_protocol)
534 if (strtolower($one_protocol) == $string2)
544 } # function kses_bad_protocol_once2
547 function kses_normalize_entities($string)
548 ###############################################################################
549 # This function normalizes HTML entities. It will convert "AT&T" to the correct
550 # "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
551 ###############################################################################
553 # Disarm all entities by converting & to &
555 $string = str_replace('&', '&', $string);
557 # Change back the allowed entities in our entity whitelist
559 $string = preg_replace('/&([A-Za-z][A-Za-z0-9]{0,19});/',
561 $string = preg_replace_callback('/&#0*([0-9]{1,5});/',
562 function ($m) { return kses_normalize_entities2($m[1]); },
564 $string = preg_replace('/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
565 '&#\\1\\2;', $string);
568 } # function kses_normalize_entities
571 function kses_normalize_entities2($i)
572 ###############################################################################
573 # This function helps kses_normalize_entities() to only accept 16 bit values
574 # and nothing more for &#number; entities.
575 ###############################################################################
577 return (($i > 65535) ? "&#$i;" : "&#$i;");
578 } # function kses_normalize_entities2
581 function kses_decode_entities($string)
582 ###############################################################################
583 # This function decodes numeric HTML entities (A and A). It doesn't
584 # do anything with other entities like ä, but we don't need them in the
585 # URL protocol whitelisting system anyway.
586 ###############################################################################
588 $string = preg_replace('/&#([0-9]+);/', function($m){return chr($m[1]);}, $string);
589 $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/', function($m){return chr(hexdec($m[1]));},
593 } # function kses_decode_entities
595 function _sanitize_hexentity($match) {
596 return '&#' . intval("0".substr($match[0], 2, strlen($match[0]) -3)) . ';';
599 function kses_verify_css($cssstr)
600 ###############################################################################
601 # CSS expression checker for IE.
602 # See URLs below for details;
603 # - http://openmya.hacker.jp/hasegawa/security/expression.txt
604 # - http://archive.openmya.devnull.jp/2006.08/msg00369.html
605 # - https://www.webappsec.jp/modules/bwiki/index.php?IE%A4%CEexpression%A4%C8url
606 ###############################################################################
608 if (!$cssstr) return true;
610 $cssstr = preg_replace_callback('/&#x[0-9A-F]+;/i', '_sanitize_hexentity', $cssstr);
611 $cssstr = mb_decode_numericentity($cssstr, array(0, 0xFFFFFF, 0, 0xFFFFFF), 'UTF-8');
612 $cssstr = preg_replace('/\x5c(\d+)/', '&#x\1;', $cssstr);
613 $cssstr = preg_replace_callback('/&#x[0-9A-F]+;/i', '_sanitize_hexentity', $cssstr);
614 $cssstr = mb_decode_numericentity($cssstr, array(0, 0xFFFFFF, 0, 0xFFFFFF), 'UTF-8');
615 $cssstr = preg_replace('{/\*.*?\*/|\x00+}', '', $cssstr);
616 $enc_orig = mb_regex_encoding();
617 mb_regex_encoding('UTF-8');
618 # e x p r e s s i o n
619 # FF45 FF58 FF50 FF52 FF45 FF53 FF53 FF49 FF4F FF4E
620 # FF25 FF38 FF30 FF32 FF25 FF33 FF33 FF29 FF2F FF2E
623 $ok = !mb_eregi('javascript:|@import|[e\x{ff45}\x{ff25}][x\x{ff58}\x{ff38}][p\x{ff50}\x{ff30}][r\x{ff52}\x{ff32}\x{0280}][e\x{ff45}\x{ff25}][s\x{ff53}\x{ff33}]{2}[i\x{ff49}\x{ff29}][o\x{ff4f}\x{ff2f}][n\x{ff4e}\x{ff2e}\x{0274}\x{207f}]', $cssstr);
624 mb_regex_encoding($enc_orig);