ScyScan Blog

Preventing SQL Injection: Essential Defense Tactics for Web Developers

SQL Injection

What is SQL Injection?

SQL Injection (CWE-89) occurs when attackers manipulate your database queries by injecting malicious SQL code through user inputs. It’s one of the most critical web vulnerabilities, enabling data theft, deletion, or full system compromise. The Open Web Application Security Project (OWASP) consistently ranks it among the top web risks.

How SQL Injection Works

Consider this unsafe PHP code:

1
2
$user = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$user'";

An attacker could input ' OR '1'='1 – turning your query into:

1
SELECT * FROM users WHERE username = '' OR '1'='1'

This returns all user records, exposing sensitive data.

Prevention Strategies

1. Use Parameterized Queries (Prepared Statements)

The #1 defense. Separate SQL logic from data using placeholders:

1
2
# Python (SQLite example)
cursor.execute("SELECT * FROM users WHERE email = ?", (user_email,))
1
2
3
// Java (JDBC)
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setInt(1, userId);

2. Stored Procedures (with Parameterization)

Use parameterized stored procedures instead of dynamic SQL:

1
2
3
4
5
CREATE PROCEDURE GetUser(@Username VARCHAR(50))
AS
BEGIN
SELECT * FROM users WHERE username = @Username
END

3. Input Validation & Sanitization

  • Allowlist validation: Reject unexpected input formats (e.g., enforce ^\d+$ for numeric IDs)
  • Escape special characters (if parameterization isn’t possible):
    1
    $safe_input = mysqli_real_escape_string($conn, $_POST['input']);

4. Principle of Least Privilege

Restrict database permissions:

1
2
CREATE USER 'webapp'@'localhost' IDENTIFIED BY 'StrongPassword!';
GRANT SELECT, INSERT ON app_db.* TO 'webapp'@'localhost'; -- Avoid GRANT ALL

5. Web Application Firewalls (WAF)

Deploy a WAF to block common attack patterns:

1
2
3
4
5
# Nginx + ModSecurity
location / {
ModSecurityEnabled on;
ModSecurityConfig modsec.conf;
}

Testing Your Defenses

Verify your fixes with these tools:

  1. ScyScan (Free): Web Security Scanner - Active online scanner for SQLi and other vulnerabilities

  2. SQLMap (Open-source): https://sqlmap.org/ - Automated penetration testing tool

  3. Acunetix Online Scanner (Freemium): https://www.acunetix.com/vulnerability-scanner/online-sql-injection-scanner/ - Cloud-based vulnerability detection

Key Takeaways

  • Always use parameterized queries – never concatenate user input into SQL
  • Validate input strictly and minimize database privileges
  • Regularly scan applications (quarterly minimum)
  • Train developers on secure coding – CWE-89 is 100% preventable

“Security is not a product, but a process.”
– Bruce Schneier

Further Reading: