Friday, May 15, 2015

PHP Functions to Mitigate against XSS and other Threats

As I was reviewing the source code of "CMS Made Simple" I found 2 functions that they loosely applied and in some circumstances had not applied it at all.  It states in their source code that the functions are MIT licensed and taken from the cakephp.org project.  I have tested and posted them below.  The following page at OWASP has some better PHP functions to utilize to sanitize input/output.

/*
 * Sanitize input to prevent against XSS and other nasty stuff.
 * Taken from cakephp (http://cakephp.org)
 * Licensed under the MIT License
 *
 * @internal
 * @param string input
 * @return string
 */
function cleanValue($val) {
        if ($val == "") {
                return $val;
        }
        //Replace odd spaces with safe ones
        $val = str_replace(" ", " ", $val);
        $val = str_replace(chr(0xCA), "", $val);
        //Encode any HTML to entities (including \n --> <br />)
        $val = cleanHtml($val);
        //Double-check special chars and remove carriage returns
        //For increased SQL security
        $val = preg_replace("/\\\$/", "$", $val);
        $val = preg_replace("/\r/", "", $val);
        $val = str_replace("!", "!", $val);
        $val = str_replace("'", "'", $val);
        //Allow unicode (?)
        $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val);
        //Add slashes for SQL
        //$val = $this->sql($val);
        //Swap user-inputted backslashes (?)
        $val = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $val);
        return $val;
}

/*
 * Method to sanitize incoming html.
 * Take from cakephp (http://cakephp.org)
 * Licensed under the MIT License
 *
 * @param string Input HTML code.
 * @param boolean Wether HTML tags should be removed.
 * @return string
 * Rolf: only used in this file
 */
function cleanHtml($string, $remove = false) {
        if ($remove) {
                $string = strip_tags($string);
        } else {
                $patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/");
                $replacements = array("&amp;", "&#37;", "&lt;", "&gt;", "&quot;", "&#39;", "&#40;", "&#41;", "&#43;", "&#45;");
                $string = preg_replace($patterns, $replacements, $string);
        }
        return $string;
}

No comments:

Post a Comment

Docker with Juiceshop - Focus on SQL Injection

In preparation for an ethical hacking class that I will be teaching, I wanted to work through a few of the Vulnhub or docker images to refr...