Creating a Zend Framework XSS Filter that uses HTML Purifier

Written by James Mansson on December 4, 2013 Categories: XSS, Zend Framework 1

When developing a website or web application, it is important to guard against cross-site scripting (XSS) attacks. While it is possible to develop your own filter mechanism, it is a more practical (and usually more effective) approach to make use of one of the filters libraries already out there. One such library – mentioned and recommended in the Zend Framework 1 documentation – is HTML Purifier. To quote from the front page of the website:

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C’s specifications. Tired of using BBCode due to the current landscape of deficient or insecure HTML filters? Have a WYSIWYG editor but never been able to use it? Looking for high-quality, standards-compliant, open-source components for that application you’re building? HTML Purifier is for you!

It is a simple matter to integrate the library with Zend Framework 1. The basic steps are as follows:

  1. Download the latest version of the library from the HTML Purifier website.
  2. Copy the code from the library directory in the distribution to library/htmlpurifier. This should make the library accessible assuming the include path has the library directory in it, which it usually does.
  3. Create a Zend_Filter class to make use of the library.

The following code shows how the filter class might be implemented:

<?php
require_once 'htmlpurifier/HTMLPurifier.auto.php';

class Application_Model_Filter_HtmlPurifier implements Zend_Filter_Interface
{
    /**
     * The HTML Purifer object
     *
     * @var HTMLPurifier
     */
    private $purifier;

    /**
     * Initialise the HTML Purifier object.
     */
    function __construct()
    {
        $config = HTMLPurifier_Config::createDefault();
        $this->purifier = new HTMLPurifier($config);
    }

    /**
     * Filter the value using HTML Purifier.
     *
     * @param string $value The value to filter
     * @see Zend_Filter_Interface::filter()
     */
    public function filter($value)
    {
        return $this->purifier->purify($value);
    }
}

One hand use of this class is in conjunction with Zend_Form. You can add this filter to the elements of the form that require protection against XSS attacks.

No Comments on Creating a Zend Framework XSS Filter that uses HTML Purifier

Leave a Reply

Your email address will not be published. Required fields are marked *