XSS - Paradoxis/PHP-security-classes GitHub Wiki
XSS is a method in which an attacker is able to run arbitrary JavaScript on a vicitim's browser. Don't let the name fool you; cross site scripting happens primarily on YOUR website and targets YOUR users (or you). With XSS an attacker is able to steal sessions (which makes logging in useless), make crafted requests to any given page, create worms, and in the worst case run a browser exploit to the targeted user.
See OWASP - Cross-site Scripting (XSS) for more information.
This class fixes this vulnerability (if used correctly) by sanitizing input before it is printed out to the screen.
When using this class you'll primarily be using getPostValue()
and getGetValue()
to directly use/print user supplied data.
Usage of the XSRF class is highly advised to fully protect against XSS.
To use this class, simply include the XSS class from the repository, and initialize it.
// Include class
require_once('PHP-security-classes/src/XSS.php');
// Give the class a neat name.
use \Paradoxis\Security\XSS as XSS;
// Utter most basic usage, a shortcut for htmlspecialchars():
$myString = XSS::escape('<script>alert(document.cookie)</script>');
Retrieving user data via $_POST
, $_GET
, $_REQUEST
, $_COOKIE
and $_SERVER
variables are all risky, so we want to make this a secure and easy process. This is why these function names all have the same naming-convention and usage:
echo XSS::getPostValue('foo');
This would print the post value foo
, and returns an empty string when it is not set or included in the form submit.
You can set a default value like so:
echo XSS::getPostValue('foo', 'Default value when foo does not exist!');
This all works the same for $_POST
, $_GET
, $_REQUEST
, $_COOKIE
and $_SERVER
variables.
$get = XSS::getGetValue('foo');
$post = XSS::getPostValue('foo');
$request = XSS::getRequestValue('foo');
$cookie = XSS::getCookieValue('foo');
$server = XSS::getServerValue('foo');
Getting array / object values works pretty much the same as the above, simply call the function, with the given array, and a key to get the escaped value. You can also specify a default value if the key doesn't exist.
$myArray = array('foo' => 'bar');
$foo = XSS::getArrayValue($myArray, 'foo', 'Default value'); // Returns 'foo'
$bar = XSS::getArrayValue($myArray, 'bar'); // Returns ''
Some web developers use htmlspecialchars() to escape their user input, but forget about some crucial things:
javascript:
link injection.
Getting safe URL's with this class is easy:
<a href="<?= XSS::escapeURL('javascript:alert(document.cookie)', 'http://yoursite.com/'); ?>">Click this link for kittens!!</a>
<? # Not escaping this, would lead to the user's cookie being alerted, however in this case it would link to your 'http://yoursite.com/' ?>
Leaving the default value blank, the function will simply add http://
in front of the url, and escape it. This prevents any javascript from running on click.