SQL Injection

Here is a clear, safe, and practical guide to SQL Injection, including what it is, how it works, and how to prevent it in real-world systems.

https://www.spanning.com/blog/sql-injection-attacks-web-based-application-security-part-4/SQL-injection-attack-example.png

⚠️ What Is SQL Injection?

SQL Injection (SQLi) is a critical security vulnerability that allows attackers to inject malicious SQL code into a query, often leading to:

  • Unauthorized data access

  • Data modification or deletion

  • Authentication bypass

  • Complete database takeover

SQL Injection occurs when user input is incorrectly handled and gets executed as SQL.


❌ Example of Vulnerable (Insecure) Code

SELECT * FROM users WHERE username = '$username' AND password = '$password';

If an attacker enters:

' OR '1'='1

The resulting query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1';

✔ Always TRUE → attacker logs in without a password.


🎯 Types of SQL Injection

1. Classic (In-band) SQL Injection

Directly manipulates SQL queries.

2. Blind SQL Injection

Database errors/results are hidden, so attackers infer information slowly.

3. Boolean-based Blind SQLi

Returns different pages based on TRUE/FALSE.

4. Time-based Blind SQLi

Uses delays (SLEEP(5)) to infer TRUE/FALSE.

5. Out-of-band SQL Injection

Uses external channels (DNS, HTTP callbacks).


🛡 How to Prevent SQL Injection (Best Practices)

1️⃣ Use Prepared Statements (Parameterized Queries)

This is the #1 recommended defense.

Example (MySQL, PostgreSQL, SQL Server)

SELECT * FROM users WHERE username = ? AND password = ?;

Example (PHP PDO)

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :u AND password = :p");
$stmt->execute([':u' => $username, ':p' => $password]);

✔ User input is treated as data, not executable code.


2️⃣ Use Stored Procedures Safely

CREATE PROCEDURE GetUser (@username NVARCHAR(50))
AS
BEGIN
SELECT * FROM users WHERE username = @username;
END;

(Still requires parameterization—stored procedures alone don’t guarantee safety.)


3️⃣ Validate and Sanitize Input

  • Accept only expected characters (e.g., alphanumeric)

  • Reject unexpected characters (', ", ;, --, etc.)

  • Enforce strong data types


4️⃣ Apply the Principle of Least Privilege

Use database accounts with minimal rights:

  • No DROP permissions

  • No ALTER permissions

  • No access to unnecessary tables


5️⃣ Disable Detailed Error Messages

Error messages can reveal:

  • Table names

  • Column names

  • SQL syntax

  • Database version

Use generic error messages in production.


6️⃣ Use ORM Frameworks (Safely)

Frameworks like:

  • Hibernate

  • Entity Framework

  • Sequelize

  • Django ORM

These automatically parameterize queries—but avoid raw SQL without placeholders.


7️⃣ Web Application Firewall (WAF)

A WAF can block common SQL Injection payloads before they reach the application.


🔥 Real-World Attack Examples (Educational Only)

Authentication Bypass

' OR 1=1 --

Dump all data from a table

' UNION SELECT * FROM users --

Blind timing attack

' OR IF(1=1, SLEEP(5), 0) --

⚠️ Never try these on systems you don’t own—illegal and unethical.
Use them only in security labs or test environments.


📌 How to Test for SQL Injection (Safely)

Use tools like:

  • Burp Suite

  • sqlmap (in authorized pentests only)

  • OWASP ZAP

And refer to OWASP SQL Injection Prevention Cheat Sheet.


🧠 Summary of Best Practices (Quick Checklist)

✔ Always use prepared statements
✔ Validate and sanitize input
✔ Avoid dynamic SQL and string concatenation
✔ Limit database permissions
✔ Hide SQL errors in production
✔ Use modern frameworks and ORMs
✔ Implement logging + monitoring
✔ Use WAF or intrusion detection systems

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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