23.9 KB · commit 40bb182
← Previous: T13.1: Database Security Threats and Authorization | 🏠 Index | Next: T13.3: Ordered Indexing →
Topic: T13 — Security, Indexing & Hashing | Priority: 🟡 Medium | Exam Frequency: 2/7 finals (+ 0 CTs) (9 marks) Sources: Silberschatz 7e Ch. 9 (§9.8.1), Ch. 5 (§5.1.1.5)
SQL injection is one of the most prominent web application security threats tested in semester finals. It appeared in 2020 Q.4(a) for 4 marks and in 2021 Q.8(b) for 5 marks (totaling 9 marks). The examiner consistently asks three things: the exact definition of an SQL injection attack, a concrete code example illustrating how the attack operates, and the technical precautions required to neutralize it. Mastering parameterized queries in JDBC and Python guarantees full marks.
SQL Injection: SQL injection is a security attack where an attacker puts malicious SQL code into an application input field. Because the application pastes this raw input into a query string, the database runs the attacker's SQL command.
Prepared Statement: A prepared statement is a precompiled SQL query template that uses question mark placeholders (
?) for user inputs. The database compiles the query structure first and binds user values later strictly as literal data. This keeps code and data separate so user input can never change the SQL command.
SQL injection happens when an application mixes untrusted user input directly into an SQL command by gluing strings together (string concatenation).
Imagine filling out a paper withdrawal slip at a bank where the blank space asks for your account name. If a normal customer writes Alice, the teller reads the instruction: "Transfer $100 from account 'Alice'." Now imagine an attacker writes: Alice' OR '1'='1. Because the bank clerk blindly copies whatever is written on the slip into the master instruction sheet, the sentence becomes: "Transfer $100 from account 'Alice' OR whenever '1'='1'." Since 1=1 is always true, the clerk empties every account in the bank!
In a safe system, code (the SQL query structure) and data (what the user typed) are kept completely separate. However, when a program builds SQL queries by pasting strings together like this:
# Insecure dynamic SQL construction
query = "SELECT * FROM users WHERE username = '" + user_input + "'"
The database SQL parser receives a single combined string. Because everything arrives mashed together, the parser has no way to tell where the developer's SQL commands end and where the user's input begins. If the user types special SQL characters like ', ", ;, or --, those characters break out of the data quote and rewrite the query's parse tree (Abstract Syntax Tree, or AST). As a result, the database runs commands the developer never intended.
To see how attackers exploit string concatenation in practice, let's walk through four common attack patterns.
OR '1'='1')Suppose an online banking portal looks up a customer's account using string concatenation:
SELECT * FROM accounts WHERE owner = '<user_input>';
' OR '1'='1SELECT * FROM accounts WHERE owner = '' OR '1'='1';
' closes the opening quote of owner = ' early.OR '1'='1' adds a new boolean condition to the WHERE clause.'1'='1' is a tautology (it is always TRUE for every row), the entire WHERE condition becomes TRUE for every row in the table.accounts table!If the database driver allows multiple semicolon-separated statements in a single call, an attacker can finish the first query early and start a brand-new command:
SELECT * FROM orders WHERE order_id = '<user_input>';
'; DROP TABLE orders; -- SELECT * FROM orders WHERE order_id = ''; DROP TABLE orders; -- ';
' closes the order_id string literal.; marks the end of the SELECT statement.DROP TABLE orders, which deletes the entire orders table.-- turns the leftover ' at the end of the developer's original query into a harmless SQL comment so the parser does not throw a syntax error.SQL injection can also happen outside the WHERE clause whenever user input controls column names, table names, or sort order:
// Dynamically appending an order attribute
String query = "SELECT * FROM takes ORDER BY " + orderAttribute;
year; DELETE FROM takes; --? placeholders cannot be used for column names or ASC/DESC keywords. If the developer does not check orderAttribute against a strict allowlist of valid column names, an attacker can piggyback destructive commands right after the ORDER BY clause.UNIONAn attacker can use the UNION operator to tack results from a secret table onto the output of an ordinary search page:
SELECT item_name, price FROM products WHERE category = '<user_input>';
' UNION SELECT username, password FROM admin_users -- SELECT item_name, price FROM products WHERE category = ''
UNION
SELECT username, password FROM admin_users -- ';
SELECT queries return two columns, the database merges the admin usernames and passwords into the product list and prints them right on the web page.Stopping SQL injection requires separating user data from SQL commands and limiting what the database account is allowed to do.
Prepared statements (also called parameterized queries) are the gold-standard defense against SQL injection.
Instead of sending one combined string to the database, a prepared statement splits query execution into two strict steps:
?) to the database before touching any user input. The database parses, compiles, and locks in the query's execution plan (AST).? placeholders.? slot strictly as a literal data value, never as executable SQL commands. Even if the user types ' OR '1'='1, the database simply looks for someone whose literal name is the 10-character string ' OR '1'='1.Untrusted Input: ' OR '1'='1
│
▼
┌────────────────────────────────────────────────────────┐
│ Precompiled Query Plan: │
│ SELECT * FROM instructor WHERE name = [Parameter 1] │
└────────────────────────────────────────────────────────┘
│
▼
Execution Engine looks for an instructor whose literal name
is the exact 10-character string: "' OR '1'='1"
│
▼
No match found → Returns 0 rows safely!
// SECURE: Using PreparedStatement with parameterized values
String query = "SELECT * FROM instructor WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
// Bind the untrusted user input as a string literal
pstmt.setString(1, user_input);
// Execute the safe query
ResultSet rs = pstmt.executeQuery();
# SECURE: Database driver binds parameters separately
query = "SELECT * FROM instructor WHERE name = %s"
cursor.execute(query, (user_input,))
records = cursor.fetchall()
Applications should also check that incoming inputs match the expected type, length, and format before running a query:
int(user_id)). If an attacker submits ' OR 1=1, the conversion fails immediately before the database is ever contacted.? placeholders only work for data values (not table names, column names, or ASC/DESC), check any dynamic column or sort keyword against a hardcoded allowlist:// SECURE: Allowlisting dynamic column names
Set<String> allowedColumns = Set.of("ID", "name", "dept_name", "salary");
if (!allowedColumns.contains(orderAttribute)) {
throw new IllegalArgumentException("Invalid sort attribute");
}
String query = "SELECT * FROM instructor ORDER BY " + orderAttribute;
Even if a bug slips into the code, the web application's database account should only have the bare minimum permissions needed for its job:
SELECT, INSERT, and UPDATE on the specific tables the app uses.root, sa, or DBA.DROP TABLE, ALTER TABLE, and GRANT revoked from the application account so an attacker can never wipe out tables.You can also wrap queries inside stored procedures that take typed parameters:
DELIMITER //
CREATE PROCEDURE GetInstructorByName(IN p_name VARCHAR(50))
BEGIN
SELECT * FROM instructor WHERE name = p_name;
END //
DELIMITER ;
Because p_name is bound as a typed VARCHAR variable rather than glued into a command string, it behaves safely just like a prepared statement (as long as the procedure does not build dynamic strings inside itself with EXECUTE IMMEDIATE).
Attackers often deliberately send broken quotes just to read the database's error message and learn table and column names. Always log detailed SQL errors privately on the server and show a polite, generic error message to the user.
admin' -- )While OR '1'='1' bypasses a login check by making the WHERE clause true for every row, attackers can also log into a specific user's account (such as admin) by commenting out the password check!
Suppose a student portal checks logins using this vulnerable PHP snippet:
// VULNERABLE CODE
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM students WHERE username = '$user' AND password = '$pass'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// Log user in
}
admin' -- into the username box and types anything (or nothing) into the password box.$user into $sql, the query string becomes:
SELECT * FROM students WHERE username = 'admin' -- ' AND password = ''
-- does: in SQL, a double hyphen starts a single-line comment. Everything after -- (including AND password = '') is completely ignored by the parser!SELECT * FROM students WHERE username = 'admin'
'admin' user exists in the students table, the query returns 1 row, and the attacker logs straight into the admin account without knowing the password.Replacing string concatenation with a prepared statement stops the attack cold:
// SECURE CODE
$stmt = $db->prepare("SELECT * FROM students WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
Now when the attacker submits admin' -- , the query structure (WHERE username = ? AND password = ?) is already compiled and locked. The database searches for a student whose literal username is "admin' -- " and whose password matches $pass (treated as data, not code). Because no student has that username, the query returns 0 rows and blocks the login.
| Year & Question | Marks | Sub-Questions Asked | Key Response Strategy |
|---|---|---|---|
| 2020 Q.4(a) | 4 | What is SQL injection? How it works? Precautions to prevent it? | Give formal definition, show ' OR '1'='1 exploit trace, list prepared statements, input validation, and least privilege. |
| 2021 Q.8(b) | 5 | What is SQL injection? Describe precautions to prevent it. | Provide definition, explain AST separation failure, detail prepared statements with code syntax, whitelisting, and least privilege. |
Appeared: 2020 Q.4(a) — (04 marks)
Question:
What is an SQL injection attack? Explain how it works and what precautions must be taken to prevent SQL injection attack.
Full Answer:
1. Definition of SQL Injection Attack:
An SQL injection attack occurs when an attacker inputs malicious SQL syntax into an unsanitized application input field. The application concatenates this input directly into a dynamic SQL query string. The database parser interprets the attacker's input as executable SQL commands rather than data, allowing unauthorized data access, authentication bypass, or data destruction.
2. How It Works:
Consider a web application that constructs a dynamic query using string concatenation:
SELECT * FROM instructor WHERE name = '<user_input>';
If an attacker enters the string ' OR '1'='1, the resulting query constructed by the application becomes:
SELECT * FROM instructor WHERE name = '' OR '1'='1';
name attribute. The OR '1'='1' condition is a tautology that always evaluates to TRUE.WHERE clause evaluates to TRUE for every row in the relation. The database returns all records in the instructor table, exposing sensitive data.Alternatively, if the database permits stacked queries, an attacker can input:
'; DROP TABLE student; --
The semicolon terminates the initial query and immediately executes the destructive DROP TABLE command, while -- comments out the remaining closing quotation marks.
3. Precautions to Prevent SQL Injection:
Use Prepared Statements (Parameterized Queries):
This is the primary defense. The application precompiles the query structure using placeholders (?). Parameter values are bound separately out-of-band:
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM instructor WHERE name = ?");
stmt.setString(1, user_input);
ResultSet rs = stmt.executeQuery();
The database never treats the contents of the parameter as executable SQL grammar.
Input Validation and Whitelisting:
Validate all input data types and lengths. For dynamic identifiers (like table or column names in ORDER BY clauses) that cannot be parameterized, check values against an explicit whitelist of permitted names.
Enforce Principle of Least Privilege:
Configure database connection accounts with minimal necessary permissions. Application accounts should only have SELECT, INSERT, or UPDATE privileges, and must never hold administrative permissions such as DROP TABLE or GRANT.
Appeared: 2021 Q.8(b) — (05 marks)
Question:
What is SQL injection attack? Describe the precautions that should be taken to prevent this attack.
Full Answer:
1. What is an SQL Injection Attack?
An SQL injection attack is a code injection technique where malicious SQL statements are inserted into entry fields of a data-driven application. It exploits a design flaw where application code concatenates user-supplied strings directly into dynamic SQL queries without sufficient validation or escaping. As a result, the database query parser cannot distinguish between application control code and user data, allowing the attacker to execute arbitrary SQL commands on the database.
2. Precautions to Prevent SQL Injection Attacks:
Adopt Prepared Statements with Parameterized Queries (Primary Defense):
Implement Input Validation and Whitelisting:
ASC/DESC keywords), validate the user input against a hardcoded whitelist of approved tokens.Enforce Least Privilege for Database Users:
DROP, ALTER, GRANT, SHUTDOWN).Use Parameterized Stored Procedures:
Suppress Verbose Database Errors:
Source: Silberschatz 7e · Chapter 9 (Practice Exercise 9.8)
Exam Relevance: High-Probability Exam Security Question
Key Tested Concept: Why dynamic string concatenation creates injectable syntax trees, and how PreparedStatement parameterization prevents injection.
Problem Statement:
- Demonstrate how a malicious user input creates an Abstract Syntax Tree (AST) injection in a dynamically concatenated SQL query.
- Write the corrected code using Java JDBC
PreparedStatement(or Python parameterized DB-API).- Explain technically why prepared statements are 100% immune to SQL injection, even if the input string contains SQL syntax keywords like
' OR '1'='1or; DROP TABLE.
Model Exam-Style Solution:
// VULNERABLE CODE:
String sql = "SELECT * FROM users WHERE username = '" + userInputUser + "' AND password = '" + userInputPass + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
userInputUser = admin' --SELECT * FROM users WHERE username = 'admin' --' AND password = '...'
' closes the string literal early, and -- turns the remainder of the query into a comment. The syntax tree itself is altered, bypassing authentication!PreparedStatement):// SECURE CODE:
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, userInputUser);
pstmt.setString(2, userInputPass);
ResultSet rs = pstmt.executeQuery();
? is sent to the database engine first:
AST constructed: Query→Filter(username = [Param 1] ∧ password = [Param 2])
The Abstract Syntax Tree is compiled and fixed before any user input is ever touched.pstmt.setString(1, "admin' --") is executed, the DBMS treats the input strictly as a raw literal data value, never as executable code.a-d-m-i-n-'- -.💡 RUET Exam Takeaway: Always explain that Prepared Statements pre-compile the SQL syntax tree BEFORE binding parameters. Data and code are fundamentally segregated.
' OR '1'='1 or '; DROP TABLE ...; -- guarantees full marks.required or JavaScript form checks) can be completely bypassed using command-line HTTP clients like curl or Postman. Server-side parameterized queries are mandatory.← Previous: T13.1: Database Security Threats and Authorization | 🏠 Index | Next: T13.3: Ordered Indexing →