~ubuntu-branches/ubuntu/hoary/moodle/hoary

« back to all changes in this revision

Viewing changes to lib/kses.php

  • Committer: Bazaar Package Importer
  • Author(s): Isaac Clerencia
  • Date: 2004-12-29 00:49:52 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20041229004952-gliyqzpj2w3e7clx
Tags: 1.4.3-1
* Urgency high as upstream release fixes several security bugs
* New upstream release
* Write database creation errors and warn the user about it, 
closes: #285842, #285842

Show diffs side-by-side

added added

removed removed

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