Database auditing, threats and SQL injection
Database auditing, threats and and SQL injection: definitions, attacker models, detection and prevention (parameterized queries, least privilege, logging), and exam-style worked examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Database systems hold business-critical data (user records, financials, logs). An engineer uses database auditing and SQL injection (SQLi) defence to detect attacks, prove who did what, and prevent attackers from reading or changing data by sending hostile input to the database.
Key ideas
All bold terms are defined before use.
Database auditing: the process of recording and examining actions performed on the database (queries executed, connections, results, schema changes). Purpose: accountability, forensics, compliance. Assumption: the audit record is available and reliable.
Audit log: an append-only file or stream listing events. Each entry usually includes timestamp, user/connection id, SQL text (or a normalized form), affected objects, and result code.
Integrity of audit logs: audit logs must be tamper-evident. A common mechanism is hash-chaining: for a sequence of log records L1, L2, ... Ln compute H0 as an initial seed (or previous checkpoint), and Hi = H(Hi-1 || Li) for i >= 1. Any tampering breaks the chain if the seed/checkpoints are protected. Assumption: H is a cryptographic hash (e.g., SHA-256) and chain anchors are secured (e.g., HMAC/signature or off-host storage).
Threat model: explicitly state what the attacker can and cannot do. For SQLi we commonly assume the attacker can send arbitrary strings as input to the application (e.g., form fields, URL parameters) but cannot directly connect to the DB server without the app. If the application constructs SQL queries by concatenation, the attacker can influence the final SQL text.
SQL injection (SQLi): a class of vulnerabilities where untrusted input is used to construct an SQL statement so that the input is interpreted as SQL code, allowing the attacker to change the intended query semantics. Exact statement: "If the application builds SQL statements by concatenating untrusted input without proper separation of code and data, the system is vulnerable to SQL injection."
Types / classifications of SQLi (exact definitions):
- Error-based SQLi: attacker crafts input to cause database errors that leak information in the error message.
- Union-based SQLi: attacker appends a
UNION SELECTto combine attacker-controlled result rows with the application's query result to read other tables. - Boolean-based blind SQLi: attacker sends payloads that make the query return different row counts or page contents depending on a boolean condition in the database; attacker infers true/false to exfiltrate data bit-by-bit.
- Time-based blind SQLi: attacker causes a database delay (e.g.,
pg_sleep(5)) when a condition is true; attacker observes response time to infer bits. - Stored procedure / command injection: attacker abuses stored procedures or DB features (e.g., xp_cmdshell) to run commands.
- Second-order SQLi: malicious input is stored in the database and later used unsafely in a different context.
- Stacked (piggy-backed) queries: attacker terminates the intended statement and adds another statement (if the server/driver allows multi-statements), enabling actions like UPDATE/DELETE/DROP.
- Out-of-band (OOB) SQLi: attacker uses DB features to trigger network/DNS/HTTP requests to exfiltrate data when in-band responses are suppressed (e.g., xp_dirtree in SQL Server, UTL_HTTP in Oracle).
Why prepared/parameterized queries work (formal statement): A prepared statement defines a query template with placeholders; the DB engine parses and compiles the template before binding parameter values. Therefore, parameter values are never parsed as SQL tokens. Assumptions: the DB driver uses server-side prepared statements or safely implements parameter binding.
Principal prevention controls:
- Parameterized queries / prepared statements: separate code and data.
- Input validation and canonicalisation: check type, length, allowed characters; canonicalise before validation (e.g., Unicode normalisation) to avoid encoding tricks.
- Escaping / quoting: transform special characters into safe forms — weaker than parameterization and error-prone.
- Least privilege: the application DB account must have only the privileges needed (SELECT/INSERT/UPDATE on specific schemas) — never DBA or owner privileges.
- Stored procedures: can limit SQL to controlled code paths if they do not themselves build dynamic SQL.
- Web Application Firewall (WAF) and DB firewalls: detect and block known SQLi patterns; not foolproof.
- Database Activity Monitoring (DAM): real-time detection of anomalous SQL patterns and queries across sessions.
- Separation of duties: auditing and admin roles should be separate; RBAC can enforce this (see Role hierarchies in the syllabus).
Detection rules and indicators: presence or repeated occurrence of
' OR 1=1 --patterns, queries containing manyUNION SELECTorINFORMATION_SCHEMAreferences from web-app accounts, repeating failed logins, sudden changes in row-return sizes, and time-delays triggered by functions like SLEEP/pg_sleep. Assumption: auditing captures SQL text or prepared-statement parameters.Diagram to draw for an exam (describe exactly): Draw three boxes left-to-right labelled "Client (browser)", "Web application", "Database server". Draw arrows: Client -> Web application labelled "HTTP request with input"; Web application -> Database server labelled "SQL query". Inside Web application box draw two small boxes labelled "Sanitise / Validate" and "Query builder". Show a broken arrow from unvalidated input concatenated into SQL builder causing "Injection" at the DB box. Also show audit log copy forwarded from DB server to a secure log store with a hash-chaining arrow.
Formulas
For this programming topic we list syntax to remember. Each line is a single syntax example; after it, what symbols mean and when it applies.
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ? AND active = ?"); — Java JDBC. conn: Connection object; ? are parameter placeholders. Use ps.setString(1, email) etc. Applies when using JDBC.
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,)) — Python psycopg2 style. %s is a placeholder; pass parameters as a tuple. cursor: DB cursor. Applies to psycopg2 and many DB-API 2.0 drivers.
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :u'); $stmt->execute([':u' => $user]); — PHP PDO. :u named parameter.
$mysqli->prepare("SELECT * FROM users WHERE id = ?") — PHP MySQLi. ? placeholder.
H_i = H(H_{i-1} || L_i) — hash-chaining for audit logs. H: cryptographic hash (e.g., SHA-256). H_0 is an initial seed. L_i: canonical representation of log entry i. || means concatenation. Applies when implementing tamper-evident logs.
DROP DATABASE is a dangerous privilege-requiring command — do not grant to application accounts. Use this as a reminder of high-privilege operations to restrict.
regex_allow = ^[A-Za-z0-9._-]{1,64}$ — example allowlist regular expression for an email local part (simplified; note: no '@' in the local part). Apply after canonicalisation and only for fields that fit a narrow pattern. Symbols: ^ start, $ end, {1,64} length.
Worked examples
Example 1 — Login bypass (classic) (step-by-step)
Given: the web app builds this SQL in PHP by string concatenation:
Query template: SELECT id FROM users WHERE username = 'USER' AND password = 'PASS'.
- Attack payloads: set USER =
admin' --and PASS = anything (ignored). - Final SQL becomes:
SELECT id FROM users WHERE username = 'admin' --' AND password = 'PASS'. --starts a SQL comment; text after it is ignored. The WHERE clause reduces tousername = 'admin'. If a rowadminexists, the query returns a user id and the attacker logs in as admin. Prevention: use parameterized query (example in Formulas). With parameters, the username valueadmin' --is treated as data and cannot terminate the'string in SQL.
Example 2 — UNION-based data extraction (step-by-step)
Suppose application runs: SELECT id, title FROM articles WHERE id = 10 and shows title. Attacker supplies id parameter: 10 UNION SELECT username, password FROM users.
- Final SQL:
SELECT id, title FROM articles WHERE id = 10 UNION SELECT username, password FROM users. - If column counts and types match, DB returns rows from users table disguised as articles. Attacker reads rows.
Prevention: parameterize id as integer, validate numeric id, disallow multiple statements, restrict application account to a schema without
userstable access (or only limited SELECT columns).
Example 3 — Detecting SQLi via audit logs (short scenario)
Audit log entry format: timestamp | conn_id | user | sql_text | rows_returned
Entries:
2026-11-01T10:02:12Z | 42 | app_user | SELECT name FROM products WHERE id = 1 | 12026-11-01T10:02:14Z | 42 | app_user | SELECT name FROM products WHERE id = 1 OR 1=1 -- | 1000Detection: same conn_id with sudden large rows_returned and literalOR 1=1indicates probable injection. Response: block IP, investigate, rotate credentials, review app code for concatenation.
Common mistakes
- Granting broad privileges to the application DB account (e.g., owner or admin rights) — violates least privilege.
- Logging full plaintext passwords or sensitive fields in audit logs.
- Disabling or truncating audit logs for performance without an alternate secure storage (breaks forensics).
- Using a blacklist of bad substrings (e.g., blocking
--,UNION) instead of a strict allowlist; attackers evade blacklists. - Forgetting second-order injection: valid input stored safely can later be used unsafely.
For your exam
Types of questions you will see: definitions (e.g., define SQL injection), short notes (describe types and prevention), derivations/explanations (prove why prepared statements prevent injection), algorithms/traces (trace an attack payload), diagram drawing (draw client–app–DB and audit flow), and practical code snippets (write parameterized query in JDBC/Python/PDO).
What a full-marks answer includes:
- Precise definitions (bold terms as above), clear threat model and assumptions.
- Correct classification of SQLi types with examples for each.
- A defended prevention strategy listing multiple layers (primary: parameterized queries; secondary: input validation, least privilege, WAF/DAM, secure logging).
- For diagrams: labelled boxes and arrows as described in Key ideas.
- For code: correct parameter syntax for at least one language and explanation of why it is safe.
Quick check
- What is the essential reason parameterized queries prevent SQL injection?
- Name two blind SQLi techniques.
- Write the hash-chain recurrence formula used to protect audit logs.
Answers: Parameterized queries separate code and data so input is bound as values, not parsed as SQL; boolean-based blind and time-based blind;
H_i = H(H_{i-1} || L_i).
Note for reviewer: I have aimed to be precise; where I am unsure I list checks in the verify list below.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?