Prevention
Core Principles
Treat all user input as dangerous
Use parameterized queries
Apply least privilege
Defense in depth
Input Validation / Sanitization
Always Sanitize
Validate input format (email, phone, etc.)
Escape special characters
Whitelist allowed characters
Reject unexpected input
Example Validation
// Validate email format
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
die("Invalid email format");
}
// Whitelist alphanumeric only
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['username'])) {
die("Invalid characters in username");
}Parameterized Queries
The Problem (Vulnerable Code)
The Solution (Parameterized)
Why It Works
Concatenation
Mixed together
Can escape context
Parameterized
Sent separately
Treated as literal data
Server understands what is code vs data, regardless of input content.
Parameterized Queries by Language
PHP (PDO)
Python (psycopg2)
Java (PreparedStatement)
C# (.NET)
Node.js (mysql2)
Output Sanitization
β οΈ Don't trust data from the database!
Why?
May have missed input sanitization
2nd-level SQL attacks - execute on output, not input
Stored XSS from compromised data
Solution
Apply sanitization/filtering on data output, especially user-generated content.
MSSQL-Specific Precautions
Don't Run as Sysadmin!
Never use sa for application queries.
Use account with minimal privileges needed.
MSSQL Database Roles
public
Default role (minimal)
db_datareader
Read all data
db_datawriter
Write all data
db_owner
Full control (DANGEROUS)
Recommended Approach
Disable Dangerous Functions
Functions Attackers Abuse
xp_cmdshell
Command execution (RCE)
xp_dirtree
NetNTLM hash leaking
xp_fileexist
File enumeration
xp_subdirs
Directory enumeration
OPENROWSET
File read
Revoke Execution Privileges
Note: Don't completely disable functions like
xp_dirtree- the server uses them internally. Just revoke user access.
Defense in Depth
Multiple Layers
WAF Rules
Block common SQLi patterns:
' OR 1=1UNION SELECTxp_cmdshellWAITFOR DELAY
Checklist
Development
Database
Infrastructure
Quick Reference
Parameterized Query
Revoke Dangerous Functions
Least Privilege User
Last updated