CNIT 129S: Securing
Web Applications
Ch 12: Attacking Users
:

Cross-Site Scripting (XSS)
Updated 4-13-22
Attacking Clients
• Vulnerabilities in browser
s

• May result in session hijacking,
unauthorized actions, and disclosure of
personal data, keylogging, remote code
executio
n

• XSS is the most prevalent web
application vulnerability in the world
Varieties of XSS
• Re
fl
ected XS
S

• Stored XS
S

• DOM-Based XSS
Re
fl
ected XSS
• Example: an error message that takes text from
user and displays it back to the user in its
respons
e

• 75% of all XSS vulnerabilities are this type
URL with data
Re
fl
ected XSS
R
e
q
u
e
s
t
w
i
t
h
d
a
t
a
R
e
s
p
o
n
s
e
Cod
e

Execution
Persistent Cookies
• If user has a persistent cookie, implementing
"remember me
"

• Step 1 is not neede
d

• User need not be currently logged in
Same-Origin Policy
• evil.com cannot get your target.com cookies
from your browse
r

• Only a page in the same domain (target.com
)

• But XSS lets the attacker add scripting to a page
that comes from target.co
m

• Hence the name Cross-Site Scripting
Stored XSS Vulnerabilities
• A message is store
d

• Executed on any user who views i
t

• May attack a large number of users
D
a
t
a
Stored XSS
R
e
q
u
e
s
t
R
e
s
p
o
n
s
e
Cod
e

Execution
DOM-Based XSS
DOM-Based XSS
Request
Response with data
Data stored
on pag
e

used
elsewhere
on pag
e

Code
Execution
The Vulnerability
• Client-side JavaScript can access the browser's
Document Object Mode
l

• Can determine the URL used to load the current
pag
e

• A script the developer put there may extract
data from the URL and display it, dynamically
updating the page's contents
Example: Dynamically
Generated Error Message
• Writes message to pag
e

• Can also write script to page
12a
Real-World XSS Attacks
Apache (2010)
• XSS in issue-tracking application
 

• Attacker injected code, obscured it with a URL
shortene
r

• Administrator clicked the lin
k

• Attacker stole the administrator's cooki
e

• Attacker altered the upload folder for the project
and placed a Trojan login form there
Apache (2010)
• Attacker captured usernames and passwords
for Apache privileged user
s

• Found passwords that were re-used on other
systems within the infrastructur
e

• Fully compromised those systems, escalating
the attack beyond the vulnerable Web
applicatio
n

• Link Ch 12a
MySpace (2005)
• Samy evaded
fi
lters intended to block
XS
S

• Added JavaScript to his user pro
fi
le, that
made every viewe
r

• Add Samy as a frien
d

• Copied the script to the user's pro
fi
l
e

• Gained over 1 million friends within hours
 

• Link Ch 12b
• Stored XSS in email allowed attackers to send a
malicious email to the CE
O

• Stealing his session cookie
Twitter (2009)
• Link Ch 12d
Other Payloads for XSS
• Virtual Defacemen
t

• Add images, code, or other content to a page
Injecting Trojan Functionality
• Inject actual working functionality into the
vulnerable applicatio
n

• Such as a fake login form to capture credential
s

• Or the fake Google purchase form on the next
slide, from 2004
Disadvantages of Session
Hijacking
• Attacker must monitor her server and collect
cookie
s

• Then carry out actions on behalf of target user
s

• Labor-intensiv
e

• Leaves traces in server logs
Inducing User Actions
• Use attack payload script to carry out actions
directl
y

• MySpace XSS worm did thi
s

• If the goal is to perform an administrative
action, each user can be forced to try it until an
administrator is compromised
Exploiting Trust Relationships
• Browsers trust JavaScript with cookies from the
same websit
e

• Autocomplete in the browser can
fi
ll in
fi
elds,
which are then read by JavaScrip
t

• Some sites require being added to Internet
Explorer's "Trusted Sites"; those sites can run
arbitrary code like this
Exploiting Trust Relationships
• ActiveX controls often contain powerful
method
s

• They may check to see that requests came
from the expected sit
e

• With XSS, that condition is satis
fi
ed
Escalating the Client-Side
Attack
• Website may attack users b
y

• Logging keystroke
s

• Capturing browsing histor
y

• Port-scanning the local network
12b
Delivery Mechanisms for
XSS Attacks
Delivering Re
fl
ected and
DOM-Based XSS Attacks
• Phishing email containing a crafted UR
L

• Targeted attack with custom emai
l

• Instant message containing a UR
L

• Code posted on websites that allow user to post
HTML
Watering Hole Attack
• Attacker creates a website with content that will
interest the target user
s

• Use search engine optimization to attract
viewer
s

• Page contains content that causes the user's
browser to make requests containing XSS
payloads to the vulnerable application
• Purchase ad space, put malicious URL in the a
d

• The ad may appear in pages about the app
you are attacking, because of keyword
matche
s

• Web apps often have "tell a friend" or "send
feedback" feature
s

• Leverage this to deliver an XSS attack via an
email that originates from the organization's
server
Delivering Re
fl
ected and
DOM-Based XSS Attacks
Delivering Stored XSS
Attacks
• In-band (most common)
Delivering Stored XSS
Attacks
• Out-of-ban
d

• Anything other than viewing the target ap
p

• Such as email from its server
Chaining XSS
• XSS vulnerability itself may be low-ris
k

• But chaining it together with other
vulnerabilities can cause serious compromise
Example
• XSS allows script to be inserted into user's
displayed nam
e

• Access control
fl
aw lets attacker change other
users' name
s

• Add token-stealing XSS to every usernam
e

• Gain administrator credentials: total control of
application
Finding and Exploiting XSS
Vunerabilities
Basic Approach
• Inject this string into every parameter on every
page of the applicatio
n

• If the attack string appears unmodi
fi
ed in the
response, that indicates an XSS vulnerabilit
y

• This is the fastest way to
fi
nd an XSS, but it
won't
fi
nd them all
When the Simple Attack
Fails
• Applications with rudimentary blacklist-based
fi
lter
s

• Remove <script>, or < > "
/

• Crafted attacks may still work
Response Different from
Input
• XSS attacks that don't simply return the attack
strin
g

• Sometimes input string is sanitized, decoded,
or otherwise modi
fi
e
d

• In DOM-based XSS, the input string isn't
necessarily returned in the browser's
immediate response, but is retained in the
DOM and accessed via client-side JavaScript
Finding and Exploiting
Re
fl
ected XSS Vulnerabilities
Identifying Re
fl
ections of
User Input
• Choose a unique string that doesn't appear
anyhere in the application and includes only
alphabetical characters that won't be
fi
ltered,
like "myxsstestdmqlwp
"

• Submit it as every parameter, one at a time,
including GET, POST, query string, and headers
such as User-Agen
t

• Monitor responses for any appearance of the
string
Testing Re
fl
ections to
Introduce Script
• Manually test each instance of re
fl
ected input to
see if it's exploitabl
e

• You'll have to customize the attack for each
situation
Demos (Use Firefox)
Demo 5. A Tag Attribute
Value
• Here are two ways to exploit it
Demo 6. A JavaScript String
• This attack works
Demo 7. An Attribute Containing
a URL
• Use the javascript: handler to make your script
into a UR
L

• Or use the onclick event handler
Probing Defensive Filters
• Three common types
Beating Signature-Based
Filters
• You may see an error message like this
Remove Parts of the String
• Until the error goes awa
y

• Find the substring that triggered the error,
usually something like <script
>

• Test bypass methods
Ways to Introduce Script
Code
Script Tags
• If <script> is blocked, try these
Event Handlers
• All these run without user interaction
Event Handlers in HTML 5
• Autofocu
s

• In closing tag
s

• New HTML 5 tags
Script Pseudo-Protocols
• Used where a URL is expecte
d

• IE allows the vbs: protoco
l

• HTML 5 provides these new ways:
Dynamically Evaluated
Styles
• IE 7 and earlier allowed this
:

• Later IE versions allow this:
Bypassing Filters: HTML
• Ways to obfuscate this attack
Inserted NULL Butes
• Causes C code to terminate the strin
g

• Will bypass many
fi
lter
s

• IE allows NULL bytes anywher
e

• Web App Firewalls (WAFs) are typically coded in
C for performance and this trick fools them
Invalid Tags
• Browser will let it ru
n

• Filter may not see it due to invalid tag "x"
Base Tag Hijacking
• Set <base> and later relative-path URLs will be
resolved relative to it
Space Following the Tag Name
• Replace the space with other character
s

• Add extra characters when there's no space
NULL Byte in Attribute
Name
• Attribute delimiter
s

• Backtick works in IE
Attribute Delimiters
• If
fi
lter is unaware that backticks work as attribute
delimiters, it treats this as a single attribute, not
realizing that the "onerror" will execut
e

• Attack with no spaces
Attribute Values
• Insert NULL, or HTML-encode characters
HTML Encoding
• Can use decimal and hexadecimal format, add
leading zeroes, omit trailing semicolo
n

• Some browsers will accept these
Tag Brackets
• Some applications perform URL decoding twice,
so this inpu
t

• becomes this, which has no < or
>

• and it's then decoded to this
• Some app frameworks translate unusual
Unicode characters into their nearest ASCII
equivalents, so double-angle quotation marks
%u00AB and %u00BB work:
Tag Brackets
• Browsers tolerate extra bracket
s

• This strange format is accepted by Firefox,
despite not having a valid <script> tag
Tag Brackets
Web Developer Add-on
• View Generated Source shows HTML after
Firefox has tried to "
fi
x" the code
Character Sets
Telling Browser the
Character Set
• Set it in the HTTP Content-Type heade
r

• Or an HTTP META ta
g

• Or a CHARSET parameter, if one is used
Shift-JIS
• A 16-bit encoding scheme developed for Japanese
character
s

• Suppose two pieces of input are used in the app's
respons
e

• input1 blocks quotes, input2 blocks < and
>

• This attack works, because %f0 starts a two-byte
character, breaking the quotation mark
Bypassing Filters: Script
Code
JavaScript Escaping
• Unicod
e

• Eva
l

• Super
fl
uous escape characters
AtoB
• Link Ch 12i
Dynamically Constructing
Strings
• Third example works in Firefo
x

• And in other browsers too, according to link Ch
12f
Alternatives
• Alternatives to eva
l

• Alternatives to dots
Combining Multiple
Techniques
• The "e" in "alert" uses Unicode escaping:
u006
5

• The backslash is URL-encoded: &#x5c
;

• With more HTML-encoding
VBScript
• Skip this sectio
n

• Microsoft abandoned VBScript with Edg
e

• Link Ch 12g
Beating Sanitization
• Encoding certain character
s

• < becomes &lt
;

• > becomes &gt
;

• Test to see what characters are sanitize
d

• Try to make an attack string without those
characters
Examples
• Your injection may already be in a script, so you
don't need <script> ta
g

• Sneak in <script> using layers of encoding, null
bytes, nonstandard syntax, or obfuscated script
code
Mistakes in Sanitizing Code
• Not removing all instance
s

• Not acting recursively
Stages of Encoding
• Filter
fi
rst strips <script> recursivel
y

• Then strips <object> recursivel
y

• This attack succeeds
Injecting into an Event
Handler
• You control fo
o

• This attack strin
g

• Turns into this, and executes in some browsers
Beating Length Limits


1. Short Attacks
• This sends cookies to server with hostname
a

• This tag executes a script from the server with
hostname a
JavaScript Packer
• Link Ch 12h
• Use multiple injection points
 

• Inject part of the code in each poin
t

• Consider this URL
Beating Length Limits


2. Span Multiple Locations
• It returns three hidden
fi
eld
s

• Inject this way
Beating Length Limits


2. Span Multiple Locations
• Result
Beating Length Limits


2. Span Multiple Locations
• Inject this JavaScript, which evaluates the
fragment string from the UR
L

• The part after #
Beating Length Limits


3. Convert Re
fl
ected XSS to DOM
• First attack works in a straightforward manne
r

• Second one works because the URL is parsed as
JavaScrip
t

• http: is interpreted as a code label, // as a
comment, and %0A terminates the comment
Beating Length Limits


3. Convert Re
fl
ected XSS to DOM
10c

Ch 12 Attacking Users - XSS

  • 1.
    CNIT 129S: Securing WebApplications Ch 12: Attacking Users : Cross-Site Scripting (XSS) Updated 4-13-22
  • 2.
    Attacking Clients • Vulnerabilitiesin browser s • May result in session hijacking, unauthorized actions, and disclosure of personal data, keylogging, remote code executio n • XSS is the most prevalent web application vulnerability in the world
  • 3.
    Varieties of XSS •Re fl ected XS S • Stored XS S • DOM-Based XSS
  • 4.
    Re fl ected XSS • Example:an error message that takes text from user and displays it back to the user in its respons e • 75% of all XSS vulnerabilities are this type
  • 6.
    URL with data Re fl ectedXSS R e q u e s t w i t h d a t a R e s p o n s e Cod e Execution
  • 9.
    Persistent Cookies • Ifuser has a persistent cookie, implementing "remember me " • Step 1 is not neede d • User need not be currently logged in
  • 10.
    Same-Origin Policy • evil.comcannot get your target.com cookies from your browse r • Only a page in the same domain (target.com ) • But XSS lets the attacker add scripting to a page that comes from target.co m • Hence the name Cross-Site Scripting
  • 11.
    Stored XSS Vulnerabilities •A message is store d • Executed on any user who views i t • May attack a large number of users
  • 13.
  • 14.
  • 15.
    DOM-Based XSS Request Response withdata Data stored on pag e used elsewhere on pag e Code Execution
  • 16.
    The Vulnerability • Client-sideJavaScript can access the browser's Document Object Mode l • Can determine the URL used to load the current pag e • A script the developer put there may extract data from the URL and display it, dynamically updating the page's contents
  • 17.
    Example: Dynamically Generated ErrorMessage • Writes message to pag e • Can also write script to page
  • 19.
  • 20.
  • 21.
    Apache (2010) • XSSin issue-tracking application • Attacker injected code, obscured it with a URL shortene r • Administrator clicked the lin k • Attacker stole the administrator's cooki e • Attacker altered the upload folder for the project and placed a Trojan login form there
  • 22.
    Apache (2010) • Attackercaptured usernames and passwords for Apache privileged user s • Found passwords that were re-used on other systems within the infrastructur e • Fully compromised those systems, escalating the attack beyond the vulnerable Web applicatio n • Link Ch 12a
  • 23.
    MySpace (2005) • Samyevaded fi lters intended to block XS S • Added JavaScript to his user pro fi le, that made every viewe r • Add Samy as a frien d • Copied the script to the user's pro fi l e • Gained over 1 million friends within hours • Link Ch 12b
  • 24.
    • Stored XSSin email allowed attackers to send a malicious email to the CE O • Stealing his session cookie
  • 25.
  • 26.
    Other Payloads forXSS • Virtual Defacemen t • Add images, code, or other content to a page
  • 28.
    Injecting Trojan Functionality •Inject actual working functionality into the vulnerable applicatio n • Such as a fake login form to capture credential s • Or the fake Google purchase form on the next slide, from 2004
  • 30.
    Disadvantages of Session Hijacking •Attacker must monitor her server and collect cookie s • Then carry out actions on behalf of target user s • Labor-intensiv e • Leaves traces in server logs
  • 31.
    Inducing User Actions •Use attack payload script to carry out actions directl y • MySpace XSS worm did thi s • If the goal is to perform an administrative action, each user can be forced to try it until an administrator is compromised
  • 32.
    Exploiting Trust Relationships •Browsers trust JavaScript with cookies from the same websit e • Autocomplete in the browser can fi ll in fi elds, which are then read by JavaScrip t • Some sites require being added to Internet Explorer's "Trusted Sites"; those sites can run arbitrary code like this
  • 33.
    Exploiting Trust Relationships •ActiveX controls often contain powerful method s • They may check to see that requests came from the expected sit e • With XSS, that condition is satis fi ed
  • 34.
    Escalating the Client-Side Attack •Website may attack users b y • Logging keystroke s • Capturing browsing histor y • Port-scanning the local network
  • 35.
  • 36.
  • 37.
    Delivering Re fl ected and DOM-BasedXSS Attacks • Phishing email containing a crafted UR L • Targeted attack with custom emai l • Instant message containing a UR L • Code posted on websites that allow user to post HTML
  • 38.
    Watering Hole Attack •Attacker creates a website with content that will interest the target user s • Use search engine optimization to attract viewer s • Page contains content that causes the user's browser to make requests containing XSS payloads to the vulnerable application
  • 39.
    • Purchase adspace, put malicious URL in the a d • The ad may appear in pages about the app you are attacking, because of keyword matche s • Web apps often have "tell a friend" or "send feedback" feature s • Leverage this to deliver an XSS attack via an email that originates from the organization's server Delivering Re fl ected and DOM-Based XSS Attacks
  • 40.
    Delivering Stored XSS Attacks •In-band (most common)
  • 41.
    Delivering Stored XSS Attacks •Out-of-ban d • Anything other than viewing the target ap p • Such as email from its server
  • 42.
    Chaining XSS • XSSvulnerability itself may be low-ris k • But chaining it together with other vulnerabilities can cause serious compromise
  • 43.
    Example • XSS allowsscript to be inserted into user's displayed nam e • Access control fl aw lets attacker change other users' name s • Add token-stealing XSS to every usernam e • Gain administrator credentials: total control of application
  • 44.
    Finding and ExploitingXSS Vunerabilities
  • 45.
    Basic Approach • Injectthis string into every parameter on every page of the applicatio n • If the attack string appears unmodi fi ed in the response, that indicates an XSS vulnerabilit y • This is the fastest way to fi nd an XSS, but it won't fi nd them all
  • 46.
    When the SimpleAttack Fails • Applications with rudimentary blacklist-based fi lter s • Remove <script>, or < > " / • Crafted attacks may still work
  • 47.
    Response Different from Input •XSS attacks that don't simply return the attack strin g • Sometimes input string is sanitized, decoded, or otherwise modi fi e d • In DOM-based XSS, the input string isn't necessarily returned in the browser's immediate response, but is retained in the DOM and accessed via client-side JavaScript
  • 48.
  • 49.
    Identifying Re fl ections of UserInput • Choose a unique string that doesn't appear anyhere in the application and includes only alphabetical characters that won't be fi ltered, like "myxsstestdmqlwp " • Submit it as every parameter, one at a time, including GET, POST, query string, and headers such as User-Agen t • Monitor responses for any appearance of the string
  • 50.
    Testing Re fl ections to IntroduceScript • Manually test each instance of re fl ected input to see if it's exploitabl e • You'll have to customize the attack for each situation
  • 51.
  • 52.
    Demo 5. ATag Attribute Value • Here are two ways to exploit it
  • 53.
    Demo 6. AJavaScript String • This attack works
  • 54.
    Demo 7. AnAttribute Containing a URL • Use the javascript: handler to make your script into a UR L • Or use the onclick event handler
  • 55.
  • 56.
    Beating Signature-Based Filters • Youmay see an error message like this
  • 57.
    Remove Parts ofthe String • Until the error goes awa y • Find the substring that triggered the error, usually something like <script > • Test bypass methods
  • 58.
    Ways to IntroduceScript Code
  • 59.
    Script Tags • If<script> is blocked, try these
  • 61.
    Event Handlers • Allthese run without user interaction
  • 62.
    Event Handlers inHTML 5 • Autofocu s • In closing tag s • New HTML 5 tags
  • 63.
    Script Pseudo-Protocols • Usedwhere a URL is expecte d • IE allows the vbs: protoco l • HTML 5 provides these new ways:
  • 64.
    Dynamically Evaluated Styles • IE7 and earlier allowed this : • Later IE versions allow this:
  • 65.
    Bypassing Filters: HTML •Ways to obfuscate this attack
  • 66.
    Inserted NULL Butes •Causes C code to terminate the strin g • Will bypass many fi lter s • IE allows NULL bytes anywher e • Web App Firewalls (WAFs) are typically coded in C for performance and this trick fools them
  • 67.
    Invalid Tags • Browserwill let it ru n • Filter may not see it due to invalid tag "x"
  • 68.
    Base Tag Hijacking •Set <base> and later relative-path URLs will be resolved relative to it
  • 69.
    Space Following theTag Name • Replace the space with other character s • Add extra characters when there's no space
  • 70.
    NULL Byte inAttribute Name • Attribute delimiter s • Backtick works in IE
  • 71.
    Attribute Delimiters • If fi lteris unaware that backticks work as attribute delimiters, it treats this as a single attribute, not realizing that the "onerror" will execut e • Attack with no spaces
  • 72.
    Attribute Values • InsertNULL, or HTML-encode characters
  • 73.
    HTML Encoding • Canuse decimal and hexadecimal format, add leading zeroes, omit trailing semicolo n • Some browsers will accept these
  • 74.
    Tag Brackets • Someapplications perform URL decoding twice, so this inpu t • becomes this, which has no < or > • and it's then decoded to this
  • 75.
    • Some appframeworks translate unusual Unicode characters into their nearest ASCII equivalents, so double-angle quotation marks %u00AB and %u00BB work: Tag Brackets
  • 76.
    • Browsers tolerateextra bracket s • This strange format is accepted by Firefox, despite not having a valid <script> tag Tag Brackets
  • 77.
    Web Developer Add-on •View Generated Source shows HTML after Firefox has tried to " fi x" the code
  • 78.
  • 79.
    Telling Browser the CharacterSet • Set it in the HTTP Content-Type heade r • Or an HTTP META ta g • Or a CHARSET parameter, if one is used
  • 80.
    Shift-JIS • A 16-bitencoding scheme developed for Japanese character s • Suppose two pieces of input are used in the app's respons e • input1 blocks quotes, input2 blocks < and > • This attack works, because %f0 starts a two-byte character, breaking the quotation mark
  • 81.
  • 82.
    JavaScript Escaping • Unicod e •Eva l • Super fl uous escape characters
  • 83.
  • 84.
    Dynamically Constructing Strings • Thirdexample works in Firefo x • And in other browsers too, according to link Ch 12f
  • 85.
    Alternatives • Alternatives toeva l • Alternatives to dots
  • 87.
    Combining Multiple Techniques • The"e" in "alert" uses Unicode escaping: u006 5 • The backslash is URL-encoded: &#x5c ; • With more HTML-encoding
  • 88.
    VBScript • Skip thissectio n • Microsoft abandoned VBScript with Edg e • Link Ch 12g
  • 89.
    Beating Sanitization • Encodingcertain character s • < becomes &lt ; • > becomes &gt ; • Test to see what characters are sanitize d • Try to make an attack string without those characters
  • 90.
    Examples • Your injectionmay already be in a script, so you don't need <script> ta g • Sneak in <script> using layers of encoding, null bytes, nonstandard syntax, or obfuscated script code
  • 91.
    Mistakes in SanitizingCode • Not removing all instance s • Not acting recursively
  • 92.
    Stages of Encoding •Filter fi rst strips <script> recursivel y • Then strips <object> recursivel y • This attack succeeds
  • 93.
    Injecting into anEvent Handler • You control fo o • This attack strin g • Turns into this, and executes in some browsers
  • 94.
    Beating Length Limits 1.Short Attacks • This sends cookies to server with hostname a • This tag executes a script from the server with hostname a
  • 95.
  • 96.
    • Use multipleinjection points • Inject part of the code in each poin t • Consider this URL Beating Length Limits 2. Span Multiple Locations
  • 97.
    • It returnsthree hidden fi eld s • Inject this way Beating Length Limits 2. Span Multiple Locations
  • 98.
    • Result Beating LengthLimits 2. Span Multiple Locations
  • 99.
    • Inject thisJavaScript, which evaluates the fragment string from the UR L • The part after # Beating Length Limits 3. Convert Re fl ected XSS to DOM
  • 100.
    • First attackworks in a straightforward manne r • Second one works because the URL is parsed as JavaScrip t • http: is interpreted as a code label, // as a comment, and %0A terminates the comment Beating Length Limits 3. Convert Re fl ected XSS to DOM
  • 101.