Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 52

Exploiting Second-Order SQL Injection

Recommended resources

In our previous lesson, we established the theoretical foundation for second-order SQL injection, defining it as a two-stage attack where a malicious payload is stored in the database and executed later by a different application function. You learned that the core vulnerability stems from a developer's misplaced trust in data retrieved from their own database.

Today, we transition from theory to practice. This lesson is designed to be highly hands-on, guiding you through the process of actively exploiting a second-order vulnerability. We will identify the distinct injection and trigger points in a sample application, craft payloads to manipulate the application's behavior, and even explore how automation tools can be adapted for these complex attacks.

Identifying the Attack Surface

The first step in exploiting a second-order vulnerability is to map out the application's data flow. You must identify two key components:

  1. The Injection Point: A feature where the application accepts user input and stores it in the database. Examples include user registration, profile updates, comment sections, or user preference settings.
  2. The Trigger Point: A separate feature that retrieves the stored data and uses it to construct a new SQL query without proper sanitization. This could be a user dashboard, a search result page, or a report generation module.

The vulnerability exists in the disconnect between how data is written and how it's read. A developer might securely save data using parameterized queries but then carelessly retrieve and use it with insecure string concatenation.

The flowchart below, taken from a real-world vulnerability in a WordPress plugin, perfectly illustrates a more subtle form of this attack.

This diagram shows a second-order SQL injection. A user with 'Contributor' privileges stores a malicious payload in a post's metadata. The key is stored as-is, while the value is escaped. Later, an admin duplicates the post, triggering a process that reads all metadata. The application loops through the key-value pairs, unsafely concatenating the **key** into a new query, leading to SQL injection. The value, which was properly escaped, is handled safely.

Notice the critical detail: the application safely handles the meta_value by escaping it. However, it blindly trusts the meta_key and concatenates it directly into a new SELECT statement. This is a classic second-order injection pattern, exploiting a blind spot in the developer's security logic.


Crafting and Executing a Simple Second-Order Attack

Let's walk through a practical exploitation scenario. The most straightforward way to confirm a second-order vulnerability is to inject a simple payload that breaks the query at the trigger point and observe the application's response.

Second Order SQL-Injection on HTB Nightmare - 0xdf hacks stuff

This article from the blog '0xdf hacks stuff' provides an excellent, practical walkthrough of identifying and confirming a second-order SQLi vulnerability on a sample application.

Please read the first two sections: The introduction to Second Order SQL Injection, which recaps the concept in the context of this specific example. The Proof-of-Concept (POC) section, focusing on how a maliciously crafted username causes an error on a different page.

As the article demonstrates, the attack unfolds in two clear steps:

  • Stage 1 (Injection): The attacker navigates to register.php and creates a user with a malicious username, such as attacker'--. The application stores this username in the users table. At this point, nothing breaks.
  • Stage 2 (Trigger): The attacker logs in. The application, likely on the user's dashboard (notes.php in the example), attempts to fetch data related to the user with a query like SELECT * FROM notes WHERE username = 'attacker'--';. The injected -- comments out the rest of the query, causing an error or unexpected behavior, confirming the vulnerability.

The key is that the vulnerability is not on the registration page, but on the notes page, which consumes the data stored by the registration page.


From Error to Exfiltration: Key-Based Injection

The previous example injected into a simple data value. As we saw in the WordPress flowchart, the injection point can also be a field name or a key. This is often harder to spot but can be just as devastating. Let's look at a video where an analyst discovers such a vulnerability by examining the application's source code.

advanced SQL injection

This video by Loi Liang Yang demonstrates an advanced SQL injection in the Drupal CMS. The presenter analyzes the source code to find the vulnerability.

Please watch the following segments: Source Code Analysis: The presenter examines the Drupal source code (database.inc) and identifies the expand_arguments function. Notice how the code iterates through an array and uses the key to reconstruct a query. This is the vulnerable pattern. Crafting the Payload: The presenter uses the browser's developer tools to modify the name attribute of an HTML input field. This name attribute becomes the array key on the server side. By injecting SQL into this attribute, they successfully update a record in the database. This demonstrates a powerful analysis technique: when you suspect a second-order vulnerability, look for code that dynamically builds queries from stored configuration data, metadata, or other non-obvious inputs, not just user-provided values.


Blind Second-Order Injection and Out-of-Band Exfiltration

What if the trigger point doesn't display any output or errors? In this case, we are dealing with a blind second-order SQL injection. We must use the out-of-band (OOB) techniques you've seen before, but adapted to this two-stage attack model. The goal is to craft a payload that, when executed at the trigger point, forces the database to send information to an external server you control.

Exploiting Second Order SQL Injection with Stored Procedures

This NetSPI blog post details a sophisticated attack combining second-order injection with DNS-based data exfiltration against an MS-SQL database.

Please study the following sections to understand the methodology: Introduction and The Vulnerability: This sets the scene, describing a report export feature as the vector. Detection: This is a critical section. Pay close attention to how the analyst confirms the vulnerability. They send a request with a malicious payload (Stage 1), get a report ID, and then use that ID in a second request (Stage 2). A payload with an unbalanced quote causes the second request to fail (500 error), while a balanced one succeeds (200 OK). This differential response confirms the blind injection. Exploitation: This section introduces the use of xp_dirtree in MS-SQL to force a DNS lookup to a controlled domain. Exfiltration via Subdomain: This shows how to embed the results of database functions like DB_NAME() into the subdomain of the DNS request, allowing you to exfiltrate data.

This approach is powerful because it works even when you get no direct feedback from the application. The process is:

  1. Inject a payload in Stage 1 that includes a command to make a network request (e.g., xp_dirtree in MS-SQL, UTL_HTTP.REQUEST in Oracle).
  2. The payload should construct a hostname where a subdomain contains the data you want to steal (e.g., (SELECT a.username FROM users a LIMIT 1).your-server.com).
  3. Trigger the execution in Stage 2.
  4. Monitor your DNS server logs for incoming requests. The requested subdomain is your exfiltrated data.

Automating the Attack with sqlmap

Manually performing these multi-step attacks can be tedious. While sqlmap is primarily designed for first-order injections, it can be adapted for second-order attacks with some customization. This usually involves telling sqlmap where the injection happens and where to look for the result.

The 0xdf hacks stuff article you read earlier contains a detailed guide on this.

Second Order SQL-Injection on HTB Nightmare - 0xdf hacks stuff

Let's return to the '0xdf hacks stuff' article to see how this manual process can be automated.

Please read the following sections: Getting It to Work: This explains why a standard sqlmap run will fail and outlines the necessary steps. Tamper Script: Study the Python tamper script. The tamper function is the key; sqlmap calls it for every payload. This script intercepts the payload and uses it to perform the Stage 1 action (creating an account) before letting sqlmap proceed with Stage 2. sqlmap Command Line: Analyze the command used. The most important flags are --tamper, which loads the custom Python script, and --second-order, which tells sqlmap which URL to visit to check for the result of the injection after the initial request is made.

This advanced use of sqlmap is a powerful technique for a security analyst. It bridges the gap between manual discovery and automated exploitation for complex vulnerability classes.


Conclusion

You have now moved beyond the theory of second-order SQL injection and into practical execution. You have seen how to identify the two-stage pattern, craft payloads for both direct and blind scenarios, and even automate the attack.

Key Takeaways:

  • Exploitation requires two steps: First, store a payload via one application feature. Second, trigger its execution via another.
  • Confirmation is key: You can confirm a vulnerability by observing errors, unexpected output, or differential responses (e.g., 200 OK vs. 500 error) at the trigger point.
  • Payloads are versatile: Your payload can be injected into data values, keys, or any other information that is stored and later used in a query.
  • Blind OOB is effective: When there is no direct output, use out-of-band techniques like DNS exfiltration to steal data.
  • Automation is possible: Tools like sqlmap can be adapted for second-order attacks using features like the --second-order flag and custom tamper scripts.

In our next lesson, we will explore another powerful post-exploitation technique: using a confirmed SQL injection vulnerability to read and exfiltrate files directly from the underlying server's file system, provided the database user has sufficient privileges.