# Cross-site scripting (Practice on PortSwigger) ###### tags: `vulnerable` `top10owasp` `exploits` `tutorials` ## What is cross-site scripting (XSS)? Cross-site scripting (also known as XSS) is a web security vulnerability that allows an attacker to compromise the interactions that users have with a vulnerable application. It allows an attacker to circumvent the same origin policy, which is designed to segregate different websites from each other. Cross-site scripting vulnerabilities normally allow an attacker to masquerade as a victim user, to carry out any actions that the user is able to perform, and to access any of the user's data. If the victim user has privileged access within the application, then the attacker might be able to gain full control over all of the application's functionality and data. ## How does XSS work? Cross-site scripting works by manipulating a vulnerable web site so that it returns malicious JavaScript to users. When the malicious code executes inside a victim's browser, the attacker can fully compromise their interaction with the application. ![](https://i.imgur.com/HtmkAPK.png) ## XSS proof of concept You can confirm most kinds of XSS vulnerability by injecting a payload that causes your own browser to execute some arbitrary JavaScript. It's long been common practice to use the alert() function for this purpose because it's short, harmless, and pretty hard to miss when it's successfully called. In fact, you solve the majority of our XSS labs by invoking alert() in a simulated victim's browser. Unfortunately, there's a slight hitch if you use Chrome. From version 92 onward (July 20th, 2021), cross-origin iframes are prevented from calling alert(). As these are used to construct some of the more advanced XSS attacks, you'll sometimes need to use an alternative PoC payload. In this scenario, we recommend the print() function. If you're interested in learning more about this change and why we like print(), check out our blog post on the subject. As the simulated victim in our labs uses Chrome, we've amended the affected labs so that they can also be solved using print(). We've indicated this in the instructions wherever relevant. ## What are the types of XSS attacks? There are three main types of XSS attacks. These are: * Reflected XSS, where the malicious script comes from the current HTTP request. * Stored XSS, where the malicious script comes from the website's database. * DOM-based XSS, where the vulnerability exists in client-side code rather than server-side code. ## Reflected cross-site scripting ### What is reflected cross-site scripting? [Reflected XSS](https://portswigger.net/web-security/cross-site-scripting/reflected) is the simplest variety of cross-site scripting. It arises when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way. Here is a simple example of a reflected XSS vulnerability: ``` https://insecure-website.com/status?message=All+is+well. <p>Status: All is well.</p> ``` The application doesn't perform any other processing of the data, so an attacker can easily construct an attack like this: ``` https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script> <p>Status: <script>/* Bad stuff here... */</script></p> ``` If the user visits the URL constructed by the attacker, then the attacker's script executes in the user's browser, in the context of that user's session with the application. At that point, the script can carry out any action, and retrieve any data, to which the user has access. **Answer**: - As Lab: Reflected XSS into HTML context with nothing encoded, we will perform basic XSS so just put <script></script> tag with alert('anything else') you want and get resolve for this lab ![](https://i.imgur.com/iFG6C8h.png) ### Impact of reflected XSS attacks If an attacker can control a script that is executed in the victim's browser, then they can typically fully compromise that user. Amongst other things, the attacker can: * Perform any action within the application that the user can perform. * View any information that the user is able to view. * Modify any information that the user is able to modify. * Initiate interactions with other application users, including malicious attacks, that will appear to originate from the initial victim user. There are various means by which an attacker might induce a victim user to make a request that they control, to deliver a reflected XSS attack. These include placing links on a website controlled by the attacker, or on another website that allows content to be generated, or by sending a link in an email, tweet or other message. The attack could be targeted directly against a known user, or could an indiscriminate attack against any users of the application: The need for an external delivery mechanism for the attack means that the impact of reflected XSS is generally less severe than [stored XSS](https://portswigger.net/web-security/cross-site-scripting/stored), where a self-contained attack can be delivered within the vulnerable application itself. **NOTE: YOU CAN APPLY XSS ON MANY SITUATION TO CAUSE SOME [OTHER VUL](https://portswigger.net/web-security/cross-site-scripting/exploiting) :scream:** ### [Reflected XSS in different contexts](https://portswigger.net/web-security/cross-site-scripting/contexts) There are many different varieties of reflected cross-site scripting. The location of the reflected data within the application's response determines what type of payload is required to exploit it and might also affect the impact of the vulnerability. In addition, if the application performs any validation or other processing on the submitted data before it is reflected, this will generally affect what kind of XSS payload is needed. ### How to find and test for reflected XSS vulnerabilities The vast majority of reflected cross-site scripting vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner. Testing for reflected XSS vulnerabilities manually involves the following steps: * Test every entry point. Test separately every entry point for data within the application's HTTP requests. This includes parameters or other data within the URL query string and message body, and the URL file path. It also includes HTTP headers, although XSS-like behavior that can only be triggered via certain HTTP headers may not be exploitable in practice. * Submit random alphanumeric values. For each entry point, submit a unique random value and determine whether the value is reflected in the response. The value should be designed to survive most input validation, so needs to be fairly short and contain only alphanumeric characters. But it needs to be long enough to make accidental matches within the response highly unlikely. A random alphanumeric value of around 8 characters is normally ideal. You can use Burp Intruder's number payloads [https://portswigger.net/burp/documentation/desktop/tools/intruder/payloads/types#numbers] with randomly generated hex values to generate suitable random values. And you can use Burp Intruder's grep payloads option to automatically flag responses that contain the submitted value. * Determine the reflection context. For each location within the response where the random value is reflected, determine its context. This might be in text between HTML tags, within a tag attribute which might be quoted, within a JavaScript string, etc. * Test a candidate payload. Based on the context of the reflection, test an initial candidate XSS payload that will trigger JavaScript execution if it is reflected unmodified within the response. The easiest way to test payloads is to send the request to Burp Repeater, modify the request to insert the candidate payload, issue the request, and then review the response to see if the payload worked. An efficient way to work is to leave the original random value in the request and place the candidate XSS payload before or after it. Then set the random value as the search term in Burp Repeater's response view. Burp will highlight each location where the search term appears, letting you quickly locate the reflection. * Test alternative payloads. If the candidate XSS payload was modified by the application, or blocked altogether, then you will need to test alternative payloads and techniques that might deliver a working XSS attack based on the context of the reflection and the type of input validation that is being performed. For more details, see cross-site scripting contexts * Test the attack in a browser. Finally, if you succeed in finding a payload that appears to work within Burp Repeater, transfer the attack to a real browser (by pasting the URL into the address bar, or by modifying the request in Burp Proxy's intercept view, and see if the injected JavaScript is indeed executed. Often, it is best to execute some simple JavaScript like alert(document.domain) which will trigger a visible popup within the browser if the attack succeeds. ### Common questions about reflected cross-site scripting What is the difference between reflected XSS and stored XSS? Reflected XSS arises when an application takes some input from an HTTP request and embeds that input into the immediate response in an unsafe way. With stored XSS, the application instead stores the input and embeds it into a later response in an unsafe way. What is the difference between reflected XSS and self-XSS? Self-XSS involves similar application behavior to regular reflected XSS, however it cannot be triggered in normal ways via a crafted URL or a cross-domain request. Instead, the vulnerability is only triggered if the victim themselves submits the XSS payload from their browser. Delivering a self-XSS attack normally involves socially engineering the victim to paste some attacker-supplied input into their browser. As such, it is normally considered to be a lame, low-impact issue. ## Stored cross-site scripting ### What is stored cross-site scripting? Stored cross-site scripting (also known as second-order or persistent XSS) arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way. Suppose a website allows users to submit comments on blog posts, which are displayed to other users. Users submit comments using an HTTP request like the following: ``` POST /post/comment HTTP/1.1 Host: vulnerable-website.com Content-Length: 100 postId=3&comment=This+post+was+extremely+helpful.&name=Carlos+Montoya&email=carlos%40normal-user.net ``` After this comment has been submitted, any user who visits the blog post will receive the following within the application's response: `<p>This post was extremely helpful.</p>` Assuming the application doesn't perform any other processing of the data, an attacker can submit a malicious comment like this: `<script>/* Bad stuff here... */</script>` Within the attacker's request, this comment would be URL-encoded as: `comment=%3Cscript%3E%2F*%2BBad%2Bstuff%2Bhere...%2B*%2F%3C%2Fscript%3E` Any user who visits the blog post will now receive the following within the application's response: `<p><script>/* Bad stuff here... */</script></p>` The script supplied by the attacker will then execute in the victim user's browser, in the context of their session with the application **Answer:** - As Stored XSS into HTML context with nothing encoded, we just need choose any post we want and typing xss script on that like `<script>alert('xss')</script>` and yet we get it xss - Think about it you cause it on the popular website, :sweat: ### Impact of stored XSS attacks If an attacker can control a script that is executed in the victim's browser, then they can typically fully compromise that user. The attacker can carry out any of the actions that are applicable to the impact of reflected XSS vulnerabilities. In terms of exploitability, the key difference between reflected and stored XSS is that a stored XSS vulnerability enables attacks that are self-contained within the application itself. The attacker does not need to find an external way of inducing other users to make a particular request containing their exploit. Rather, the attacker places their exploit into the application itself and simply waits for users to encounter it. The self-contained nature of stored cross-site scripting exploits is particularly relevant in situations where an XSS vulnerability only affects users who are currently logged in to the application. If the XSS is reflected, then the attack must be fortuitously timed: a user who is induced to make the attacker's request at a time when they are not logged in will not be compromised. In contrast, if the XSS is stored, then the user is guaranteed to be logged in at the time they encounter the exploit. ### Stored XSS in different contexts There are many different varieties of stored cross-site scripting. The location of the stored data within the application's response determines what type of payload is required to exploit it and might also affect the impact of the vulnerability. In addition, if the application performs any validation or other processing on the data before it is stored, or at the point when the stored data is incorporated into responses, this will generally affect what kind of XSS payload is needed. ### How to find and test for stored XSS vulnerabilities Many stored XSS vulnerabilities can be found using Burp Suite's web vulnerability scanner. Testing for stored XSS vulnerabilities manually can be challenging. You need to test all relevant "entry points" via which attacker-controllable data can enter the application's processing, and all "exit points" at which that data might appear in the application's responses. Entry points into the application's processing include: * Parameters or other data within the URL query string and message body. * The URL file path. * HTTP request headers that might not be exploitable in relation to reflected XSS. * Any out-of-band routes via which an attacker can deliver data into the application. The routes that exist depend entirely on the functionality implemented by the application: a webmail application will process data received in emails; an application displaying a Twitter feed might process data contained in third-party tweets; and a news aggregator will include data originating on other web sites. The exit points for stored XSS attacks are all possible HTTP responses that are returned to any kind of application user in any situation. The first step in testing for stored XSS vulnerabilities is to locate the links between entry and exit points, whereby data submitted to an entry point is emitted from an exit point. The reasons why this can be challenging are that: * Data submitted to any entry point could in principle be emitted from any exit point. For example, user-supplied display names could appear within an obscure audit log that is only visible to some application users. * Data that is currently stored by the application is often vulnerable to being overwritten due to other actions performed within the application. For example, a search function might display a list of recent searches, which are quickly replaced as users perform other searches. To comprehensively identify links between entry and exit points would involve testing each permutation separately, submitting a specific value into the entry point, navigating directly to the exit point, and determining whether the value appears there. However, this approach is not practical in an application with more than a few pages. Instead, a more realistic approach is to work systematically through the data entry points, submitting a specific value into each one, and monitoring the application's responses to detect cases where the submitted value appears. Particular attention can be paid to relevant application functions, such as comments on blog posts. When the submitted value is observed in a response, you need to determine whether the data is indeed being stored across different requests, as opposed to being simply reflected in the immediate response. When you have identified links between entry and exit points in the application's processing, each link needs to be specifically tested to detect if a stored XSS vulnerability is present. This involves determining the context within the response where the stored data appears and testing suitable candidate XSS payloads that are applicable to that context. At this point, the testing methodology is broadly the same as for finding reflected XSS vulnerabilities. ## DOM-based cross-site scripting ### What is DOM-based cross-site scripting? DOM-based XSS vulnerabilities usually arise when JavaScript takes data from an attacker-controllable source, such as the URL, and passes it to a sink that supports dynamic code execution, such as eval() or innerHTML. This enables attackers to execute malicious JavaScript, which typically allows them to hijack other users' accounts. To deliver a DOM-based XSS attack, you need to place data into a source so that it is propagated to a sink and causes execution of arbitrary JavaScript. The most common source for DOM XSS is the URL, which is typically accessed with the window.location object. An attacker can construct a link to send a victim to a vulnerable page with a payload in the query string and fragment portions of the URL. In certain circumstances, such as when targeting a 404 page or a website running PHP, the payload can also be placed in the path. For a detailed explanation of the taint flow between sources and sinks, please refer to the [DOM-based vulnerabilities](https://portswigger.net/web-security/dom-based) page. ### How to test for DOM-based cross-site scripting The majority of DOM XSS vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner. To test for DOM-based cross-site scripting manually, you generally need to use a browser with developer tools, such as Chrome. You need to work through each available source in turn, and test each one individually. #### Testing HTML sinks To test for DOM XSS in an HTML sink, place a random alphanumeric string into the source (such as location.search), then use developer tools to inspect the HTML and find where your string appears. Note that the browser's "View source" option won't work for DOM XSS testing because it doesn't take account of changes that have been performed in the HTML by JavaScript. In Chrome's developer tools, you can use Control+F (or Command+F on MacOS) to search the DOM for your string. For each location where your string appears within the DOM, you need to identify the context. Based on this context, you need to refine your input to see how it is processed. For example, if your string appears within a double-quoted attribute then try to inject double quotes in your string to see if you can break out of the attribute. Note that browsers behave differently with regards to URL-encoding, Chrome, Firefox, and Safari will URL-encode location.search and location.hash, while IE11 and Microsoft Edge (pre-Chromium) will not URL-encode these sources. If your data gets URL-encoded before being processed, then an XSS attack is unlikely to work. #### Testing JavaScript execution sinks Testing JavaScript execution sinks for DOM-based XSS is a little harder. With these sinks, your input doesn't necessarily appear anywhere within the DOM, so you can't search for it. Instead you'll need to use the JavaScript debugger to determine whether and how your input is sent to a sink. For each potential source, such as location, you first need to find cases within the page's JavaScript code where the source is being referenced. In Chrome's developer tools, you can use Control+Shift+F (or Command+Alt+F on MacOS) to search all the page's JavaScript code for the source. Once you've found where the source is being read, you can use the JavaScript debugger to add a break point and follow how the source's value is used. You might find that the source gets assigned to other variables. If this is the case, you'll need to use the search function again to track these variables and see if they're passed to a sink. When you find a sink that is being assigned data that originated from the source, you can use the debugger to inspect the value by hovering over the variable to show its value before it is sent to the sink. Then, as with HTML sinks, you need to refine your input to see if you can deliver a successful XSS attack. #### [Testing for DOM XSS using DOM Invader](https://portswigger.net/burp/documentation/desktop/tools/dom-invader) Identifying and exploiting DOM XSS in the wild can be a tedious process, often requiring you to manually trawl through complex, minified JavaScript. If you use Burp's browser, however, you can take advantage of its built-in DOM Invader extension, which does a lot of the hard work for you. #### Exploiting DOM XSS with different sources and sinks In principle, a website is vulnerable to DOM-based cross-site scripting if there is an executable path via which data can propagate from source to sink. In practice, different sources and sinks have differing properties and behavior that can affect exploitability, and determine what techniques are necessary. Additionally, the website's scripts might perform validation or other processing of data that must be accommodated when attempting to exploit a vulnerability. There are a variety of sinks that are relevant to DOM-based vulnerabilities. Please refer to the list below for details. The document.write sink works with script elements, so you can use a simple payload, such as the one below: `document.write('... <script>alert(document.domain)</script> ...');` Note, however, that in some situations the content that is written to document.write includes some surrounding context that you need to take account of in your exploit. For example, you might need to close some existing elements before using your JavaScript payload. The innerHTML sink doesn't accept script elements on any modern browser, nor will svg onload events fire. This means you will need to use alternative elements like img or iframe. Event handlers such as onload and onerror can be used in conjunction with these elements. For example: `element.innerHTML='... <img src=1 onerror=alert(document.domain)> ...'` #### Sources and sinks in third-party dependencies Modern web applications are typically built using a number of third-party libraries and frameworks, which often provide additional functions and capabilities for developers. It's important to remember that some of these are also potential sources and sinks for DOM XSS. ##### DOM XSS in jQuery If a JavaScript library such as jQuery is being used, look out for sinks that can alter DOM elements on the page. For instance, jQuery's attr() function can change the attributes of DOM elements. If data is read from a user-controlled source like the URL, then passed to the attr() function, then it may be possible to manipulate the value sent to cause XSS. For example, here we have some JavaScript that changes an anchor element's href attribute using data from the URL: ``` $(function() { $('#backLink').attr("href",(new URLSearchParams(window.location.search)).get('returnUrl')); }); ``` You can exploit this by modifying the URL so that the location.search source contains a malicious JavaScript URL. After the page's JavaScript applies this malicious URL to the back link's href, clicking on the back link will execute it: `?returnUrl=javascript:alert(document.domain)` Another potential sink to look out for is jQuery's $() selector function, which can be used to inject malicious objects into the DOM. jQuery used to be extremely popular, and a classic DOM XSS vulnerability was caused by websites using this selector in conjunction with the location.hash source for animations or auto-scrolling to a particular element on the page. This behavior was often implemented using a vulnerable hashchange event handler, similar to the following: ``` $(window).on('hashchange', function() { var element = $(location.hash); element[0].scrollIntoView(); }); ``` As the hash is user controllable, an attacker could use this to inject an XSS vector into the $() selector sink. More recent versions of jQuery have patched this particular vulnerability by preventing you from injecting HTML into a selector when the input begins with a hash character (#). However, you may still find vulnerable code in the wild. To actually exploit this classic vulnerability, you'll need to find a way to trigger a hashchange event without user interaction. One of the simplest ways of doing this is to deliver your exploit via an iframe: `<iframe src="https://vulnerable-website.com#" onload="this.src+='<img src=1 onerror=alert(1)>'">` In this example, the src attribute points to the vulnerable page with an empty hash value. When the iframe is loaded, an XSS vector is appended to the hash, causing the hashchange event to fire. ##### DOM XSS in AngularJS If a framework like AngularJS is used, it may be possible to execute JavaScript without angle brackets or events. When a site uses the ng-app attribute on an HTML element, it will be processed by AngularJS. In this case, AngularJS will execute JavaScript inside double curly braces that can occur directly in HTML or inside attributes. #### DOM XSS combined with reflected and stored data Some pure DOM-based vulnerabilities are self-contained within a single page. If a script reads some data from the URL and writes it to a dangerous sink, then the vulnerability is entirely client-side. However, sources aren't limited to data that is directly exposed by browsers - they can also originate from the website. For example, websites often reflect URL parameters in the HTML response from the server. This is commonly associated with normal XSS, but it can also lead to reflected DOM XSS vulnerabilities. In a reflected DOM XSS vulnerability, the server processes data from the request, and echoes the data into the response. The reflected data might be placed into a JavaScript string literal, or a data item within the DOM, such as a form field. A script on the page then processes the reflected data in an unsafe way, ultimately writing it to a dangerous sink. `eval('var data = "reflected string"');` Websites may also store data on the server and reflect it elsewhere. In a stored DOM XSS vulnerability, the server receives data from one request, stores it, and then includes the data in a later response. A script within the later response contains a sink which then processes the data in an unsafe way. `element.innerHTML = comment.author` #### Which sinks can lead to DOM-XSS vulnerabilities? The following are some of the main sinks that can lead to DOM-XSS vulnerabilities: ``` document.write() document.writeln() document.domain element.innerHTML element.outerHTML element.insertAdjacentHTML element.onevent ``` The following jQuery functions are also sinks that can lead to DOM-XSS vulnerabilities: ``` add() after() append() animate() insertAfter() insertBefore() before() html() prepend() replaceAll() replaceWith() wrap() wrapInner() wrapAll() has() constructor() init() index() jQuery.parseHTML() $.parseHTML() ``` #### How to prevent DOM-XSS vulnerabilities In addition to the general measures described on the [DOM-based vulnerabilities](https://portswigger.net/web-security/dom-based) page, you should avoid allowing data from any untrusted source to be dynamically written to the HTML document. ## What can XSS be used for? An attacker who exploits a cross-site scripting vulnerability is typically able to: * Impersonate or masquerade as the victim user. * Carry out any action that the user is able to perform. * Read any data that the user is able to access. * Capture the user's login credentials. * Perform virtual defacement of the web site. * Inject trojan functionality into the web site. ## Impact of XSS vulnerabilities The actual impact of an XSS attack generally depends on the nature of the application, its functionality and data, and the status of the compromised user. For example: * In a brochureware application, where all users are anonymous and all information is public, the impact will often be minimal. * In an application holding sensitive data, such as banking transactions, emails, or healthcare records, the impact will usually be serious. * If the compromised user has elevated privileges within the application, then the impact will generally be critical, allowing the attacker to take full control of the vulnerable application and compromise all users and their data. ## How to find and test for XSS vulnerabilities The vast majority of XSS vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner. Manually testing for reflected and stored XSS normally involves submitting some simple unique input (such as a short alphanumeric string) into every entry point in the application, identifying every location where the submitted input is returned in HTTP responses, and testing each location individually to determine whether suitably crafted input can be used to execute arbitrary JavaScript. In this way, you can determine the context in which the XSS occurs and select a suitable payload to exploit it. Manually testing for DOM-based XSS arising from URL parameters involves a similar process: placing some simple unique input in the parameter, using the browser's developer tools to search the DOM for this input, and testing each location to determine whether it is exploitable. However, other types of DOM XSS are harder to detect. To find DOM-based vulnerabilities in non-URL-based input (such as document.cookie) or non-HTML-based sinks (like setTimeout), there is no substitute for reviewing JavaScript code, which can be extremely time-consuming. Burp Suite's web vulnerability scanner combines static and dynamic analysis of JavaScript to reliably automate the detection of DOM-based vulnerabilities. ## Content security policy Content security policy ([CSP](https://portswigger.net/web-security/cross-site-scripting/content-security-policy)) is a browser mechanism that aims to mitigate the impact of cross-site scripting and some other vulnerabilities. If an application that employs CSP contains XSS-like behavior, then the CSP might hinder or prevent exploitation of the vulnerability. Often, the CSP can be circumvented to enable exploitation of the underlying vulnerability. ## [Dangling markup injection](https://portswigger.net/web-security/cross-site-scripting/dangling-markup) Dangling markup injection is a technique that can be used to capture data cross-domain in situations where a full cross-site scripting exploit is not possible, due to input filters or other defenses. It can often be exploited to capture sensitive information that is visible to other users, including CSRF tokens that can be used to perform unauthorized actions on behalf of the user. ## [How to prevent XSS attacks](https://portswigger.net/web-security/cross-site-scripting/preventing) Preventing cross-site scripting is trivial in some cases but can be much harder depending on the complexity of the application and the ways it handles user-controllable data. In general, effectively preventing XSS vulnerabilities is likely to involve a combination of the following measures: * Filter input on arrival. At the point where user input is received, filter as strictly as possible based on what is expected or valid input. * Encode data on output. At the point where user-controllable data is output in HTTP responses, encode the output to prevent it from being interpreted as active content. Depending on the output context, this might require applying combinations of HTML, URL, JavaScript, and CSS encoding. * Use appropriate response headers. To prevent XSS in HTTP responses that aren't intended to contain any HTML or JavaScript, you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend. * Content Security Policy. As a last line of defense, you can use Content Security Policy (CSP) to reduce the severity of any XSS vulnerabilities that still occur. ## Common questions about cross-site scripting How common are XSS vulnerabilities? XSS vulnerabilities are very common, and XSS is probably the most frequently occurring web security vulnerability. How common are XSS attacks? It is difficult to get reliable data about real-world XSS attacks, but it is probably less frequently exploited than other vulnerabilities. What is the difference between XSS and CSRF? XSS involves causing a web site to return malicious JavaScript, while CSRF involves inducing a victim user to perform actions they do not intend to do. What is the difference between XSS and SQL injection? XSS is a client-side vulnerability that targets other application users, while SQL injection is a server-side vulnerability that targets the application's database. How do I prevent XSS in PHP? Filter your inputs with a whitelist of allowed characters and use type hints or type casting. Escape your outputs with htmlentities and ENT_QUOTES for HTML contexts, or JavaScript Unicode escapes for JavaScript contexts. How do I prevent XSS in Java? Filter your inputs with a whitelist of allowed characters and use a library such as Google Guava to HTML-encode your output for HTML contexts, or use JavaScript Unicode escapes for JavaScript contexts # Pratice DOM XSS (PortSwigger) ## LAB: DOM XSS in `document.write` sink using source `location.search` with SVG tag - So the lab require we cause alert() funtion to perform xss - First we take a look about website and it contain search box and other post like blog so we can access this post and try cause XSS on comment box like this ![](https://i.imgur.com/63h8gqn.png) but it know perform xss like this not work so take back the home and check form search - One thing if we type anything it on that it will show data what querry we find so that can make or do xss payload ![](https://i.imgur.com/lpAV2qJ.png) - So we can try typing a payload like this to searchbox `"><svg onload=alert(1)>` and it will post alert box cause xss - So i will explaint it, so when we typing like that svg tag have the onload function we can embed on website and cause alert XSS so it will cause that on the `<h1>` tag it contait quote para `''` so we can add string but not string and cause xss through svg tag so let me take look with script but i think it will not work because we can expect add script tag on body so we can have same xss payload with many situation like this ![](https://i.imgur.com/DcjLYxX.png) ## Lab: DOM XSS in innerHTML sink using source location.search - It such like above lab but we will do DOM XSS with div and content on that let take a look - Website like normal but contain search box so let dump that with some payload like xss but first typing alphabet or numberic to check what website return for us ![](https://i.imgur.com/rfpuIsc.png) - So it have litte bit diff from with seperate content input in search box so we need to do with searchMessage take a look some JS and i think it will cause some thing fun - So it relate with `<img>` to cause some XSS with innerHTML so payload will like this `<img src=a onerror='alert();'>` on [this](https://stackoverflow.com/questions/30661497/xss-prevention-and-innerhtml) - ![](https://i.imgur.com/7F7B3vY.png) i think it will work but not so add onerror i think it the tag notice for us to catch the err if img tag not find anything, isn't right ? :sweat_smile: and it work if we replace onerror by somestring but not work i think it will cause if we do it function and alert on on that thing and take a look [this](https://www.w3schools.com/jsref/event_onerror.asp) ## XSS Jquerry: Lab: DOM XSS in jQuery anchor href attribute sink using location.search source - Cause alert cookie is targer of lab and as jquery we will add $ quote and take do function and change it href on location.search it will be again search box :smile: - ![](https://i.imgur.com/XSVZVya.png) oh i am wrong it just the submit feedback and it will do some thing on message box with some thing cause like this ``` $(function() { $('#backLink').attr("href",(new URLSearchParams(window.location.search)).get('returnUrl')); }); ``` and if we click on that link we generate it will do this stuff like return js and done we cause alert - We just first i not see the on the URL and focus message but it not have anything so when take a look like this `https://0ac4007c0462b327c02c037f00ae00d9.web-security-academy.net/feedback?returnPath=/` so kind is strage so i put some thing on to after slash and yet it update for this href on the back href. So with that we can do javascript on that by payload like this and it will cause XSS `https://0ac4007c0462b327c02c037f00ae00d9.web-security-academy.net/feedback?returnPath=javascript:alert('xss')` and okay we have resolve of lab. ## Lab: DOM XSS in jQuery selector sink using a hashchange event - Description the lab: his lab contains a DOM-based cross-site scripting vulnerability on the home page. It uses jQuery's $() selector function to auto-scroll to a given post, whose title is passed via the location.hash property. - To solve the lab, deliver an exploit to the victim that calls the print() function in their browse - Take a look back on DOM we can find the style of code like this and need to do some iframe or some king to return XSS alert and print that to cause XSS ![](https://i.imgur.com/wmhwarb.png) - ![](https://i.imgur.com/tAs1iiO.png) the server we need to exploit and ship that to victim so it containt HTTPS check file HEAD and BODY so it like return web page to that so gen some XSS and make victim cause that i think it target of lab - Payload need iframe tag it is relave about the way to exploit that and payload will like `<iframe src="https://exploit-0a13001503a04799c0eb1e960120001a.web-security-academy.net" onload="this.src+='<img src=1 onerror=print()>'"></iframe>` store and view it will cause the print() function that funtion for print of web page and yet, take back a lab and we get resolve of this LAB ##