Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is $_SERVER['QUERY_STRING'] safe from XSS?

Tags:

http

php

xss

I need to construct a form who's action takes you back to the exact same page - GET parameters included. I'm thinking I can say something to the effect of:

echo '<form action="'.$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'].
     '" method="post">'

This seems to work, and testing passing a couple XSS attacks seems to be successful, as the output of QUERY_STRING seems to be URL encoded. However the PHP documentation does not mention this, so I'm not confident I can trust this behavior.

Is it safe to use QUERY_STRING the way I am above? If not, what can I do instead? References to documentation would be appreciated.

Update switched to SCRIPT_NAME, just mixed up which one was ok and which was bad in my head, thanks for catching me. action="" does resolve my specific issue nicely, but I'm still curious if QUERY_STRING is pre-processed so it is safe to use or not, since there are other times you might want to re-use the query string, assuming it's safe to do so.

like image 677
dimo414 Avatar asked Jan 03 '11 03:01

dimo414


People also ask

Is$_ SERVER safe?

This is called a "tainted" variable, and is unsafe. When using $_SERVER , many of the variables can be controlled. PHP_SELF , HTTP_USER_AGENT , HTTP_X_FORWARDED_FOR , HTTP_ACCEPT_LANGUAGE and many others are a part of the HTTP request header sent by the client.

What is $_ server Query_string?

$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string. $_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request.


2 Answers

You should never trust $_SERVER['QUERY_STRING'] as it can be used for XSS attacks.

In your case, one could exploit the vulnerability with:

http://your.server.com/your_script.php?"><script>alert(111);</script>

Note that the code above works on IE; FireFox and Chrome efficiently encode the query string before sending it to the web server.

I would always wrap it with htmlentities (mind the double_encode parameter) as with every user input.

Good luck!

like image 164
dimi Avatar answered Oct 29 '22 00:10

dimi


If it's exploitable by XSS, first you need to know which attack. In the code posted here there is just one simple attack using the PHP_SELF.

But, to avoid any problem you could just leave the form action in blank. This will send the form to the same page including the query string.

like image 38
Keyne Viana Avatar answered Oct 29 '22 00:10

Keyne Viana