RiptideTempora

TLWSD -- Primitive XSS Filter for URLs

Jul 31st, 2012
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1. <?
  2. // REQUESTING COMMENTS AND CRITICISMS!
  3. function removeXSS($in) {
  4.   // Experimental feature. Add/remove XSS filters if new attack vectors are discovered.
  5.  
  6.   // First, grab the protocol and store it.
  7.   preg_match('/^(https|http|ftp|irc):\/\/(.*)/', $in, $matches); // Whitelist
  8.   if(empty($matches)) return null; // Not matched to a URL
  9.   $protocol = $matches[1];
  10.  
  11.   // We'll keep the rest of the string here, for filtering:
  12.   $in = $matches[2];
  13.  
  14.   /*
  15.  
  16.   // Replace what we don't want to have in a URL
  17.   $in = str_replace('&', '&amp;', $in);
  18.   $in = str_replace('\\', '\\\\', $in);
  19.   $in = str_replace('<', '&lt;', $in);
  20.   $in = str_replace('"', '&quot;', $in);
  21.   $in = str_replace(':', '&#58;', $in);
  22.   $in = str_replace("'", "\\'", $in);
  23.   $in = str_replace('>', '&gt;', $in);
  24.   $in = preg_replace('/([^\x20-\x7F]+)/', '', $in); // Remove non-ASCII chars
  25.                                                     // and whitespace!
  26.   */
  27.   $in = preg_replace_callback('/([^\x20\x25\x2E\x2F-\x39\x3F-\x5A\x5F\x61-\x7A])/', function($reg) {
  28.     return '%'.str_pad(
  29.       hexdec(ord($reg[1]), 2, '0', STR_PAD_LEFT)
  30.     );
  31.   },$in);
  32.   $in = htmlspecialchars($in, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  33.  
  34.   // You can replace this with a call to HTMLPurifier in your implementation;
  35.   // I haven't had the time to research XSS filters so I'm employing a basic one
  36.   // until my circumstances change.
  37.  
  38.   // If anyone wants to submit some XSS proof-of-concept code, I encourage you
  39.   // to publish it openly as soon as you find it and just tweet me in the public
  40.   // disclosure. Due credit will be given ;)
  41.   return $protocol.'://'.$in;
  42. }
  43. /*                                    --@RiptideTempora */
  44. ?>
Advertisement
Add Comment
Please, Sign In to add comment