]> git.mjollnir.org Git - moodle.git/commitdiff
Added better cleaning of HTML attributes, using kses library.
authormoodler <moodler>
Sat, 21 Aug 2004 04:34:06 +0000 (04:34 +0000)
committermoodler <moodler>
Sat, 21 Aug 2004 04:34:06 +0000 (04:34 +0000)
Thanks to Eamon Costello for finding the library and writing the
wrapper functions.

lib/kses.php [new file with mode: 0644]
lib/weblib.php

diff --git a/lib/kses.php b/lib/kses.php
new file mode 100644 (file)
index 0000000..260b49b
--- /dev/null
@@ -0,0 +1,545 @@
+<?php\r
+\r
+# kses 0.2.1 - HTML/XHTML filter that only allows some elements and attributes\r
+# Copyright (C) 2002, 2003  Ulf Harnhammar\r
+#\r
+# This program is free software and open source software; you can redistribute\r
+# it and/or modify it under the terms of the GNU General Public License as\r
+# published by the Free Software Foundation; either version 2 of the License,\r
+# or (at your option) any later version.\r
+#\r
+# This program is distributed in the hope that it will be useful, but WITHOUT\r
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\r
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\r
+# more details.\r
+#\r
+# You should have received a copy of the GNU General Public License along\r
+# with this program; if not, write to the Free Software Foundation, Inc.,\r
+# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  or visit\r
+# http://www.gnu.org/licenses/gpl.html\r
+#\r
+# *** CONTACT INFORMATION ***\r
+#\r
+# E-mail:      metaur at users dot sourceforge dot net\r
+# Web page:    http://sourceforge.net/projects/kses\r
+# Paper mail:  (not at the moment)\r
+#\r
+# [kses strips evil scripts!]\r
+\r
+\r
+function kses($string, $allowed_html, $allowed_protocols =\r
+               array('http', 'https', 'ftp', 'news', 'nntp', 'telnet',\r
+                     'gopher', 'mailto'))\r
+###############################################################################\r
+# This function makes sure that only the allowed HTML element names, attribute\r
+# names and attribute values plus only sane HTML entities will occur in\r
+# $string. You have to remove any slashes from PHP's magic quotes before you\r
+# call this function.\r
+###############################################################################\r
+{\r
+  $string = kses_no_null($string);\r
+  $string = kses_js_entities($string);\r
+  $string = kses_normalize_entities($string);\r
+  $string = kses_hook($string);\r
+  $allowed_html_fixed = kses_array_lc($allowed_html);\r
+  return kses_split($string, $allowed_html_fixed, $allowed_protocols);\r
+} # function kses\r
+\r
+\r
+function kses_hook($string)\r
+###############################################################################\r
+# You add any kses hooks here.\r
+###############################################################################\r
+{\r
+  return $string;\r
+} # function kses_hook\r
+\r
+\r
+function kses_version()\r
+###############################################################################\r
+# This function returns kses' version number.\r
+###############################################################################\r
+{\r
+  return '0.2.1';\r
+} # function kses_version\r
+\r
+\r
+function kses_split($string, $allowed_html, $allowed_protocols)\r
+###############################################################################\r
+# This function searches for HTML tags, no matter how malformed. It also\r
+# matches stray ">" characters.\r
+###############################################################################\r
+{\r
+  return preg_replace('%(<'.   # EITHER: <\r
+                      '[^>]*'. # things that aren't >\r
+                      '(>|$)'. # > or end of string\r
+                      '|>)%e', # OR: just a >\r
+                      "kses_split2('\\1', \$allowed_html, ".\r
+                      '$allowed_protocols)',\r
+                      $string);\r
+} # function kses_split\r
+\r
+\r
+function kses_split2($string, $allowed_html, $allowed_protocols)\r
+###############################################################################\r
+# This function does a lot of work. It rejects some very malformed things\r
+# like <:::>. It returns an empty string, if the element isn't allowed (look\r
+# ma, no strip_tags()!). Otherwise it splits the tag into an element and an\r
+# attribute list.\r
+###############################################################################\r
+{\r
+  $string = kses_stripslashes($string);\r
+\r
+  if (substr($string, 0, 1) != '<')\r
+    return '&gt;';\r
+    # It matched a ">" character\r
+\r
+  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))\r
+    return '';\r
+    # It's seriously malformed\r
+\r
+  $slash = trim($matches[1]);\r
+  $elem = $matches[2];\r
+  $attrlist = $matches[3];\r
\r
+               \r
+         if ( !is_array($allowed_html[strtolower($elem)]))\r
+               return '';\r
+               # They are using a not allowed HTML element\r
+\r
+\r
+  return kses_attr("$slash$elem", $attrlist, $allowed_html,\r
+                   $allowed_protocols);\r
+} # function kses_split2\r
+\r
+\r
+function kses_attr($element, $attr, $allowed_html, $allowed_protocols)\r
+###############################################################################\r
+# This function removes all attributes, if none are allowed for this element.\r
+# If some are allowed it calls kses_hair() to split them further, and then it\r
+# builds up new HTML code from the data that kses_hair() returns. It also\r
+# removes "<" and ">" characters, if there are any left. One more thing it\r
+# does is to check if the tag has a closing XHTML slash, and if it does,\r
+# it puts one in the returned code as well.\r
+###############################################################################\r
+{\r
+# Is there a closing XHTML slash at the end of the attributes?\r
+\r
+  $xhtml_slash = '';\r
+  if (preg_match('%\s/\s*$%', $attr))\r
+    $xhtml_slash = ' /';\r
+\r
+# Are any attributes allowed at all for this element?\r
+\r
+  if (count($allowed_html[strtolower($element)]) == 0)\r
+    return "<$element$xhtml_slash>";\r
+\r
+# Split it\r
+\r
+  $attrarr = kses_hair($attr, $allowed_protocols);\r
+\r
+# Go through $attrarr, and save the allowed attributes for this element\r
+# in $attr2\r
+\r
+  $attr2 = '';\r
+\r
+  foreach ($attrarr as $arreach)\r
+  {\r
+    $current = $allowed_html[strtolower($element)]\r
+                            [strtolower($arreach['name'])];\r
+    if ($current == '')\r
+      continue; # the attribute is not allowed\r
+\r
+    if (!is_array($current))\r
+      $attr2 .= ' '.$arreach['whole'];\r
+    # there are no checks\r
+\r
+    else\r
+    {\r
+    # there are some checks\r
+      $ok = true;\r
+      foreach ($current as $currkey => $currval)\r
+        if (!kses_check_attr_val($arreach['value'], $arreach['vless'],\r
+                                 $currkey, $currval))\r
+        { $ok = false; break; }\r
+\r
+      if ($ok)\r
+        $attr2 .= ' '.$arreach['whole']; # it passed them\r
+    } # if !is_array($current)\r
+  } # foreach\r
+\r
+# Remove any "<" or ">" characters\r
+\r
+  $attr2 = preg_replace('/[<>]/', '', $attr2);\r
+\r
+  return "<$element$attr2$xhtml_slash>";\r
+} # function kses_attr\r
+\r
+\r
+function kses_hair($attr, $allowed_protocols)\r
+###############################################################################\r
+# This function does a lot of work. It parses an attribute list into an array\r
+# with attribute data, and tries to do the right thing even if it gets weird\r
+# input. It will add quotes around attribute values that don't have any quotes\r
+# or apostrophes around them, to make it easier to produce HTML code that will\r
+# conform to W3C's HTML specification. It will also remove bad URL protocols\r
+# from attribute values.\r
+###############################################################################\r
+{\r
+  $attrarr = array();\r
+  $mode = 0;\r
+  $attrname = '';\r
+\r
+# Loop through the whole attribute list\r
+\r
+  while (strlen($attr) != 0)\r
+  {\r
+    $working = 0; # Was the last operation successful?\r
+\r
+    switch ($mode)\r
+    {\r
+      case 0: # attribute name, href for instance\r
+\r
+        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))\r
+        {\r
+          $attrname = $match[1];\r
+          $working = $mode = 1;\r
+          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);\r
+        }\r
+\r
+        break;\r
+\r
+      case 1: # equals sign or valueless ("selected")\r
+\r
+        if (preg_match('/^\s*=\s*/', $attr)) # equals sign\r
+        {\r
+          $working = 1; $mode = 2;\r
+          $attr = preg_replace('/^\s*=\s*/', '', $attr);\r
+          break;\r
+        }\r
+\r
+        if (preg_match('/^\s+/', $attr)) # valueless\r
+        {\r
+          $working = 1; $mode = 0;\r
+          $attrarr[] = array\r
+                        ('name'  => $attrname,\r
+                         'value' => '',\r
+                         'whole' => $attrname,\r
+                         'vless' => 'y');\r
+          $attr = preg_replace('/^\s+/', '', $attr);\r
+        }\r
+\r
+        break;\r
+\r
+      case 2: # attribute value, a URL after href= for instance\r
+\r
+        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))\r
+         # "value"\r
+        {\r
+          $thisval = kses_bad_protocol($match[1], $allowed_protocols);\r
+\r
+          $attrarr[] = array\r
+                        ('name'  => $attrname,\r
+                         'value' => $thisval,\r
+                         'whole' => "$attrname=\"$thisval\"",\r
+                         'vless' => 'n');\r
+          $working = 1; $mode = 0;\r
+          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);\r
+          break;\r
+        }\r
+\r
+        if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))\r
+         # 'value'\r
+        {\r
+          $thisval = kses_bad_protocol($match[1], $allowed_protocols);\r
+\r
+          $attrarr[] = array\r
+                        ('name'  => $attrname,\r
+                         'value' => $thisval,\r
+                         'whole' => "$attrname='$thisval'",\r
+                         'vless' => 'n');\r
+          $working = 1; $mode = 0;\r
+          $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);\r
+          break;\r
+        }\r
+\r
+        if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))\r
+         # value\r
+        {\r
+          $thisval = kses_bad_protocol($match[1], $allowed_protocols);\r
+\r
+          $attrarr[] = array\r
+                        ('name'  => $attrname,\r
+                         'value' => $thisval,\r
+                         'whole' => "$attrname=\"$thisval\"",\r
+                         'vless' => 'n');\r
+                         # We add quotes to conform to W3C's HTML spec.\r
+          $working = 1; $mode = 0;\r
+          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);\r
+        }\r
+\r
+        break;\r
+    } # switch\r
+\r
+    if ($working == 0) # not well formed, remove and try again\r
+    {\r
+      $attr = kses_html_error($attr);\r
+      $mode = 0;\r
+    }\r
+  } # while\r
+\r
+  if ($mode == 1)\r
+  # special case, for when the attribute list ends with a valueless\r
+  # attribute like "selected"\r
+    $attrarr[] = array\r
+                  ('name'  => $attrname,\r
+                   'value' => '',\r
+                   'whole' => $attrname,\r
+                   'vless' => 'y');\r
+\r
+  return $attrarr;\r
+} # function kses_hair\r
+\r
+\r
+function kses_check_attr_val($value, $vless, $checkname, $checkvalue)\r
+###############################################################################\r
+# This function performs different checks for attribute values. The currently\r
+# implemented checks are "maxlen", "minlen", "maxval", "minval" and "valueless"\r
+# with even more checks to come soon.\r
+###############################################################################\r
+{\r
+  $ok = true;\r
+\r
+  switch (strtolower($checkname))\r
+  {\r
+    case 'maxlen':\r
+    # The maxlen check makes sure that the attribute value has a length not\r
+    # greater than the given value. This can be used to avoid Buffer Overflows\r
+    # in WWW clients and various Internet servers.\r
+\r
+      if (strlen($value) > $checkvalue)\r
+        $ok = false;\r
+      break;\r
+\r
+    case 'minlen':\r
+    # The minlen check makes sure that the attribute value has a length not\r
+    # smaller than the given value.\r
+\r
+      if (strlen($value) < $checkvalue)\r
+        $ok = false;\r
+      break;\r
+\r
+    case 'maxval':\r
+    # The maxval check does two things: it checks that the attribute value is\r
+    # an integer from 0 and up, without an excessive amount of zeroes or\r
+    # whitespace (to avoid Buffer Overflows). It also checks that the attribute\r
+    # value is not greater than the given value.\r
+    # This check can be used to avoid Denial of Service attacks.\r
+\r
+      if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))\r
+        $ok = false;\r
+      if ($value > $checkvalue)\r
+        $ok = false;\r
+      break;\r
+\r
+    case 'minval':\r
+    # The minval check checks that the attribute value is a positive integer,\r
+    # and that it is not smaller than the given value.\r
+\r
+      if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))\r
+        $ok = false;\r
+      if ($value < $checkvalue)\r
+        $ok = false;\r
+      break;\r
+\r
+    case 'valueless':\r
+    # The valueless check checks if the attribute has a value\r
+    # (like <a href="blah">) or not (<option selected>). If the given value\r
+    # is a "y" or a "Y", the attribute must not have a value.\r
+    # If the given value is an "n" or an "N", the attribute must have one.\r
+\r
+      if (strtolower($checkvalue) != $vless)\r
+        $ok = false;\r
+      break;\r
+  } # switch\r
+\r
+  return $ok;\r
+} # function kses_check_attr_val\r
+\r
+\r
+function kses_bad_protocol($string, $allowed_protocols)\r
+###############################################################################\r
+# This function removes all non-allowed protocols from the beginning of\r
+# $string. It ignores whitespace and the case of the letters, and it does\r
+# understand HTML entities. It does its work in a while loop, so it won't be\r
+# fooled by a string like "javascript:javascript:alert(57)".\r
+###############################################################################\r
+{\r
+  $string = kses_no_null($string);\r
+  $string2 = $string.'a';\r
+  while ($string != $string2)\r
+  {\r
+    $string2 = $string;\r
+    $string = kses_bad_protocol_once($string, $allowed_protocols);\r
+  } # while\r
+\r
+  return $string;\r
+} # function kses_bad_protocol\r
+\r
+\r
+function kses_no_null($string)\r
+###############################################################################\r
+# This function removes any NULL or chr(173) characters in $string.\r
+###############################################################################\r
+{\r
+  $string = preg_replace('/\0+/', '', $string);\r
+  $string = preg_replace('/(\\\\0)+/', '', $string);\r
+\r
+  $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"\r
+\r
+  return $string;\r
+} # function kses_no_null\r
+\r
+\r
+function kses_stripslashes($string)\r
+###############################################################################\r
+# This function changes the character sequence  \"  to just  "\r
+# It leaves all other slashes alone. It's really weird, but the quoting from\r
+# preg_replace(//e) seems to require this.\r
+###############################################################################\r
+{\r
+  return preg_replace('%\\\\"%', '"', $string);\r
+} # function kses_stripslashes\r
+\r
+\r
+function kses_array_lc($inarray)\r
+###############################################################################\r
+# This function goes through an array, and changes the keys to all lower case.\r
+###############################################################################\r
+{\r
+  $outarray = array();\r
+\r
+  foreach ($inarray as $inkey => $inval)\r
+  {\r
+    $outkey = strtolower($inkey);\r
+    $outarray[$outkey] = array();\r
+\r
+    foreach ($inval as $inkey2 => $inval2)\r
+    {\r
+      $outkey2 = strtolower($inkey2);\r
+      $outarray[$outkey][$outkey2] = $inval2;\r
+    } # foreach $inval\r
+  } # foreach $inarray\r
+\r
+  return $outarray;\r
+} # function kses_array_lc\r
+\r
+\r
+function kses_js_entities($string)\r
+###############################################################################\r
+# This function removes the HTML JavaScript entities found in early versions of\r
+# Netscape 4.\r
+###############################################################################\r
+{\r
+  return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);\r
+} # function kses_js_entities\r
+\r
+\r
+function kses_html_error($string)\r
+###############################################################################\r
+# This function deals with parsing errors in kses_hair(). The general plan is\r
+# to remove everything to and including some whitespace, but it deals with\r
+# quotes and apostrophes as well.\r
+###############################################################################\r
+{\r
+  return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);\r
+} # function kses_html_error\r
+\r
+\r
+function kses_bad_protocol_once($string, $allowed_protocols)\r
+###############################################################################\r
+# This function searches for URL protocols at the beginning of $string, while\r
+# handling whitespace and HTML entities.\r
+###############################################################################\r
+{\r
+  return preg_replace('/^((&[^;]*;|[\sA-Za-z0-9])*)'.\r
+                      '(:|&#58;|&#[Xx]3[Aa];)\s*/e',\r
+                      'kses_bad_protocol_once2("\\1", $allowed_protocols)',\r
+                      $string);\r
+} # function kses_bad_protocol_once\r
+\r
+\r
+function kses_bad_protocol_once2($string, $allowed_protocols)\r
+###############################################################################\r
+# This function processes URL protocols, checks to see if they're in the white-\r
+# list or not, and returns different data depending on the answer.\r
+###############################################################################\r
+{\r
+  $string2 = kses_decode_entities($string);\r
+  $string2 = preg_replace('/\s/', '', $string2);\r
+  $string2 = kses_no_null($string2);\r
+  $string2 = strtolower($string2);\r
+\r
+  $allowed = false;\r
+  foreach ($allowed_protocols as $one_protocol)\r
+    if (strtolower($one_protocol) == $string2)\r
+    {\r
+      $allowed = true;\r
+      break;\r
+    }\r
+\r
+  if ($allowed)\r
+    return "$string2:";\r
+  else\r
+    return '';\r
+} # function kses_bad_protocol_once2\r
+\r
+\r
+function kses_normalize_entities($string)\r
+###############################################################################\r
+# This function normalizes HTML entities. It will convert "AT&T" to the correct\r
+# "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.\r
+###############################################################################\r
+{\r
+# Disarm all entities by converting & to &amp;\r
+\r
+  $string = str_replace('&', '&amp;', $string);\r
+\r
+# Change back the allowed entities in our entity whitelist\r
+\r
+  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',\r
+                         '&\\1;', $string);\r
+  $string = preg_replace('/&amp;#0*([0-9]{1,5});/e',\r
+                         'kses_normalize_entities2("\\1")', $string);\r
+  $string = preg_replace('/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',\r
+                         '&#\\1\\2;', $string);\r
+\r
+  return $string;\r
+} # function kses_normalize_entities\r
+\r
+\r
+function kses_normalize_entities2($i)\r
+###############################################################################\r
+# This function helps kses_normalize_entities() to only accept 16 bit values\r
+# and nothing more for &#number; entities.\r
+###############################################################################\r
+{\r
+  return (($i > 65535) ? "&amp;#$i;" : "&#$i;");\r
+} # function kses_normalize_entities2\r
+\r
+\r
+function kses_decode_entities($string)\r
+###############################################################################\r
+# This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't\r
+# do anything with other entities like &auml;, but we don't need them in the\r
+# URL protocol whitelisting system anyway.\r
+###############################################################################\r
+{\r
+  $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);\r
+  $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))',\r
+                         $string);\r
+\r
+  return $string;\r
+} # function kses_decode_entities\r
+\r
+?>\r
index cb848263a33ea6373f9aea3ec1dbd5262ffc3f60..a444478aa0f435074a6c95e53ba8b96eeb801bee 100644 (file)
@@ -744,22 +744,68 @@ function clean_text($text, $format=FORMAT_MOODLE) {
         /// Remove tags that are not allowed
             $text = strip_tags($text, $ALLOWED_TAGS);
 
-        /// Munge javascript: label
-            $text = str_ireplace("javascript:", "Xjavascript:", $text);
-            $text = str_ireplace("vbscript:", "Xvbscript:", $text);
-
         /// Remove script events
             $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
             $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
 
-        /// Remove Javascript entities
-            $text = eregi_replace('&\{([^};]*)\};', '\1', $text);
+               /// Clean up embedded scripts and , using kses
+            $text = cleanAttributes($text);
 
             return $text;
     }
 }
 
 
+function cleanAttributes($str){
+///  This function takes a string and examines it for html tags.
+///  If tags are detected it passes the string to a helper function cleanAttributes2
+///  which checks for attributes and filters them for malicious content
+///                    17/08/2004                              ::                      Eamon DOT Costello AT dcu DOT ie
+    $result = preg_replace(
+            '%(<[^>]*(>|$)|>)%me', #search for html tags
+            "cleanAttributes2('\\1')", 
+            $str
+            );   
+    return  $result;
+} 
+
+               
+function cleanAttributes2($htmlTag){
+    ///  This function takes a string with an html tag and strips out any unallowed
+    ///  protocols e.g. javascript:
+    ///  It calls ancillary functions in kses which are prefixed by kses
+    ///                        17/08/2004                              ::                      Eamon DOT Costello AT dcu DOT ie
+
+    global $CFG;
+       require_once("$CFG->libdir/kses.php");
+
+    $htmlTag = kses_stripslashes($htmlTag);
+    if (substr($htmlTag, 0, 1) != '<'){
+        return '&gt;';  //a single character ">" detected
+    }
+    if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)){
+        return ''; // It's seriously malformed 
+    }  
+    $slash = trim($matches[1]); //trailing xhtml slash
+    $elem = $matches[2];       //the element name
+    $attrlist = $matches[3]; // the list of attributes as a string
+
+    $allowed_protocols = array('http', 'https', 'ftp', 'news', 'mailto');
+    $attrArray =  kses_hair($attrlist, $allowed_protocols) ;
+
+    $attStr = '';  
+    foreach ($attrArray as $arreach)
+    {
+        $attStr .=  ' '.strtolower($arreach['name']).'="'.strtolower($arreach['value']).'" ';
+    }
+    $xhtml_slash = '';
+    if (preg_match('%/\s*$%', $attrlist)){
+        $xhtml_slash = ' /'; 
+    }
+    return "<$slash$elem$attStr$xhtml_slash>";
+}
+
+
 function replace_smilies(&$text) {
 /// Replaces all known smileys in the text with image equivalents
     global $CFG;