Reflected XSS is a type of XSS vulnerability where a malicious script is reflected to the user’s browser, often via a crafted URL or form submission. Consider a search query containing <script>alert(document.cookie)</script>; many users wouldn’t be suspicious about such a URL, even if they look at it up close. If processed by a vulnerable web application, it will be executed within the context of the user’s browser.
In this innocuous example, it displays the cookie in an alert box. Obviously, an attacker wants to achieve more than just displaying the cookie as an alert to the user. However, for such an attack to be possible, we need a vulnerable application.
Vulnerable Web Application
One simple reflected XSS vulnerability is when the user searches for some term, and the search string is included verbatim in the results page. This simple scenario provides an easy target for the attacker to exploit.
Although discovering such vulnerabilities is not always easy, fixing them is straightforward. User input such as <script>alert('XSS')</script> should be santized or HTML-encoded to <script>alert('XSS')</script>.
In the following subsections, we provide examples of vulnerable code in the following languages and frameworks:
- PHP
- JavaScript (Node.js)
- Python (Flask)
- C# (ASP.NET)
PHP
Vulnerable code
Look at the following code snippet in PHP and figure out why it might be vulnerable to reflected XSS.
<?php
$search_query = $_GET['q'];
echo "<p>You searched for: $search_query</p>";
?>
If you are unfamiliar with PHP, $_GET is a PHP array containing values from the URL query string. Furthermore, $_GET['q'] refers to the query string parameter q. For example, in http://shop.thm/search.php?q=table, $_GET['q'] has the value table.
As you might have guessed, the vulnerability is caused by the search value displayed on the result page without sanitization. Therefore, an attacker can add a malicious script to the URL, knowing it would be executed. For example, as a proof of concept, the following URL can be tested: http://shop.thm/search.php?q=<script>alert(document.cookie)</script> and if the site is vulnerable, an alert box will appear displaying the user’s cookie.
Fixed code
Luckily, fixing this code is simple.
<?php
$search_query = $_GET['q'];
$escaped_search_query = htmlspecialchars($search_query);
echo "<p>You searched for: $escaped_search_query</p>";
?>
The PHP function htmlspecialchars() converts special characters to HTML entities. The characters <, >, &, ", ' are replaced by default to prevent scripts in the input from executing. You can read its documentation here.
JavaScript (Node.js)
Vulnerable code
The following Node.js code snippet is vulnerable to reflected XSS. Try to find the vulnerable part and think of a solution.
const express = require('express');
const app = express();
app.get('/search', function(req, res) {
var searchTerm = req.query.q;
res.send('You searched for: ' + searchTerm);
});
app.listen(80);
If you are unfamiliar with Node.js, the code snippet above uses Express, a popular web application framework for Node.js. The req.query.q will extract the value of q. For example, in http://shop.thm/search?q=table, req.query.q has the value table. Finally, the response is generated by appending the search term provided by the user to “You searched for:”.
Because the value is taken from the user and inserted in the response HTML without sanitization or escaping, it is easy to append a malicious query. As a proof of concept, we can test the following URL: http://shop.thm/search?q=<script>alert(document.cookie)</script>, and if the site is vulnerable, an alert box will appear displaying the user’s cookie.
Fixed code
const express = require('express');
const sanitizeHtml = require('sanitize-html');
const app = express();
app.get('/search', function(req, res) {
const searchTerm = req.query.q;
const sanitizedSearchTerm = sanitizeHtml(searchTerm);
res.send('You searched for: ' + sanitizedSearchTerm);
});
app.listen(80);
The solution is achieved by using the sanitizeHtml() from the sanitize-html library. This function removes unsafe elements and attributes. This includes removing script tags, among other elements that could be used for malicious purposes. You can read its documentation here.
Another approach would be by using the escapeHtml() function instead of the sanitizeHtml() function. As the name indicates, the escapeHtml() function aims to escape characters such as <, >, &, ", and '. You can check its homepage here.
Python (Flask)
Vulnerable code
Consider the following simple Flask application. Try to find the vulnerable part.
from flask import Flask, request
app = Flask(__name__)
@app.route("/search")
def home():
query = request.args.get("q")
return f"You searched for: {query}!"
if __name__ == "__main__":
app.run(debug=True)
If you are unfamiliar with Flask, request.args.get() is used to access query string parameters from the request URL. In fact, request.args contains all the query string parameters in a dictionary-like object. For example, in http://shop.thm/search?q=table, request.args.get("q") has the value table.
Because the value is taken from the user and inserted in the response HTML without sanitization or escaping, it is easy to append a malicious query. As a proof of concept, we can test the following URL: http://shop.thm/search?q=<script>alert(document.cookie)</script>, and if the site is vulnerable, an alert box will appear displaying the user’s cookie.
Fixed code
from flask import Flask, request
from html import escape
app = Flask(__name__)
@app.route("/search")
def home():
query = request.args.get("q")
escaped_query = escape(query)
return f"You searched for: {escaped_query}!"
if __name__ == "__main__":
app.run(debug=True)
The main change is that the user input is now escaped using the escape() function from the html module. Note that the html.escape() function in Flask is actually an alias for markupsafe.escape(). They both come from the Werkzeug library and serve the same purpose: escaping unsafe characters in strings. This function converts characters like <, >, ", ' to HTML escaped entities, disarming any malicious code the user has inserted.
ASP.NET
Vulnerable code
The code snippet below is created using ASP.NET C#.
public void Page_Load(object sender, EventArgs e)
{
var userInput = Request.QueryString["q"];
Response.Write("User Input: " + userInput);
}
If you are unfamiliar with ASP.NET and C#, the code above uses Request.QueryString, which returns a collection of associated string keys and values. In the example above, we are interested in the value associated with the key q, and we save it in the variable userInput. Finally, the response is created by appending the userInput to another string.
Fixed code
using System.Web;
public void Page_Load(object sender, EventArgs e)
{
var userInput = Request.QueryString["q"];
var encodedInput = HttpUtility.HtmlEncode(userInput);
Response.Write("User Input: " + encodedInput);
}
Again, the solution lies in encoding the user input into HTML-safe strings. ASP.NET C# provides the HttpUtility.HtmlEncode() method, which converts various characters, such as <, >, and &, into their respective HTML entity encoding.