Explain SQL Injection (SQLi) vulnerabilities and defense mechanisms (Prepared Statements vs ORM)
Quick Revision Summary
SQL Injection (SQLi) is a critical web security vulnerability (OWASP Top 10) where an attacker interferes with database queries by injecting malicious SQL fragments through user...
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
SQL Injection (SQLi) is a critical web security vulnerability (OWASP Top 10) where an attacker interferes with database queries by injecting malicious SQL fragments through user input fields.
The Vulnerability Mechanism
When user input is directly concatenated into SQL strings, the database interpreter cannot distinguish between the query structure and user data:
// VULNERABLE CODE: const query = "SELECT * FROM users WHERE email = '" + userInput + "'"; // If userInput = "[email protected]' OR '1'='1" // Executed SQL: SELECT * FROM users WHERE email = '[email protected]' OR '1'='1' // Bypasses authentication completely!
Primary Defense: Parameterized Queries (Prepared Statements)
Prepared statements pre-compile the SQL statement structure on the database engine. User input is supplied separately as parameters and treated strictly as literal data values, never as executable code:
// SECURE PARAMETERIZED QUERY (better-sqlite3 / pg): const stmt = db.prepare('SELECT * FROM users WHERE email = ? AND status = ?'); const user = stmt.get(userInput, 1);
Defense-in-Depth Measures
- Principle of Least Privilege: Web application database credentials should have minimal privileges (e.g., cannot drop tables or execute administrative procedures).
- Input Validation & Allow-listing: Validate formats using strict regex for expected inputs (e.g., email syntax, alphanumeric IDs).
- Web Application Firewall (WAF): Inspects HTTP requests for SQLi patte s at the network perimeter.
Interviewer Evaluation Points & Scoring Rubric
- 1 Give a concise, high-level definition before diving into technical details.
- 2 Provide a concrete real-world production use case or code example.
- 3 Contrast with common alternatives or prior versions.
Related Questions in Cybersecurity & InfoSec
What is least privilege, and how would you apply it to a database-backed application?
Easy level • 6 views
How do authentication, authorization, and accounting differ?
Easy level • 5 views
Why do parameterized queries prevent SQL injection more reliably than escaping user input?
Medium level • 5 views
How do XSS and CSRF differ, and what controls address each?
Medium level • 4 views
A user changes an invoice ID in the URL and sees another customer’s invoice. What failed?
Medium level • 3 views