Skip to content

Instantly share code, notes, and snippets.

@soaj1664
Created October 7, 2014 07:18
Show Gist options
  • Select an option

  • Save soaj1664/c5c19d73202da349925a to your computer and use it in GitHub Desktop.

Select an option

Save soaj1664/c5c19d73202da349925a to your computer and use it in GitHub Desktop.

Revisions

  1. soaj1664 created this gist Oct 7, 2014.
    34 changes: 34 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    <!--
    /**
    * XSS protection function for script context only
    * @usecases
    * @double quoted JavaScript string literal case e.g.,
    * <script> var searchquery = "use this function if output reflects here"; </script>
    * @single quoted JavaScript string literal case e.g.,
    * <script> var searchquery = 'use this function if output reflects here'; </script>
    * < is filtered because an attacker can prematuraley closes the script block
    * @description
    * Sanitize/Filter meta or control characters that attacker may use to break the script context e.g.,
    * "; confirm(1); " OR '; prompt(1); // OR </script><script>alert(1)</script>
    * \ and % are filtered because they may break the page e.g., \n or %0a
    * & is sanitized because of a complex or nested context (if in use)
    * The same protection also works in JSON context ...
    * @author Ashar Javed
    * @Link https://twitter.com/soaj1664ashar
    * @demo http://xssplaygroundforfunandlearn.netai.net/final.html
    */
    -->


    <?php
    function scriptContextCleaner($input) {

    $bad_chars = array("\"", "<", "'", "\\\\", "%", "&");

    $safe_chars = array("&quot;", "&lt;", "&apos;", "&bsol;", "&percnt;", "&amp;");

    $output = str_replace($bad_chars, $safe_chars, $input);

    return stripslashes($output);
    }
    ?>