Second Order Injections

Introduction

Second-Order SQL Injection is a type of SQL injection attack where the malicious payload is stored in the database and executed later, during a different database operation. Unlike traditional SQL injection, where the attack is immediate, second-order attacks exploit stored data, making detection more challenging.

Table of Contents

How to identify

To identify Second-Order SQL Injection vulnerabilities, look for places where user inputs are stored and later used in SQL queries. Indicators include:

  1. Data Storage Points: Inputs that are stored in the database, such as user profiles or comments.

  2. Subsequent Queries: Later queries that use stored data without proper sanitization.

  3. Manual Testing: Injecting benign data and later manipulating it in different parts of the application to observe any anomalies.

Example:

User registration with username: ' OR '1'='1

If the application later uses this username in another query without sanitization, it may be vulnerable.

  1. Code analysis: When the source code is provided look for php code that doesn't sanitize the input. Here is an example of a vulnerable PHP code snippet:

<?php
// Registration
$username = $_POST['username'];
$query = "INSERT INTO users (username) VALUES ('$username')";
mysqli_query($conn, $query);

// Profile update
$id = $_SESSION['user_id'];
$new_email = $_POST['email'];
$query = "UPDATE users SET email = '$new_email' WHERE id = $id";
mysqli_query($conn, $query);
?>

Code/tools/websites

Tools

  • SQLMap: An automated tool for SQL injection and database takeover.

  • Burp Suite: A web vulnerability scanner with tools for manual testing.

  • Havij: An automated SQL injection tool.

Websites

  • PortSwigger Web Security Academy: Offers labs and exercises to practice SQL injection techniques.

  • HackTheBox Previous Contests: They are a great way to learn by practicing question have come in real CTFs.

Sample problem

Problem Statement

You are given access to a web application with a user registration and profile update feature. The URLs are:

http://example.com/register.php
http://example.com/profile.php

Identify if the application is vulnerable to Second-Order SQL Injection and update the email of a different user.

Solution

Click to reveal the solution
  1. Register a user with an SQL injection payload:

    Username: ' OR '1'='1
  2. Observe if the application allows this registration and stores the payload.

  3. Exploit the stored payload during profile update:

    Email: example@example.com' WHERE id=2; --

References

Conclusion

Second-Order SQL Injection targets stored data that is later used in SQL queries, making it harder to detect. Identifying these vulnerabilities involves understanding data flow and storage in the application.

Last updated