root/trunk/licqweb/kses.php

Revision 4526, 19.0 kB (checked in by erijo, 2 years ago)

Removed svn:keywords from all files that don't need it. May make your
checkout a tiny bit faster :)

  • Property svn:eol-style set to native
Line 
1<?php
2
3# kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
4# Copyright (C) 2002, 2003, 2005  Ulf Harnhammar
5#
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.
10#
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
14# more details.
15#
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
20#
21# *** CONTACT INFORMATION ***
22#
23# E-mail:      metaur at users dot sourceforge dot net
24# Web page:    http://sourceforge.net/projects/kses
25# Paper mail:  Ulf Harnhammar
26#              Ymergatan 17 C
27#              753 25  Uppsala
28#              SWEDEN
29#
30# [kses strips evil scripts!]
31
32
33function kses($string, $allowed_html, $allowed_protocols =
34               array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',
35                     'gopher', 'mailto'))
36###############################################################################
37# This function makes sure that only the allowed HTML element names, attribute
38# names and attribute values plus only sane HTML entities will occur in
39# $string. You have to remove any slashes from PHP's magic quotes before you
40# call this function.
41###############################################################################
42{
43  $string = kses_no_null($string);
44  $string = kses_js_entities($string);
45  $string = kses_normalize_entities($string);
46  $string = kses_hook($string);
47  $allowed_html_fixed = kses_array_lc($allowed_html);
48  return kses_split($string, $allowed_html_fixed, $allowed_protocols);
49} # function kses
50
51
52function kses_hook($string)
53###############################################################################
54# You add any kses hooks here.
55###############################################################################
56{
57  return $string;
58} # function kses_hook
59
60
61function kses_version()
62###############################################################################
63# This function returns kses' version number.
64###############################################################################
65{
66  return '0.2.2';
67} # function kses_version
68
69
70function kses_split($string, $allowed_html, $allowed_protocols)
71###############################################################################
72# This function searches for HTML tags, no matter how malformed. It also
73# matches stray ">" characters.
74###############################################################################
75{
76  return preg_replace('%(<'.   # EITHER: <
77                      '[^>]*'. # things that aren't >
78                      '(>|$)'. # > or end of string
79                      '|>)%e', # OR: just a >
80                      "kses_split2('\\1', \$allowed_html, ".
81                      '$allowed_protocols)',
82                      $string);
83} # function kses_split
84
85
86function kses_split2($string, $allowed_html, $allowed_protocols)
87###############################################################################
88# This function does a lot of work. It rejects some very malformed things
89# like <:::>. It returns an empty string, if the element isn't allowed (look
90# ma, no strip_tags()!). Otherwise it splits the tag into an element and an
91# attribute list.
92###############################################################################
93{
94  $string = kses_stripslashes($string);
95
96  if (substr($string, 0, 1) != '<')
97    return '&gt;';
98    # It matched a ">" character
99
100  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
101    return '';
102    # It's seriously malformed
103
104  $slash = trim($matches[1]);
105  $elem = $matches[2];
106  $attrlist = $matches[3];
107
108  if (!@isset($allowed_html[strtolower($elem)])) {
109    $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), $string);
110    return $string;
111    # They are using a not allowed HTML element
112  }
113
114  if ($slash != '')
115    return "<$slash$elem>";
116  # No attributes are allowed for closing elements
117
118  return kses_attr("$slash$elem", $attrlist, $allowed_html,
119                   $allowed_protocols);
120} # function kses_split2
121
122
123function kses_attr($element, $attr, $allowed_html, $allowed_protocols)
124###############################################################################
125# This function removes all attributes, if none are allowed for this element.
126# If some are allowed it calls kses_hair() to split them further, and then it
127# builds up new HTML code from the data that kses_hair() returns. It also
128# removes "<" and ">" characters, if there are any left. One more thing it
129# does is to check if the tag has a closing XHTML slash, and if it does,
130# it puts one in the returned code as well.
131###############################################################################
132{
133# Is there a closing XHTML slash at the end of the attributes?
134
135  $xhtml_slash = '';
136  if (preg_match('%\s/\s*$%', $attr))
137    $xhtml_slash = ' /';
138
139# Are any attributes allowed at all for this element?
140
141  if (@count($allowed_html[strtolower($element)]) == 0)
142    return "<$element$xhtml_slash>";
143
144# Split it
145
146  $attrarr = kses_hair($attr, $allowed_protocols);
147
148# Go through $attrarr, and save the allowed attributes for this element
149# in $attr2
150
151  $attr2 = '';
152
153  foreach ($attrarr as $arreach)
154  {
155    if (!@isset($allowed_html[strtolower($element)]
156                            [strtolower($arreach['name'])]))
157      continue; # the attribute is not allowed
158
159    $current = $allowed_html[strtolower($element)]
160                            [strtolower($arreach['name'])];
161
162    if (!is_array($current))
163      $attr2 .= ' '.$arreach['whole'];
164    # there are no checks
165
166    else
167    {
168    # there are some checks
169      $ok = true;
170      foreach ($current as $currkey => $currval)
171        if (!kses_check_attr_val($arreach['value'], $arreach['vless'],
172                                 $currkey, $currval))
173        { $ok = false; break; }
174
175      if ($ok)
176        $attr2 .= ' '.$arreach['whole']; # it passed them
177    } # if !is_array($current)
178  } # foreach
179
180# Remove any "<" or ">" characters
181
182  $attr2 = preg_replace('/[<>]/', '', $attr2);
183
184  return "<$element$attr2$xhtml_slash>";
185} # function kses_attr
186
187
188function kses_hair($attr, $allowed_protocols)
189###############################################################################
190# This function does a lot of work. It parses an attribute list into an array
191# with attribute data, and tries to do the right thing even if it gets weird
192# input. It will add quotes around attribute values that don't have any quotes
193# or apostrophes around them, to make it easier to produce HTML code that will
194# conform to W3C's HTML specification. It will also remove bad URL protocols
195# from attribute values.
196###############################################################################
197{
198  $attrarr = array();
199  $mode = 0;
200  $attrname = '';
201
202# Loop through the whole attribute list
203
204  while (strlen($attr) != 0)
205  {
206    $working = 0; # Was the last operation successful?
207
208    switch ($mode)
209    {
210      case 0: # attribute name, href for instance
211
212        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
213        {
214          $attrname = $match[1];
215          $working = $mode = 1;
216          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
217        }
218
219        break;
220
221      case 1: # equals sign or valueless ("selected")
222
223        if (preg_match('/^\s*=\s*/', $attr)) # equals sign
224        {
225          $working = 1; $mode = 2;
226          $attr = preg_replace('/^\s*=\s*/', '', $attr);
227          break;
228        }
229
230        if (preg_match('/^\s+/', $attr)) # valueless
231        {
232          $working = 1; $mode = 0;
233          $attrarr[] = array
234                        ('name'  => $attrname,
235                         'value' => '',
236                         'whole' => $attrname,
237                         'vless' => 'y');
238          $attr = preg_replace('/^\s+/', '', $attr);
239        }
240
241        break;
242
243      case 2: # attribute value, a URL after href= for instance
244
245        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
246         # "value"
247        {
248          $thisval = kses_bad_protocol($match[1], $allowed_protocols);
249
250          $attrarr[] = array
251                        ('name'  => $attrname,
252                         'value' => $thisval,
253                         'whole' => "$attrname=\"$thisval\"",
254                         'vless' => 'n');
255          $working = 1; $mode = 0;
256          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
257          break;
258        }
259
260        if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
261         # 'value'
262        {
263          $thisval = kses_bad_protocol($match[1], $allowed_protocols);
264
265          $attrarr[] = array
266                        ('name'  => $attrname,
267                         'value' => $thisval,
268                         'whole' => "$attrname='$thisval'",
269                         'vless' => 'n');
270          $working = 1; $mode = 0;
271          $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
272          break;
273        }
274
275        if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
276         # value
277        {
278          $thisval = kses_bad_protocol($match[1], $allowed_protocols);
279
280          $attrarr[] = array
281                        ('name'  => $attrname,
282                         'value' => $thisval,
283                         'whole' => "$attrname=\"$thisval\"",
284                         'vless' => 'n');
285                         # We add quotes to conform to W3C's HTML spec.
286          $working = 1; $mode = 0;
287          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
288        }
289
290        break;
291    } # switch
292
293    if ($working == 0) # not well formed, remove and try again
294    {
295      $attr = kses_html_error($attr);
296      $mode = 0;
297    }
298  } # while
299
300  if ($mode == 1)
301  # special case, for when the attribute list ends with a valueless
302  # attribute like "selected"
303    $attrarr[] = array
304                  ('name'  => $attrname,
305                   'value' => '',
306                   'whole' => $attrname,
307                   'vless' => 'y');
308
309  return $attrarr;
310} # function kses_hair
311
312
313function kses_check_attr_val($value, $vless, $checkname, $checkvalue)
314###############################################################################
315# This function performs different checks for attribute values. The currently
316# implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"
317# with even more checks to come soon.
318###############################################################################
319{
320  $ok = true;
321
322  switch (strtolower($checkname))
323  {
324    case 'maxlen':
325    # The maxlen check makes sure that the attribute value has a length not
326    # greater than the given value. This can be used to avoid Buffer Overflows
327    # in WWW clients and various Internet servers.
328
329      if (strlen($value) > $checkvalue)
330        $ok = false;
331      break;
332
333    case 'minlen':
334    # The minlen check makes sure that the attribute value has a length not
335    # smaller than the given value.
336
337      if (strlen($value) < $checkvalue)
338        $ok = false;
339      break;
340
341    case 'maxval':
342    # The maxval check does two things: it checks that the attribute value is
343    # an integer from 0 and up, without an excessive amount of zeroes or
344    # whitespace (to avoid Buffer Overflows). It also checks that the attribute
345    # value is not greater than the given value.
346    # This check can be used to avoid Denial of Service attacks.
347
348      if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
349        $ok = false;
350      if ($value > $checkvalue)
351        $ok = false;
352      break;
353
354    case 'minval':
355    # The minval check checks that the attribute value is a positive integer,
356    # and that it is not smaller than the given value.
357
358      if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
359        $ok = false;
360      if ($value < $checkvalue)
361        $ok = false;
362      break;
363
364    case 'valueless':
365    # The valueless check checks if the attribute has a value
366    # (like <a href="blah">) or not (<option selected>). If the given value
367    # is a "y" or a "Y", the attribute must not have a value.
368    # If the given value is an "n" or an "N", the attribute must have one.
369
370      if (strtolower($checkvalue) != $vless)
371        $ok = false;
372      break;
373  } # switch
374
375  return $ok;
376} # function kses_check_attr_val
377
378
379function kses_bad_protocol($string, $allowed_protocols)
380###############################################################################
381# This function removes all non-allowed protocols from the beginning of
382# $string. It ignores whitespace and the case of the letters, and it does
383# understand HTML entities. It does its work in a while loop, so it won't be
384# fooled by a string like "javascript:javascript:alert(57)".
385###############################################################################
386{
387  $string = kses_no_null($string);
388  $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
389  $string2 = $string.'a';
390
391  while ($string != $string2)
392  {
393    $string2 = $string;
394    $string = kses_bad_protocol_once($string, $allowed_protocols);
395  } # while
396
397  return $string;
398} # function kses_bad_protocol
399
400
401function kses_no_null($string)
402###############################################################################
403# This function removes any NULL characters in $string.
404###############################################################################
405{
406  $string = preg_replace('/\0+/', '', $string);
407  $string = preg_replace('/(\\\\0)+/', '', $string);
408
409  return $string;
410} # function kses_no_null
411
412
413function kses_stripslashes($string)
414###############################################################################
415# This function changes the character sequence  \"  to just  "
416# It leaves all other slashes alone. It's really weird, but the quoting from
417# preg_replace(//e) seems to require this.
418###############################################################################
419{
420  return preg_replace('%\\\\"%', '"', $string);
421} # function kses_stripslashes
422
423
424function kses_array_lc($inarray)
425###############################################################################
426# This function goes through an array, and changes the keys to all lower case.
427###############################################################################
428{
429  $outarray = array();
430
431  foreach ($inarray as $inkey => $inval)
432  {
433    $outkey = strtolower($inkey);
434    $outarray[$outkey] = array();
435
436    foreach ($inval as $inkey2 => $inval2)
437    {
438      $outkey2 = strtolower($inkey2);
439      $outarray[$outkey][$outkey2] = $inval2;
440    } # foreach $inval
441  } # foreach $inarray
442
443  return $outarray;
444} # function kses_array_lc
445
446
447function kses_js_entities($string)
448###############################################################################
449# This function removes the HTML JavaScript entities found in early versions of
450# Netscape 4.
451###############################################################################
452{
453  return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
454} # function kses_js_entities
455
456
457function kses_html_error($string)
458###############################################################################
459# This function deals with parsing errors in kses_hair(). The general plan is
460# to remove everything to and including some whitespace, but it deals with
461# quotes and apostrophes as well.
462###############################################################################
463{
464  return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
465} # function kses_html_error
466
467
468function kses_bad_protocol_once($string, $allowed_protocols)
469###############################################################################
470# This function searches for URL protocols at the beginning of $string, while
471# handling whitespace and HTML entities.
472###############################################################################
473{
474  return preg_replace('/^((&[^;]*;|[\sA-Za-z0-9])*)'.
475                      '(:|&#58;|&#[Xx]3[Aa];)\s*/e',
476                      'kses_bad_protocol_once2("\\1", $allowed_protocols)',
477                      $string);
478} # function kses_bad_protocol_once
479
480
481function kses_bad_protocol_once2($string, $allowed_protocols)
482###############################################################################
483# This function processes URL protocols, checks to see if they're in the white-
484# list or not, and returns different data depending on the answer.
485###############################################################################
486{
487  $string2 = kses_decode_entities($string);
488  $string2 = preg_replace('/\s/', '', $string2);
489  $string2 = kses_no_null($string2);
490  $string2 = preg_replace('/\xad+/', '', $string2);
491   # deals with Opera "feature"
492  $string2 = strtolower($string2);
493
494  $allowed = false;
495  foreach ($allowed_protocols as $one_protocol)
496    if (strtolower($one_protocol) == $string2)
497    {
498      $allowed = true;
499      break;
500    }
501
502  if ($allowed)
503    return "$string2:";
504  else
505    return '';
506} # function kses_bad_protocol_once2
507
508
509function kses_normalize_entities($string)
510###############################################################################
511# This function normalizes HTML entities. It will convert "AT&T" to the correct
512# "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
513###############################################################################
514{
515# Disarm all entities by converting & to &amp;
516
517  $string = str_replace('&', '&amp;', $string);
518
519# Change back the allowed entities in our entity whitelist
520
521  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',
522                         '&\\1;', $string);
523  $string = preg_replace('/&amp;#0*([0-9]{1,5});/e',
524                         'kses_normalize_entities2("\\1")', $string);
525  $string = preg_replace('/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
526                         '&#\\1\\2;', $string);
527
528  return $string;
529} # function kses_normalize_entities
530
531
532function kses_normalize_entities2($i)
533###############################################################################
534# This function helps kses_normalize_entities() to only accept 16 bit values
535# and nothing more for &#number; entities.
536###############################################################################
537{
538  return (($i > 65535) ? "&amp;#$i;" : "&#$i;");
539} # function kses_normalize_entities2
540
541
542function kses_decode_entities($string)
543###############################################################################
544# This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't
545# do anything with other entities like &auml;, but we don't need them in the
546# URL protocol whitelisting system anyway.
547###############################################################################
548{
549  $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
550  $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))',
551                         $string);
552
553  return $string;
554} # function kses_decode_entities
555
556?>
Note: See TracBrowser for help on using the browser.