I need to protect my web application against xss attacks via URL. what is the best way to do this? the application is huge, so I can not edit each of the actions, need something general.
Examples:
for all actions in same just add a event handle to onBeginRequest:
$this->attachEventHandler('onBeginRequest', [$this, 'purifyParams']);
public function purifyParams($event)
{
$userAgent = $this->getRequest()->getUserAgent();
$isIE = preg_match('/(msie)[ \/]([\w.]+)/i', $userAgent, $version);
if (!empty($isIE) && (int) $version[2] < 11) {
$purifier = new CHtmlPurifier();
$_GET = array_map(function ($param) use ($purifier) {
return $purifier->purify($param);
}, $_GET);
}
}
If you aim to manipulate your actions before handle them you can use beforeAction in your controller/component, with something like this:
protected function beforeAction($action) {
#check a preg_match on a url sanitization pattern, like "[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]", for instance
return parent::beforeAction($action);
}
This articles shows how you can make your application secure with SQL Injections, XSS Attacks and CSRF.
Hope it helps you.
Firstly, you can use regular expressions to validate your inputs, you can generalize your inputs in some regular expresions, something like this:
$num = $_GET["index"];
if (preg_match("^\d{2}$", $num)) {
//allowed
} else {
//not allowed
}
Also you can create a white list or black list, if your inputs can be grouped into what is allowed in your application, use a white list, otherwise use a black list. This lists can be sotored in your database or files, something you can easily upgrade without affecting your application. You just have to compare your inputs with that list before proccesing your inputs.
My last recommendation is encoding, you should encode your inputs and outputs, because your data from database can contain malicious code, maybe someone put it by mistake or mischief, always think in all possibilities. For this case, I remember the functions htmlspecialchars
and utf8_encode
, I think you should the first function, also you can analyze your inputs and build your own encoding function.
I share the following links:
I hope this information helps you.
Good Luck.