Validating HTML with tidy

Author Michael Tougeron on January 15, 2009

Posted under PHP, Security, Tips & Tricks, Web Development and tagged with , , , , ,

If you ever have to do HTML validation or parsing in PHP the tidy extension is the way to do it! This extension lets you use the abilities of tidy in some pretty powerful ways. The extension, written by John Coggeshall, has been around for several years now. I can see how if someone just took a quick glance at it they could think it was nice, but not really something they need. How wrong they would be! If you take a few minutes and look under the hood, tidy is an extremely powerful tool. Not only can it format html to standards (what most people use it for), it can also be a powerful parser and validation tool.

When I’m dealing with user inputted data where I want to allow HTML I have two concerns. First, I don’t want to allow XSS (some xml parsers think <p kkk=”></p>” closes the <p> tag). Second, the user frequently enters invalid html (e.g., doesn’t close the <a> tag). Fortunately tidy can easily deal with both. The second issue is the easiest to solve by running tidy->cleanRepair() on the html. The first is taken care of by looping through the tidy nodes and rebuilding the html using a whitelist. More about how to do this after the break.

To start, you’ll need to setup your tidy options. I tend to use the following options. The word-2000 option is great because it strips out all of the annoying html, css, etc. that Microsoft Word inserts for its formatting.

  1. span class=”st0″>’indent’‘output-xhtml’‘wrap’ => 0,
  2.   ‘fix-uri’‘word-2000’‘show-body-only’‘drop-proprietary-attributes’‘ncr’‘drop-empty-paras’‘hide-endtags’‘lower-literals’‘markup’‘quote-ampersand’‘force-output’

Add/Remove these options as it works best for you. I’ve found that these work best for the cleaning & repairing of accidentally invalid HTML. Read the tidy docs for what each of these mean and how they affect what tidy does. Please note that in the above options I include “force-output” so that I can display back to the user what the results of trying to fix the HTML is so that they can fix their input.

If you’re parsing user generated content, usually they are just entering the tags and HTML for the specific content they want posted. This means you’ll need to wrap that input in the <!DOCTYPE>, <HTML> and <BODY> tags before processing it through tidy.

  1. // Let’s initialize tidy with our HTML and config options.
  2. // Not let’s clean &amp; repair to try and "fix" user errors
  3. $tidy->cleanRepair();
  4. // Start tracking any errors at this point so we can give good feedback to the user
  5. "\n"// Once tidy has cleaned &amp; repaired the initial user input
  6. // we need to loop through the object and validate each
  7. // HTML tag block.  We will only need to do that though if
  8. // the $body actually has child tags
  9. // we need to validate each HTML tag in the <body>
  10.   // validateTidyNode() will be called recursively for
  11.   // any sub-tag blocks
  12. // And of course track the errors as they
  13.     // appear to give good feedback to the user
  14. ‘html’‘errors’// If the node is text, just add the text to the HTML
  15. // If the node does not exist in your array of acceptable HTML tags
  16.   // then track and error message and set the $bad_tag flag.
  17. ‘Tag: ‘‘ is not allowed and has been removed.’// I prefer to "display" the bad HTML tags so that the
  18. // user can see that it was not accepted.  But you
  19. // may prefer to just strip the tag.
  20. //    $html .= ‘ ‘;
  21.     $html .= ‘&amp;lt;’‘<‘// verify that the tag is allowed to have the specified attribute.
  22. ‘attribs’]) ) {
  23.           $errors[] = ‘Tag ‘‘ is not allowed to have the attribute ‘‘ and has been removed.’// validate the attribute’s value.  We don’t want invalid values.
  24. ‘remove’] ) {
  25.             $html .= ‘ ‘ . $res[‘attrib_name’] . ‘="’ . $res[‘attrib_value’] . ‘"’‘errors’] ) {
  26.             $errors[] = $res[‘errors’// check to make sure that required attributes are set.  e.g. <img> needs to have the src attribute
  27. ‘attribs’‘attribs’‘required’‘Tag ‘‘ is required to have the attribute ‘‘.’;
  28.         }
  29.       }
  30.     }
  32. // some tags require at least one of a set of attributes.  e.g. <a> needs to have either the href or name attribute.
  33. ‘required_attribs’‘required_attribs’‘Tag ‘‘ is required to have one of the following attributes: ‘‘, ‘‘required_attribs’]) . ‘.’‘settings’‘settings’][‘require_close’] ) {
  34.     $html .= ‘ /’//   $html .= ‘ ‘;
  35.     $html .= ‘&amp;gt;’‘>’‘settings’][‘require_close’‘&amp;lt;/’‘&amp;gt;’‘</’‘>’// set to the unmodified version first.  if modified, it will change at the end of the method.
  36.   $res[‘attrib_name’‘attrib_value’"$tag_name could not be found.  Invalid tag/attribute."‘attribs’][‘unlimited_attribs’] ) {
  37.     $res[‘valid’‘attribs’‘type’] ) {
  38. // no restrictions on the value of the attributes (not normally recommended)
  39. ‘unrestricted’// the attribute can only have one of the defined values
  40. ‘fixed’‘values’]) ) {
  41.         $res[‘errors’] = "$attrib_name is not set to an accepted value for $tag_name tag."// some basic numeric checks
  42. ‘numeric’‘px’‘percent’‘max’] ) {
  43.         $res[‘errors’] = "$attrib_name is greater than the max value (" . $attrib[‘max’] . ") allowed for $tag_name tag."‘min’] ) {
  44.         $res[‘errors’] = "$attrib_name is less than the max value (" . $attrib[‘min’] . ") allowed for $tag_name tag."‘type’] == ‘percent’"%"‘type’] == ‘px’"px"‘hex’:
  45.       // 6 characters of A-F and 0-9
  46.       // optionally allow a # in front for a total
  47.       // of 7 characters
  48. ‘url’:
  49.       // validate according to your valid URL criteria
  50.       // e.g., only allow for current domain or if the
  51.       // tag is "img" make sure the extension is .jpg or .gif
  52. ‘string’:
  53.       // validate for a string.  I usually consider _-. and similar
  54.       // characters acceptable for a "string" even though they are
  55.       // not truly a string
  56. ‘errors’] = "ERROR!  Do not know how to process the tag $tag_name!"‘attrib_name’‘attrib_value’‘valid’

So how you setup the array for tag validation is pretty much up to you. The format I used looks a lot like this:

  1. span class=”st0″>’a’‘settings’‘require_close’‘attribs’‘href’‘type’ => ‘url’),
  2.                                                 ‘name’‘type’ => ‘string’),
  3.                                                 ‘id’‘type’ => ‘string’,
  4.                                                                   ‘auth_level’‘class’‘type’ => ‘unrestricted’,
  5.                                                                   ‘auth_level’‘onclick’‘type’ => ‘unrestricted’,
  6.                                                                   ‘auth_level’‘onmouseover’‘type’ => ‘unrestricted’,
  7.                                                                   ‘auth_level’‘required_attribs’‘href’, ‘name’ )
  8.                         ),
  9.             ‘b’‘settings’‘require_close’‘img’‘settings’‘require_close’‘attribs’‘src’‘type’ => ‘url’,
  10.                                                                         ‘required’‘alt’‘type’ => ‘string’),
  11.                                                         ‘border’‘type’ => ‘numeric’,
  12.                                                                             ‘min’ => 0,
  13.                                                                             ‘max’ => 5
  14.                                                                          ),
  15.                                                         ‘align’‘type’ => ‘fixed’,
  16.                                                                             ‘values’‘center’,
  17.                                                                                                 ‘left’,
  18.                                                                                                 ‘right’
  19.                                                                                             )
  20.                                                                         ),
  21.                                                         ‘height’‘type’ => ‘numeric’,
  22.                                                                             ‘min’ => 1,
  23.                                                                             ‘max’ => 2048
  24.                                                                          ),
  25.                                                         ‘width’‘type’ => ‘numeric’,
  26.                                                                             ‘min’ => 1,
  27.                                                                             ‘max’ => 2048
  28.                                                                          ),
  29.                                                         ‘title’‘type’=>‘string’),
  30.                                                         ‘hspace’‘type’ => ‘numeric’,
  31.                                                                             ‘min’ => 0,
  32.                                                                             ‘max’ => 10
  33.                                                                          ),
  34.                                                         ‘vspace’‘type’ => ‘numeric’,
  35.                                                                             ‘min’ => 0,
  36.                                                                             ‘max’ => 10
  37.                                                                          ),
  38.                                                         ‘id’‘type’ => ‘string’,
  39.                                                                           ‘auth_level’‘class’‘type’ => ‘unrestricted’,
  40.                                                                           ‘auth_level’‘onclick’‘type’ => ‘unrestricted’,
  41.                                                                           ‘auth_level’‘onmouseover’‘type’ => ‘unrestricted’,
  42.                                                                           ‘auth_level’

The auth_level is a filter that I have in place to only allow users with a certain amount of access, such as internal staff, to use that attribute. As you probably already know, attributes like onmouseover are an easy gateway to XSS exploits. As you add new elements to the tag rule definition you just need to update the validate function in order to validate against it.

You may have noticed that I’m using the deprecated HTML attributes instead of putting all of this in a “style” attribute. I’ve found that most users don’t know CSS styles and are familiar with the old-style HTML attributes. If you force your users to use styles you’ll have whole other validation routine to ensure exploits are not in the CSS.

Note: Please don’t just copy/paste this code into your code and use it. I’m quite positive there are bugs and typos all throughout. Oh, and no, this is not the code used by the sites I work on. It is similar but definitely not the same. 😛

Posted under PHP, Security, Tips & Tricks, Web Development

This post was written by Michael Tougeron on January 15, 2009

Tags: , , , , ,

1 Comment so far

  1. Michael Tougeron February 25, 2009 7:38 am

    I gave a talk about this topic to the GBA LAMP meetup:

Leave a Comment

You must be logged in to post a comment.

More Blog Posts