Prevent XSS[Cross-Site Scripting] Attacks

Cross site scripting (also known as XSS) occurs when a web application gathers malicious data from a user.

Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool a user (Read below for further details) in order to gather data from them

Persistent Attack Example

<script>document.location=’http://www.google.com/'</script>

Non-Persistent Attack Example

http://portal.example/index.php?sessionid=12312312&username=<script>document.location=’http://google.com'</script>

DOM-based Attack Example

http://www.vulnerable.site/welcome.html?name=<script>alert(document.cookie)</script>

XSS is different from, but similar in spirit to SQL injection. SQL injection is where SQL commands are not cleaned from inputs and thus able to do malicious things to a database. Using HTTPS cannot help with either XSS or SQL injection. HTTPS only protects data in transit over networks.

Best way to solve XSS is filter your input variable.For SQL injection,you should use mysql_real_escape_string to prevent sql injection.

Using apache htaccess XSS Protection,sounds like scary but once it done,you would not worry about any code…

Just add these to your .htaccess file and modify to suitable…

# redirect from non www. domain to www. to prevent duplicate listings for SEO

RewriteEngine On

RewriteCond %{HTTP_HOST} ^yoursite\.com$ [NC]

RewriteRule ^(.*)$ http://www.yoursite.com/$1 [R=301,L]

# Anti XSS protection

Options +FollowSymLinks

RewriteEngine On

RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]

RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]

RewriteCond %{QUERY_STRING} (\<|%3C).*iframe.*(\>|%3E) [NC,OR]

RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]

RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})

RewriteRule ^(.*)$ index_error.php [F,L]

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)

RewriteRule .* – [F]

# Anti cross site tracing – protection

RewriteEngine On

RewriteCond %{REQUEST_METHOD} ^TRACE

RewriteRule .* – [F]

# prevent image theft / hotlinking

RewriteEngine on

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://(www\.)?yoursite.com.com/.*$ [NC]

RewriteCond %{HTTP_USER_AGENT} !(googlebot-image|msnbot|psbot|yahoo-mmcrawler|cavalla_bot) [NC]

RewriteRule \.(gif|jpg)$ – [F]

About the Author