Xss Cheat Sheet Github



This article is focused on providing application security testing professionals with a guide to assist in Cross Site Scripting testing. The initial contents of this article were donated to OWASP by RSnake, from his seminal XSS Cheat Sheet, which was at: http://ha.ckers.org/xss.html. That site now redirects to its new home here, where we plan to maintain and enhance it. The very first OWASP Prevention Cheat Sheet, the XSS (Cross Site Scripting) Prevention Cheat Sheet, was inspired by RSnake's XSS Cheat Sheet, so we can thank him for our inspiration. We wanted to create short, simple guidelines that developers could follow to prevent XSS, rather than simply telling developers to build apps that could protect against all the fancy tricks specified in rather complex attack cheat sheet, and so the OWASP Cheat Sheet Series was born.

  • 본 문서는 지속적으로 업데이트됩니다.Basic123456789 link.
  • Cross-site Scripting (XSS). There is an Authentication Cheat Sheet. Insecure Direct Object Reference or Forceful Browsing. There are emerging tools that can be used to track security issues in dependency sets, like automated scanning from GitHub and GitLab.

This cheat sheet is for people who already understand the basics of XSS attacks but want a deep understanding of the nuances regarding filter evasion.

Please note that most of these cross site scripting vectors have been tested in the browsers listed at the bottom of the scripts.

Here we are going to see about most important XSS Cheat Sheet. What is XSS(Cross Site Scripting)? An attacker can inject untrusted snippets of JavaScript into your application without validation. This JavaScript is then executed by the victim who is visiting the target site. XSS classified into three types and these XSS Cheat Sheet will help to find the XSS vulnerabilities for Pentesters.

XSS Locator

Inject this string, and in most cases where a script is vulnerable with no special XSS vector requirements the word 'XSS' will pop up. Use this URL encoding calculator to encode the entire string. Tip: if you're in a rush and need to quickly check a page, often times injecting the depreciated '<PLAINTEXT>' tag will be enough to check to see if something is vulnerable to XSS by messing up the output appreciably:

XSS locator 2

If you don't have much space and know there is no vulnerable JavaScript on the page, this string is a nice compact XSS injection check. View source after injecting it and look for <XSS verses &lt;XSS to see if it is vulnerable:

No Filter Evasion

This is a normal XSS JavaScript injection, and most likely to get caught but I suggest trying it first (the quotes are not required in any modern browser so they are omitted here):

Image XSS using the JavaScript directive

Image XSS using the JavaScript directive (IE7.0 doesn't support the JavaScript directive in context of an image, but it does in other contexts, but the following show the principles that would work in other tags as well:

No quotes and no semicolon

Case insensitive XSS attack vector

HTML entities

The semicolons are required for this to work:

Grave accent obfuscation

If you need to use both double and single quotes you can use a grave accent to encapsulate the JavaScript string - this is also useful because lots of cross site scripting filters don't know about grave accents:

Malformed A tags

Skip the HREF attribute and get to the meat of the XXS...Submitted by David Cross ~ Verified on Chrome

Xss injection cheat sheet

<a onmouseover='alert(document.cookie)'>xxs link</a>

orChrome loves to replace missing quotes for you... if you ever get stuck just leave them off and Chrome will put them in the right place and fix your missing quotes on a URL or script.

<a onmouseover=alert(document.cookie)>xxs link</a>

Malformed IMG tags

Originally found by Begeek (but cleaned up and shortened to work in all browsers), this XSS vector uses the relaxed rendering engine to create our XSS vector within an IMG tag that should be encapsulated within quotes. I assume this was originally meant to correct sloppy coding. This would make it significantly more difficult to correctly parse apart an HTML tag:

fromCharCode

if no quotes of any kind are allowed you can eval() a fromCharCode in JavaScript to create any XSS vector you need:

Default SRC tag to get past filters that check SRC domain

This will bypass most SRC domain filters. Inserting javascript in an event method will also apply to any HTML tag type injection that uses elements like Form, Iframe, Input, Embed etc. It will also allow any relevant event for the tag type to be substituted like onblur, onclick giving you an extensive amount of variations for many injections listed here.Submitted by David Cross.

Default SRC tag by leaving it empty

Default SRC tag by leaving it out entirely

Decimal HTML character references

all of the XSS examples that use a javascript: directive inside of an <IMG tag will not work in Firefox or Netscape 8.1+ in the Gecko rendering engine mode). Use the XSS Calculator for more information:

Decimal HTML character references without trailing semicolons

This is often effective in XSS that attempts to look for '&#XX;', since most people don't know about padding - up to 7 numeric characters total. This is also useful against people who decode against strings like $tmp_string =~ s/.*&#(d+);.*/$1/; which incorrectly assumes a semicolon is required to terminate a html encoded string (I've seen this in the wild):

Hexadecimal HTML character references without trailing semicolons

This is also a viable XSS attack against the above string $tmp_string =~ s/.*&#(d+);.*/$1/; which assumes that there is a numeric character following the pound symbol - which is not true with hex HTML characters). Use the XSS calculator for more information:

Embedded tab

Used to break up the cross site scripting attack:

Embedded Encoded tab

Use this one to break up XSS :

Embedded newline to break up XSS

Some websites claim that any of the chars 09-13 (decimal) will work for this attack. That is incorrect. Only 09 (horizontal tab), 10 (newline) and 13 (carriage return) work. See the ascii chart for more details. The following four XSS examples illustrate this vector:

Embedded carriage return to break up XSS

(Note: with the above I am making these strings longer than they have to be because the zeros could be omitted. Often I've seen filters that assume the hex and dec encoding has to be two or three characters. The real rule is 1-7 characters.):

Null breaks up JavaScript directive

Null chars also work as XSS vectors but not like above, you need to inject them directly using something like Burp Proxy or use %00 in the URL string or if you want to write your own injection tool you can either use vim (^V^@ will produce a null) or the following program to generate it into a text file. Okay, I lied again, older versions of Opera (circa 7.11 on Windows) were vulnerable to one additional char 173 (the soft hypen control char). But the null char %00is much more useful and helped me bypass certain real world filters with a variation on this example:

Spaces and meta chars before the JavaScript in images for XSS

This is useful if the pattern match doesn't take into account spaces in the word 'javascript:' -which is correct since that won't render- and makes the false assumption that you can't have a space between the quote and the 'javascript:' keyword. The actual reality is you can have any char from 1-32 in decimal:

Non-alpha-non-digit XSS

The Firefox HTML parser assumes a non-alpha-non-digit is not valid after an HTML keyword and therefor considers it to be a whitespace or non-valid token after an HTML tag. The problem is that some XSS filters assume that the tag they are looking for is broken up by whitespace. For example '<SCRIPTs' != '<SCRIPT/XSSs':

Based on the same idea as above, however,expanded on it, using Rnake fuzzer. The Gecko rendering engine allows for any character other than letters, numbers or encapsulation chars (like quotes, angle brackets, etc...) between the event handler and the equals sign, making it easier to bypass cross site scripting blocks. Note that this also applies to the grave accent char as seen here:

Yair Amit brought this to my attention that there is slightly different behavior between the IE and Gecko rendering engines that allows just a slash between the tag and the parameter with no spaces. This could be useful if the system does not allow spaces.

Submitted by Franz Sedlmaier, this XSS vector could defeat certain detection engines that work by first using matching pairs of open and close angle brackets and then by doing a comparison of the tag inside, instead of a more efficient algorythm like Boyer-Moore that looks for entire string matches of the open angle bracket and associated tag (post de-obfuscation, of course). The double slash comments out the ending extraneous bracket to supress a JavaScript error:

No closing script tags

In Firefox and Netscape 8.1 in the Gecko rendering engine mode you don't actually need the '></SCRIPT>' portion of this Cross Site Scripting vector. Firefox assumes it's safe to close the HTML tag and add closing tags for you. How thoughtful! Unlike the next one, which doesn't effect Firefox, this does not require any additional HTML below it. You can add quotes if you need to, but they're not needed generally, although beware, I have no idea what the HTML will end up looking like once this is injected:

Protocol resolution in script tags

This particular variant was submitted by Łukasz Pilorz and was based partially off of Ozh's protocol resolution bypass below. This cross site scripting example works in IE, Netscape in IE rendering mode and Opera if you add in a </SCRIPT> tag at the end. However, this is especially useful where space is an issue, and of course, the shorter your domain, the better. The '.j' is valid, regardless of the encoding type because the browser knows it in context of a SCRIPT tag.

Half open HTML/JavaScript XSS vector

Unlike Firefox the IE rendering engine doesn't add extra data to your page, but it does allow the javascript: directive in images. This is useful as a vector because it doesn't require a close angle bracket. This assumes there is any HTML tag below where you are injecting this cross site scripting vector. Even though there is no close '>' tag the tags below it will close it. A note: this does mess up the HTML, depending on what HTML is beneath it. It gets around the following NIDS regex: /((%3D)|(=))[^n]*((%3C)|<)[^n]+((%3E)|>)/ because it doesn't require the end '>'. As a side note, this was also affective against a real world XSS filter I came across using an open ended <IFRAME tag instead of an <IMG tag:

Double open angle brackets

Using an open angle bracket at the end of the vector instead of a close angle bracket causes different behavior in Netscape Gecko rendering. Without it, Firefox will work but Netscape won't:

Escaping JavaScript escapes

When the application is written to output some user information inside of a JavaScript like the following: <SCRIPT>var a='$ENV{QUERY_STRING}';</SCRIPT> and you want to inject your own JavaScript into it but the server side application escapes certain quotes you can circumvent that by escaping their escape character. When this is gets injected it will read <SCRIPT>var a=';alert('XSS');//';</SCRIPT> which ends up un-escaping the double quote and causing the Cross Site Scripting vector to fire. The XSS locator uses this method.:

End title tag

This is a simple XSS vector that closes <TITLE> tags, which can encapsulate the malicious cross site scripting attack:

INPUT image

BODY image

IMG Dynsrc

IMG lowsrc

List-style-image

Fairly esoteric issue dealing with embedding images for bulleted lists. This will only work in the IE rendering engine because of the JavaScript directive. Not a particularly useful cross site scripting vector:

VBscript in an image

Livescript (older versions of Netscape only)

BODY tag

Method doesn't require using any variants of 'javascript:' or '<SCRIPT...' to accomplish the XSS attack). Dan Crowley additionally noted that you can put a space before the equals sign ('onload=' != 'onload ='):

Event Handlers

It can be used in similar XSS attacks to the one above (this is the most comprehensive list on the net, at the time of this writing). Thanks to Rene Ledosquet for the HTML+TIME updates.

The Dottoro Web Reference also has a nice list of events in JavaScript.

  1. FSCommand() (attacker can use this when executed from within an embedded Flash object)
  2. onAbort() (when user aborts the loading of an image)
  3. onActivate() (when object is set as the active element)
  4. onAfterPrint() (activates after user prints or previews print job)
  5. onAfterUpdate() (activates on data object after updating data in the source object)
  6. onBeforeActivate() (fires before the object is set as the active element)
  7. onBeforeCopy() (attacker executes the attack string right before a selection is copied to the clipboard - attackers can do this with the execCommand('Copy') function)
  8. onBeforeCut() (attacker executes the attack string right before a selection is cut)
  9. onBeforeDeactivate() (fires right after the activeElement is changed from the current object)
  10. onBeforeEditFocus() (Fires before an object contained in an editable element enters a UI-activated state or when an editable container object is control selected)
  11. onBeforePaste() (user needs to be tricked into pasting or be forced into it using the execCommand('Paste') function)
  12. onBeforePrint() (user would need to be tricked into printing or attacker could use the print() or execCommand('Print') function).
  13. onBeforeUnload() (user would need to be tricked into closing the browser - attacker cannot unload windows unless it was spawned from the parent)
  14. onBeforeUpdate() (activates on data object before updating data in the source object)
  15. onBegin() (the onbegin event fires immediately when the element's timeline begins)
  16. onBlur() (in the case where another popup is loaded and window looses focus)
  17. onBounce() (fires when the behavior property of the marquee object is set to 'alternate' and the contents of the marquee reach one side of the window)
  18. onCellChange() (fires when data changes in the data provider)
  19. onChange() (select, text, or TEXTAREA field loses focus and its value has been modified)
  20. onClick() (someone clicks on a form)
  21. onContextMenu() (user would need to right click on attack area)
  22. onControlSelect() (fires when the user is about to make a control selection of the object)
  23. onCopy() (user needs to copy something or it can be exploited using the execCommand('Copy') command)
  24. onCut() (user needs to copy something or it can be exploited using the execCommand('Cut') command)
  25. onDataAvailable() (user would need to change data in an element, or attacker could perform the same function)
  26. onDataSetChanged() (fires when the data set exposed by a data source object changes)
  27. onDataSetComplete() (fires to indicate that all data is available from the data source object)
  28. onDblClick() (user double-clicks a form element or a link)
  29. onDeactivate() (fires when the activeElement is changed from the current object to another object in the parent document)
  30. onDrag() (requires that the user drags an object)
  31. onDragEnd() (requires that the user drags an object)
  32. onDragLeave() (requires that the user drags an object off a valid location)
  33. onDragEnter() (requires that the user drags an object into a valid location)
  34. onDragOver() (requires that the user drags an object into a valid location)
  35. onDragDrop() (user drops an object (e.g. file) onto the browser window)
  36. onDragStart() (occurs when user starts drag operation)
  37. onDrop() (user drops an object (e.g. file) onto the browser window)
  38. onEnd() (the onEnd event fires when the timeline ends.
  39. onError() (loading of a document or image causes an error)
  40. onErrorUpdate() (fires on a databound object when an error occurs while updating the associated data in the data source object)
  41. onFilterChange() (fires when a visual filter completes state change)
  42. onFinish() (attacker can create the exploit when marquee is finished looping)
  43. onFocus() (attacker executes the attack string when the window gets focus)
  44. onFocusIn() (attacker executes the attack string when window gets focus)
  45. onFocusOut() (attacker executes the attack string when window looses focus)
  46. onHashChange() (fires when the fragment identifier part of the document's current address changed)
  47. onHelp() (attacker executes the attack string when users hits F1 while the window is in focus)
  48. onInput() (the text content of an element is changed through the user interface)
  49. onKeyDown() (user depresses a key)
  50. onKeyPress() (user presses or holds down a key)
  51. onKeyUp() (user releases a key)
  52. onLayoutComplete() (user would have to print or print preview)
  53. onLoad() (attacker executes the attack string after the window loads)
  54. onLoseCapture() (can be exploited by the releaseCapture() method)
  55. onMediaComplete() (When a streaming media file is used, this event could fire before the file starts playing)
  56. onMediaError() (User opens a page in the browser that contains a media file, and the event fires when there is a problem)
  57. onMessage() (fire when the document received a message)
  58. onMouseDown() (the attacker would need to get the user to click on an image)
  59. onMouseEnter() (cursor moves over an object or area)
  60. onMouseLeave() (the attacker would need to get the user to mouse over an image or table and then off again)
  61. onMouseMove() (the attacker would need to get the user to mouse over an image or table)
  62. onMouseOut() (the attacker would need to get the user to mouse over an image or table and then off again)
  63. onMouseOver() (cursor moves over an object or area)
  64. onMouseUp() (the attacker would need to get the user to click on an image)
  65. onMouseWheel() (the attacker would need to get the user to use their mouse wheel)
  66. onMove() (user or attacker would move the page)
  67. onMoveEnd() (user or attacker would move the page)
  68. onMoveStart() (user or attacker would move the page)
  69. onOffline() (occurs if the browser is working in online mode and it starts to work offline)
  70. onOnline() (occurs if the browser is working in offline mode and it starts to work online)
  71. onOutOfSync() (interrupt the element's ability to play its media as defined by the timeline)
  72. onPaste() (user would need to paste or attacker could use the execCommand('Paste') function)
  73. onPause() (the onpause event fires on every element that is active when the timeline pauses, including the body element)
  74. onPopState() (fires when user navigated the session history)
  75. onProgress() (attacker would use this as a flash movie was loading)
  76. onPropertyChange() (user or attacker would need to change an element property)
  77. onReadyStateChange() (user or attacker would need to change an element property)
  78. onRedo() (user went forward in undo transaction history)
  79. onRepeat() (the event fires once for each repetition of the timeline, excluding the first full cycle)
  80. onReset() (user or attacker resets a form)
  81. onResize() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  82. onResizeEnd() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  83. onResizeStart() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  84. onResume() (the onresume event fires on every element that becomes active when the timeline resumes, including the body element)
  85. onReverse() (if the element has a repeatCount greater than one, this event fires every time the timeline begins to play backward)
  86. onRowsEnter() (user or attacker would need to change a row in a data source)
  87. onRowExit() (user or attacker would need to change a row in a data source)
  88. onRowDelete() (user or attacker would need to delete a row in a data source)
  89. onRowInserted() (user or attacker would need to insert a row in a data source)
  90. onScroll() (user would need to scroll, or attacker could use the scrollBy() function)
  91. onSeek() (the onreverse event fires when the timeline is set to play in any direction other than forward)
  92. onSelect() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand('SelectAll');)
  93. onSelectionChange() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand('SelectAll');)
  94. onSelectStart() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand('SelectAll');)
  95. onStart() (fires at the beginning of each marquee loop)
  96. onStop() (user would need to press the stop button or leave the webpage)
  97. onStorage() (storage area changed)
  98. onSyncRestored() (user interrupts the element's ability to play its media as defined by the timeline to fire)
  99. onSubmit() (requires attacker or user submits a form)
  100. onTimeError() (user or attacker sets a time property, such as dur, to an invalid value)
  101. onTrackChange() (user or attacker changes track in a playList)
  102. onUndo() (user went backward in undo transaction history)
  103. onUnload() (as the user clicks any link or presses the back button or attacker forces a click)
  104. onURLFlip() (this event fires when an Advanced Streaming Format (ASF) file, played by a HTML+TIME (Timed Interactive Multimedia Extensions) media tag, processes script commands embedded in the ASF file)
  105. seekSegmentTime() (this is a method that locates the specified point on the element's segment time line and begins playing from that point. The segment consists of one repetition of the time line including reverse play using the AUTOREVERSE attribute.)

BGSOUND

& JavaScript includes

STYLE sheet

Remote style sheet

(using something as simple as a remote style sheet you can include your XSS as the style parameter can be redefined using an embedded expression.) This only works in IE and Netscape 8.1+ in IE rendering engine mode. Notice that there is nothing on the page to show that there is included JavaScript. Note: With all of these remote style sheet examples they use the body tag, so it won't work unless there is some content on the page other than the vector itself, so you'll need to add a single letter to the page to make it work if it's an otherwise blank page:

Remote style sheet part 2

This works the same as above, but uses a <STYLE> tag instead of a <LINK> tag). A slight variation on this vector was used to hack Google Desktop. As a side note, you can remove the end </STYLE> tag if there is HTML immediately after the vector to close it. This is useful if you cannot have either an equals sign or a slash in your cross site scripting attack, which has come up at least once in the real world:

Remote style sheet part 3

Sheet

This only works in Opera 8.0 (no longer in 9.x) but is fairly tricky. According to RFC2616 setting a link header is not part of the HTTP1.1 spec, however some browsers still allow it (like Firefox and Opera). The trick here is that I am setting a header (which is basically no different than in the HTTP header saying Link: <http://ha.ckers.org/xss.css>; REL=stylesheet) and the remote style sheet with my cross site scripting vector is running the JavaScript, which is not supported in FireFox:

Remote style sheet part 4

This only works in Gecko rendering engines and works by binding an XUL file to the parent page. I think the irony here is that Netscape assumes that Gecko is safer and therefor is vulnerable to this for the vast majority of sites:

STYLE tags with broken up JavaScript for XSS

This XSS at times sends IE into an infinite loop of alerts:

Created by Roman Ivanov

IMG STYLE with expression

This is really a hybrid of the above XSS vectors, but it really does show how hard STYLE tags can be to parse apart, like above this can send IE into a loop:

STYLE tag (Older versions of Netscape only)

STYLE tag using background-image

STYLE tag using background

<STYLE type='text/css'>BODY{background:url('javascript:alert('XSS')')}</STYLE>

Anonymous HTML with STYLE attribute

IE6.0 and Netscape 8.1+ in IE rendering engine mode don't really care if the HTML tag you build exists or not, as long as it starts with an open angle bracket and a letter:

Local htc file

This is a little different than the above two cross site scripting vectors because it uses an .htc file which must be on the same server as the XSS vector. The example file works by pulling in the JavaScript and running it as part of the style attribute:

US-ASCII encoding

US-ASCII encoding (found by Kurt Huwig).This uses malformed ASCII encoding with 7 bits instead of 8. This XSS may bypass many content filters but only works if the host transmits in US-ASCII encoding, or if you set the encoding yourself. This is more useful against web application firewall cross site scripting evasion than it is server side filter evasion. Apache Tomcat is the only known server that transmits in US-ASCII encoding.

META

The odd thing about meta refresh is that it doesn't send a referrer in the header - so it can be used for certain types of attacks where you need to get rid of referring URLs:

META using data

Directive URL scheme. This is nice because it also doesn't have anything visibly that has the word SCRIPT or the JavaScript directive in it, because it utilizes base64 encoding. Please see RFC 2397 for more details or go here or here to encode your own. You can also use the XSS calculator below if you just want to encode raw HTML or JavaScript as it has a Base64 encoding method:

META with additional URL parameter

If the target website attempts to see if the URL contains 'http://' at the beginning you can evade it with the following technique (Submitted by Moritz Naumann):

IFRAME

If iframes are allowed there are a lot of other XSS problems as well:

IFRAME Event based

IFrames and most other elements can use event based mayhem like the following... (Submitted by: David Cross)

FRAME

Frames have the same sorts of XSS problems as iframes

TABLE

TD

Just like above, TD's are vulnerable to BACKGROUNDs containing JavaScript XSS vectors:

DIV

DIV background-image

DIV background-image with unicoded XSS exploit

This has been modified slightly to obfuscate the url parameter. The original vulnerability was found by Renaud Lifchitz as a vulnerability in Hotmail:

Rnaske built a quick XSS fuzzer to detect any erroneous characters that are allowed after the open parenthesis but before the JavaScript directive in IE and Netscape 8.1 in secure site mode. These are in decimal but you can include hex and add padding of course. (Any of the following chars can be used: 1-32, 34, 39, 160, 8192-8.13, 12288, 65279):

DIV expression

A variant of this was effective against a real world cross site scripting filter using a newline between the colon and 'expression':

Downlevel-Hidden block

Only works in IE5.0 and later and Netscape 8.1 in IE rendering engine mode). Some websites consider anything inside a comment block to be safe and therefore does not need to be removed, which allows our Cross Site Scripting vector. Or the system could add comment tags around something to attempt to render it harmless. As we can see, that probably wouldn't do the job:

Xss Cheat Sheet 2020

BASE tag

Works in IE and Netscape 8.1 in safe mode. You need the // to comment out the next characters so you won't get a JavaScript error and your XSS tag will render. Also, this relies on the fact that the website uses dynamically placed images like 'images/image.jpg' rather than full paths. If the path includes a leading forward slash like '/images/image.jpg' you can remove one slash from this vector (as long as there are two to begin the comment this will work):

OBJECT tag

If they allow objects, you can also inject virus payloads to infect the users, etc. and same with the APPLET tag). The linked file is actually an HTML file that can contain your XSS:

Using an EMBED tag you can embed a Flash movie that contains XSS

Click here for a demo. If you add the attributes allowScriptAccess='never' and allownetworking='internal' it can mitigate this risk (thank you to Jonathan Vanasco for the info).:

You can EMBED SVG which can contain your XSS vector

This example only works in Firefox, but it's better than the above vector in Firefox because it does not require the user to have Flash turned on or installed. Thanks to nEUrOO for this one.

Using ActionScript inside flash can obfuscate your XSS vector

XML data island with CDATA obfuscation

This XSS attack works only in IE and Netscape 8.1 in IE rendering engine mode) - vector found by Sec Consult while auditing Yahoo:

Locally hosted XML with embedded JavaScript that is generated using an XML data island

This is the same as above but instead referrs to a locally hosted (must be on the same server) XML file that contains your cross site scripting vector. You can see the result here:

HTML+TIME in XML

This is how Grey Magic hacked Hotmail and Yahoo!. This only works in Internet Explorer and Netscape 8.1 in IE rendering engine mode and remember that you need to be between HTML and BODY tags for this to work:

Assuming you can only fit in a few characters and it filters against '.js'

you can rename your JavaScript file to an image as an XSS vector:

SSI (Server Side Includes)

This requires SSI to be installed on the server to use this XSS vector. I probably don't need to mention this, but if you can run commands on the server there are no doubt much more serious issues:

PHP

Requires PHP to be installed on the server to use this XSS vector. Again, if you can run any scripts remotely like this, there are probably much more dire issues:

IMG Embedded commands

This works when the webpage where this is injected (like a web-board) is behind password protection and that password protection works with other commands on the same domain. This can be used to delete users, add users (if the user who visits the page is an administrator), send credentials elsewhere, etc.... This is one of the lesser used but more useful XSS vectors:

IMG Embedded commands part II

This is more scary because there are absolutely no identifiers that make it look suspicious other than it is not hosted on your own domain. The vector uses a 302 or 304 (others work too) to redirect the image back to a command. So a normal <IMG SRC='> could actually be an attack vector to run commands as the user who views the image link. Here is the .htaccess (under Apache) line to accomplish the vector (thanks to Timo for part of this):

Cookie manipulation

Admittidly this is pretty obscure but I have seen a few examples where <META is allowed and you can use it to overwrite cookies. There are other examples of sites where instead of fetching the username from a database it is stored inside of a cookie to be displayed only to the user who visits the page. With these two scenarios combined you can modify the victim's cookie which will be displayed back to them as JavaScript (you can also use this to log people out or change their user states, get them to log in as you, etc...):

UTF-7 encoding

If the page that the XSS resides on doesn't provide a page charset header, or any browser that is set to UTF-7 encoding can be exploited with the following (Thanks to Roman Ivanov for this one). Click here for an example (you don't need the charset statement if the user's browser is set to auto-detect and there is no overriding content-types on the page in Internet Explorer and Netscape 8.1 in IE rendering engine mode). This does not work in any modern browser without changing the encoding type which is why it is marked as completely unsupported. Watchfire found this hole in Google's custom 404 script.:

XSS using HTML quote encapsulation

This was tested in IE, your mileage may vary. For performing XSS on sites that allow '<SCRIPT>' but don't allow '<SCRIPT SRC...' by way of a regex filter '/<script[^>]+src/i':

For performing XSS on sites that allow '<SCRIPT>' but don't allow '<script src...' by way of a regex filter '/<script((s+w+(s*=s*(?:'(.)*?'|'(.)*?'|[^'>s]+))?)+s*|s*)src/i' (this is an important one, because I've seen this regex in the wild):

Another XSS to evade the same filter, '/<script((s+w+(s*=s*(?:'(.)*?'|'(.)*?'|[^'>s]+))?)+s*|s*)src/i':

Yet another XSS to evade the same filter, '/<script((s+w+(s*=s*(?:'(.)*?'|'(.)*?'|[^'>s]+))?)+s*|s*)src/i'. I know I said I wasn't goint to discuss mitigation techniques but the only thing I've seen work for this XSS example if you still want to allow <SCRIPT> tags but not remote script is a state machine (and of course there are other ways to get around this if they allow <SCRIPT> tags):

And one last XSS attack to evade, '/<script((s+w+(s*=s*(?:'(.)*?'|'(.)*?'|[^'>s]+))?)+s*|s*)src/i' using grave accents (again, doesn't work in Firefox):

Here's an XSS example that bets on the fact that the regex won't catch a matching pair of quotes but will rather find any quotes to terminate a parameter string improperly:

This XSS still worries me, as it would be nearly impossible to stop this without blocking all active content:

URL string evasion

Assuming 'http://www.google.com/' is pro grammatically disallowed:

IP verses hostname

URL encoding

Dword encoding

(Note: there are other of variations of Dword encoding - see the IP Obfuscation calculator below for more details):

Hex encoding

The total size of each number allowed is somewhere in the neighborhood of 240 total characters as you can see on the second digit, and since the hex number is between 0 and F the leading zero on the third hex quotet is not required):

Octal encoding

Again padding is allowed, although you must keep it above 4 total characters per class - as in class A, class B, etc...:

Mixed encoding

Let's mix and match base encoding and throw in some tabs and newlines - why browsers allow this, I'll never know). The tabs and newlines only work if this is encapsulated with quotes:

Protocol resolution bypass

(// translates to http:// which saves a few more bytes). This is really handy when space is an issue too (two less characters can go a long way) and can easily bypass regex like '(ht|f)tp(s)?://' (thanks to Ozh for part of this one). You can also change the '//' to '. You do need to keep the slashes in place, however, otherwise this will be interpreted as a relative path URL.

Google 'feeling lucky' part 1.

Firefox uses Google's 'feeling lucky' function to redirect the user to any keywords you type in. So if your exploitable page is the top for some random keyword (as you see here) you can use that feature against any Firefox user. This uses Firefox's 'keyword:' protocol. You can concatinate several keywords by using something like the following 'keyword:XSS+RSnake' for instance. This no longer works within Firefox as of 2.0.

Google 'feeling lucky' part 2.

This uses a very tiny trick that appears to work Firefox only, because if it's implementation of the 'feeling lucky' function. Unlike the next one this does not work in Opera because Opera believes that this is the old HTTP Basic Auth phishing attack, which it is not. It's simply a malformed URL. If you click okay on the dialogue it will work, but as a result of the erroneous dialogue box I am saying that this is not supported in Opera, and it is no longer supported in Firefox as of 2.0:

Google 'feeling lucky' part 3.

This uses a malformed URL that appears to work in Firefox and Opera only, because if their implementation of the 'feeling lucky' function. Like all of the above it requires that you are #1 in Google for the keyword in question (in this case 'google'):

Removing cnames

Xss Filter Evasion Cheat Sheet Github

When combined with the above URL, removing 'www.' will save an additional 4 bytes for a total byte savings of 9 for servers that have this set up properly):

JavaScript link location:

Content replace as attack vector

Assuming 'http://www.google.com/' is programmatically replaced with nothing). I actually used a similar attack vector against a several separate real world XSS filters by using the conversion filter itself (here is an example) to help create the attack vector (IE: 'java&#x09;script:' was converted into 'java script:', which renders in IE, Netscape 8.1+ in secure site mode and Opera):

Character escape sequences

All the possible combinations of the character '<' in HTML and JavaScript. Most of these won't render out of the box, but many of them can get rendered in certain circumstances as seen above.

This following links include calculators for doing basic transformation functions that are useful for XSS.

Robert 'RSnake' Hansen from www.fallingrocknetworks.com

OWASP Cheat Sheets Project Homepage

Developer Cheat Sheets (Builder)

Assessment Cheat Sheets (Breaker)

Mobile Cheat Sheets

OpSec Cheat Sheets (Defender)

Draft Cheat Sheets

When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of XSS):

  • Reflected or Stored#Stored_and_Reflected_XSS_Attacks)
  • DOM Based XSS.

The XSS Prevention Cheatsheet does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension of) the XSS Prevention Cheatsheet.

In order to understand DOM based XSS, one needs to see the fundamental difference between Reflected and Stored XSS when compared to DOM based XSS. The primary difference is where the attack is injected into the application.

Reflected and Stored XSS are server side injection issues while DOM based XSS is a client (browser) side injection issue.

All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. Also, XSS attacks always execute in the browser.

The difference between Reflected/Stored XSS is where the attack is added or injected into the application. With Reflected/Stored the attack is injected into the application during server-side processing of requests where untrusted input is dynamically added to HTML. For DOM XSS, the attack is injected into the application during runtime in the client directly.

When a browser is rendering HTML and any other associated content like CSS, JavaScript, etc. it identifies various rendering contexts for the different kinds of input and follows different rules for each context. A rendering context is associated with the parsing of HTML tags and their attributes.

  • The HTML parser of the rendering context dictates how data is presented and laid out on the page and can be further broken down into the standard contexts of HTML, HTML attribute, URL, and CSS.
  • The JavaScript or VBScript parser of an execution context is associated with the parsing and execution of script code. Each parser has distinct and separate semantics in the way they can possibly execute script code which make creating consistent rules for mitigating vulnerabilities in various contexts difficult. The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.

For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.

In JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.

The following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:

Let’s look at the individual subcontexts of the execution context in turn.

There are several methods and attributes which can be used to directly render HTML content within JavaScript. These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:

Example Dangerous HTML Methods

Attributes

Methods

Guideline

To make dynamic updates to HTML in the DOM safe, we recommend:

  1. HTML encoding, and then
  2. JavaScript encoding all untrusted input, as shown in these examples:

Note: The Encoder.encodeForHTML() and Encoder.encodeForJS() are just notional encoders. Various options for actual encoders are listed later in this document.

The HTML attribute subcontext within the execution context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.

When you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).

For example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute. This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.

SAFE but BROKEN example

The problem is that if companyName had the value “Johnson & Johnson”. What would be displayed in the input text field would be “Johnson & Johnson”. The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.

SAFE and FUNCTIONALLY CORRECT example

It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.

Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings. In many cases, JavaScript encoding does not stop attacks within an execution context. For example, a JavaScript encoded string will execute even though it is JavaScript encoded.

Therefore, the primary recommendation is to avoid including untrusted data in this context. If you must, the following examples describe some approaches that do and do not work.

The setAttribute(name_string,value_string) method is dangerous because it implicitly coerces the value_string into the DOM attribute datatype of name_string.

In the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated. In the case above, JavaScript encoding does not mitigate against DOM based XSS.

Other JavaScript methods which take code as a string types will have a similar problem as outline above (setTimeout, setInterval, new Function, etc.). This is in stark contrast to JavaScript encoding in the event handler attribute of a HTML tag (HTML parser) where JavaScript encoding mitigates against XSS.

An alternative to using Element.setAttribute(...) to set DOM attributes is to set the attribute directly. Directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. Please note, it is always dangerous design to put untrusted data directly into a command execution context.

There are other places in JavaScript where JavaScript encoding is accepted as valid executable code.

or

Because JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).

However the opposite is the case with HTML encoding. HTML tag elements are well defined and do not support alternate representations of the same tag. So HTML encoding cannot be used to allow the developer to have alternate representations of the <a> tag for example.

HTML Encoding’s Disarming Nature

In general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts. Working example (no HTML encoding):

Normally encoded example (Does Not Work – DNW):

HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):

If HTML encoding followed the same semantics as JavaScript encoding. The line above could have possibily worked to render a link. This difference makes JavaScript encoding a less viable weapon in our fight against XSS.

Normally executing JavaScript from a CSS context required either passing javascript:attackCode() to the CSS url() method or invoking the CSS expression() method passing JavaScript code to be directly executed.

From my experience, calling the expression() function from an execution context (JavaScript) has been disabled. In order to mitigate against the CSS url() method, ensure that you are URL encoding the data passed to the CSS url() method.

The logic which parses URLs in both execution and rendering contexts looks to be the same. Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.

If you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (http: or javascript:) will be URL encoded preventing the http and javascript protocols from being invoked.

The most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property textContent.

Here is an example of safe usage.

The best way to fix DOM based cross-site scripting is to use the right output method (sink). For example if you want to use user input to write in a div tag element don’t use innerHtml, instead use innerText or textContent. This will solve the problem, and it is the right way to re-mediate DOM based XSS vulnerabilities.

It is always a bad idea to use a user-controlled input in dangerous sources such as eval. 99% of the time it is an indication of bad or lazy programming practice, so simply don’t do it instead of trying to sanitize the input.

Finally, to fix the problem in our initial code, instead of trying to encode the output correctly which is a hassle and can easily go wrong we would simply use element.textContent to write it in a content like this:

It does the same thing but this time it is not vulnerable to DOM based cross-site scripting vulnerabilities.

DOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.

The guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.

GUIDELINE #1 - Untrusted data should only be treated as displayable text

Avoid treating untrusted data as code or markup within JavaScript code.

GUIDELINE #2 - Always JavaScript encode and delimit untrusted data as quoted strings when entering the application when building templated Javascript

Always JavaScript encode and delimit untrusted data as quoted strings when entering the application as illustrated in the following example.

GUIDELINE #3 - Use document.createElement('...'), element.setAttribute('...','value'), element.appendChild(...) and similar to build dynamic interfaces

document.createElement('...'), element.setAttribute('...','value'), element.appendChild(...) and similar are save ways to build dynamic interfaces.

Please note, element.setAttribute is only safe for a limited number of attributes.

Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur.

Examples of safe attributes includes: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width.

GUIDELINE #4 - Avoid sending untrusted data into HTML rendering methods

Avoid populating the following methods with untrusted data.

  1. element.innerHTML = '...';
  2. element.outerHTML = '...';
  3. document.write(...);
  4. document.writeln(...);

GUIDELINE #5 - Avoid the numerous methods which implicitly eval() data passed to it

There are numerous methods which implicitly eval() data passed to it that must be avoided.

Make sure that any untrusted data passed to these methods is:

  1. Delimited with string delimiters
  2. Enclosed within a closure or JavaScript encoded to N-levels based on usage
  3. Wrapped in a custom function.

Ensure to follow step 3 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.

Xss Cheat Codes

Utilizing an Enclosure (as suggested by Gaz)

The example that follows illustrates using closures to avoid double JavaScript encoding.

The other alternative is using N-levels of encoding.

N-Levels of Encoding

If your code looked like the following, you would need to only double JavaScript encode input data.

The doubleJavaScriptEncodedData has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.

Then the implicit eval of setTimeout reverses another layer of JavaScript encoding to pass the correct value to customFunction

The reason why you only need to double JavaScript encode is that the customFunction function did not itself pass the input to another method which implicitly or explicitly called eval If firstName was passed to another JavaScript method which implicitly or explicitly called eval() then <%=doubleJavaScriptEncodedData%> above would need to be changed to <%=tripleJavaScriptEncodedData%>.

An important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of evals() the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.

If A is double JavaScript encoded then the following if check will return false.

This brings up an interesting design point. Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.

Then client-side encode (using a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM methods) which untrusted data is passed to. ESAPI4JS and jQuery Encoder are two client side encoding libraries developed by Chris Schmidt.

Here are some examples of how they are used:

One option is utilize ECMAScript 5 immutable properties in the JavaScript library.Another option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous closures.

An example follows:

Chris Schmidt has put together another implementation of a JavaScript encoder here.

GUIDELINE #6 - Limit the usage of untrusted data to only right side operations

Not only is it good design to limit the usage of untrusted data to right side operations, but also be aware of data which may be passed to the application which look like code (eg. location, eval()).

If you want to change different object attributes based on user input then use a level of indirection.Instead of:

Do the following instead:

GUIDELINE #7 - When URL encoding in DOM be aware of character set issues

When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).

GUIDELINE #8 - Limit access to properties objects when using object[x] accessors

Limit access to properties objects when using object[x] accessors (Mike Samuel). In other words use a level of indirection between untrusted input and specified object properties.

Here is an example of the problem when using map types:

Although the developer writing the code above was trying to add additional keyed elements to the myMapType object. This could be used by an attacker to subvert internal and external attributes of the myMapType object.

GUIDELINE #9 - Run your JavaScript in a ECMAScript 5 canopy or sandbox

Run your JavaScript in a ECMAScript 5 canopy or sandbox to make it harder for your JavaScript API to be compromised (Gareth Heyes and John Stevens).

GUIDELINE #10 - Don’t eval() JSON to convert it to native JavaScript objects

Don’t eval() JSON to convert it to native JavaScript objects. Instead use JSON.toJSON() and JSON.parse() (Chris Schmidt).

Complex Contexts

In many cases the context isn’t always straightforward to discern.

Xss Payload Cheat Sheet Github

In the above example, untrusted data started in the rendering URL context (href attribute of an a tag) then changed to a JavaScript execution context (javascript: protocol handler) which passed the untrusted data to an execution URL subcontext (window.location of myFunction).

Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:

Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:

Inconsistencies of Encoding Libraries

There are a number of open source encoding libraries out there:

  1. OWASP ESAPI
  2. OWASP Java Encoder
  3. Apache Commons Text StringEscapeUtils, replace one from Apache Commons Lang3
  4. Your company’s custom implementation.

Some work on a black list while others ignore important characters like “<” and “>”.

Java Encoder is an active project providing supports for HTML, CSS and JavaScript encoding.

ESAPI is one of the few which works on a whitelist and encodes all non-alphanumeric characters. It is important to use an encoding library that understands which characters can be used to exploit vulnerabilities in their respective contexts. Misconceptions abound related to the proper encoding that is required.

Encoding Misconceptions

Many security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.

Sheet

This logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.

However, if the pages returned from your web application utilize a content type of text/xhtml or the file type extension of *.xhtml then HTML encoding may not work to mitigate against XSS.

For example:

The HTML encoded value above is still executable. If that isn’t enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element.

Let’s look at the sample page and script:

Finally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.

Usually Safe Methods

One example of an attribute which is thought to be safe is innerText.

Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML. However, depending on the tag which innerText is applied, code can be executed.

The innerText feature was originally introduced by Internet Explorer, and was formally specified in the HTML standard in 2016 after being adopted by all major browser vendors.

Jim Manico - jim@owasp.org

Abraham Kang - abraham.kang@owasp.org

Gareth (Gaz) Heyes

Stefano Di Paola

Achim Hoffmann - achim@owasp.org

Robert (RSnake) Hansen

Mario Heiderich

John Steven

Chris (Chris BEEF) Schmidt

Mike Samuel

Xss Cheat Sheet Github

Jeremy Long

Dhiraj Mishra - mishra.dhiraj@owasp.org

Eduardo (SirDarkCat) Alberto Vela Nava

Jeff Williams - jeff.williams@owasp.org

Erlend Oftedal