Skip to content

Instantly share code, notes, and snippets.

@soaj1664
Created October 7, 2014 07:18
Show Gist options
  • Save soaj1664/c5c19d73202da349925a to your computer and use it in GitHub Desktop.
Save soaj1664/c5c19d73202da349925a to your computer and use it in GitHub Desktop.
ScriptContextCleaner Function
<!--
/**
* 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);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment