Network Security SQL Injection

SQL Injection (SQLi) is one of the oldest and most damaging web application vulnerabilities. It occurs when an attacker inserts malicious SQL code into an input field that a web application passes to a database. If the application fails to properly validate and sanitize input, the database executes the attacker's code instead of the intended query. The result can be complete database compromise — theft, modification, or deletion of every record.

How a Database Query Normally Works

When you log into a website, the application sends your username and password to the database in a query to check if they match:

Login form: Username: alice   Password: sunshine2020

Application builds this SQL query:
SELECT * FROM users WHERE username='alice' AND password='sunshine2020'

Database finds alice's record with that password → returns user data
Application: Login successful

How SQL Injection Breaks the Query

An attacker enters malicious text in the username field instead of a real username:

Username: admin'--
Password: (anything)

Application builds:
SELECT * FROM users WHERE username='admin'--' AND password='anything'

SQL comment "--" causes everything after it to be ignored:
SELECT * FROM users WHERE username='admin'

Database finds the admin user and returns their record.
No password check was ever performed.
Attacker is now logged in as admin.

Types of SQL Injection

In-Band SQLi (Classic)

The attacker receives results directly in the application response. This is the most common type. The attacker sees database output in the web page itself.

Attack:
Username: ' OR '1'='1

Application builds:
SELECT * FROM users WHERE username='' OR '1'='1'

Since '1'='1' is always true, the query returns ALL user records.
If the application shows the first result: attacker sees admin account.

Union-Based SQLi

The attacker uses the UNION SQL operator to append a second query that extracts data from other tables — including tables the application was never designed to expose.

Attack in a product search field:
?id=1 UNION SELECT username, password, 3 FROM users--

Application query becomes:
SELECT name, price, stock FROM products WHERE id=1
UNION
SELECT username, password, 3 FROM users--

Result displayed in the product list area:
"admin | $2b$12$hashedpassword | 3"
"alice | $2b$12$alicehash | 3"

Attacker just retrieved the entire user table.

Blind SQLi

The application does not display database output directly, but the attacker can still extract data by asking true/false questions and observing differences in application behavior (different response time, different error, different page content).

Boolean-based blind SQLi:
?id=1 AND 1=1  → page loads normally (true condition)
?id=1 AND 1=2  → page shows error or is empty (false condition)

Attacker asks:
?id=1 AND SUBSTRING(username,1,1)='a'  → normal page → first char is 'a'
?id=1 AND SUBSTRING(username,2,1)='d'  → normal page → second char is 'd'
?id=1 AND SUBSTRING(username,3,1)='m'  → normal page → third char is 'm'

Letter by letter, attacker extracts 'admin'.
Slow but effective against databases that do not display errors.

Time-Based Blind SQLi

The attacker injects a command that causes the database to pause for a set time if a condition is true. By measuring the response time, the attacker learns information one bit at a time.

MySQL example:
?id=1; IF(1=1, SLEEP(5), 0)--

If response takes 5 seconds: condition was true.
If response is instant: condition was false.

Attacker measures time to extract data:
?id=1; IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0)--
→ Response takes 5 seconds → first character is 'a'.

What Attackers Can Do with SQLi

Capability                   | Impact
-----------------------------|-------------------------------------------
Read all database tables     | Complete data theft (users, passwords, PII)
Bypass login authentication  | Admin access without knowing passwords
Modify or delete records     | Data integrity destroyed
Insert data                  | Plant fake records, create admin accounts
Read server files            | Access config files, source code (some DBs)
Execute OS commands          | Full server compromise (some DBs with xp_cmdshell)

Defenses Against SQL Injection

Parameterized Queries (Prepared Statements)

The most effective defense. The application sends the SQL structure and the user data separately. The database never interprets user input as code — it is always treated as a data value.

VULNERABLE CODE (string concatenation):
query = "SELECT * FROM users WHERE username='" + username + "'"

Attacker input: admin'--
Result:         SELECT * FROM users WHERE username='admin'-- ← injected!

SAFE CODE (parameterized query):
query = "SELECT * FROM users WHERE username = ?"
execute(query, [username])

Attacker input: admin'--
Result:         The database looks for a user literally named "admin'--"
                No such user → login fails safely
                SQL injection is impossible.

Stored Procedures

Pre-written database procedures that accept parameters safely. They separate code from data the same way parameterized queries do.

Input Validation and Sanitization

Reject any input that contains SQL keywords or special characters where they are not expected. A username field should contain only letters, numbers, and underscores — block apostrophes, dashes, semicolons, and comment characters at the application layer.

Least Privilege Database Accounts

The web application's database account should have only the permissions it needs. A login query needs only SELECT on the users table. An attacker who achieves SQLi through that account cannot DROP tables, read other databases, or execute OS commands.

Web Application Firewall (WAF)

A WAF detects and blocks common SQLi patterns in HTTP requests. It provides an additional layer but should not replace proper parameterized queries — WAFs can be bypassed with obfuscated attack strings.

Defense Priority:
1. Parameterized queries in ALL database interactions ← mandatory
2. Stored procedures where appropriate
3. Input validation and sanitization
4. Least privilege database accounts
5. WAF as supplementary layer
6. Regular security testing (penetration testing, DAST tools)

SQL Injection consistently appears in the OWASP Top 10 most critical web application security risks. Despite being a well-understood, decades-old vulnerability with straightforward fixes, SQLi continues to enable major breaches because developers build applications without security training or code review. Parameterized queries are non-negotiable in any production application that uses a database.

Leave a Comment

Your email address will not be published. Required fields are marked *