CAPIE - Chapter 5.XTRA1
API Penetration Testing Report

Client: [Client Name]

Project Name: API Penetration Test

Test Period: [Start Date] - [End Date]

Tested by: [Tester Name/Team]

Report Date: [Date]

1. Executive Summary

This report details the findings of the penetration test conducted on the client's API. The objective of the test was to identify potential security vulnerabilities, assess the effectiveness of authentication and access controls, and validate the overall security posture of the API endpoints.

The testing was carried out over [X] days, focusing on common vulnerabilities such as SQL Injection, Cross-Site Scripting (XSS), Broken Access Control (BAC), Insecure Direct Object References (IDOR), and others. A combination of manual testing and automated tools was employed to simulate real-world attack scenarios.

Key Findings:

Critical Vulnerabilities:

High Vulnerabilities:

Medium Vulnerabilities:

Risk Assessment Overview

Critical
2 Issues
High
2 Issues
Medium
1 Issue
Low
0 Issues

Risk Assessment: The overall risk level is considered Medium due to the presence of critical vulnerabilities that need immediate attention, especially in the areas of access control and input validation.

2. Methodology

Our approach followed the standard OWASP API Security Testing guidelines. The test was divided into the following stages:

Testing Methodology Flow

Information Gathering
Vulnerability Identification
Exploitation
Reporting

Stage 1: Information Gathering

Example Commands:
curl -X GET "https://api.example.com/v1/endpoints" -H "Authorization: Bearer TOKEN" postman collection run api-endpoints.json burpsuite --target https://api.example.com

Stage 2: Vulnerability Identification

Example Commands:
sqlmap -u "https://api.example.com/user?id=1" --dbs sqlmap -u "https://api.example.com/user?id=1" --dump burpsuite --scan https://api.example.com --active

Stage 3: Exploitation

Stage 4: Reporting

3. Detailed Findings

Vulnerability 1: Broken Access Control (BAC)

Severity: Critical

Description:

The API failed to enforce proper access control in several endpoints. By modifying request parameters (e.g., changing user ID in the URL), unauthorized access to sensitive data was possible.

Impact:

This vulnerability allows attackers to escalate their privileges and access unauthorized data or actions.

Exploit:

An attacker could modify the user ID parameter to gain access to other users' data.

Exploitation Example:
curl -X GET "https://api.example.com/user/profile?user_id=100" -H "Authorization: Bearer ATTACKER_TOKEN" curl -X GET "https://api.example.com/user/profile?user_id=101" -H "Authorization: Bearer ATTACKER_TOKEN"

By changing user_id from 100 to 101, the attacker gains access to another user's profile.

Recommendation:

  • Implement robust Role-Based Access Control (RBAC) and validate user access permissions before serving sensitive data.
  • Always verify that the authenticated user has permission to access the requested resource.
  • Use indirect object references instead of direct database IDs.

Vulnerability 2: SQL Injection (SQLi)

Severity: High

Description:

Several endpoints were found to be vulnerable to SQL Injection attacks. By injecting malicious SQL queries into API parameters, it was possible to manipulate the backend database.

Impact:

This vulnerability can lead to unauthorized access to the database, data leaks, and potentially full system compromise.

Exploit:

An attacker can modify a parameter in an API request to inject SQL code that could read, modify, or delete data.

Exploitation Example:
curl -X GET "https://api.example.com/user?id=1' OR '1'='1" curl -X GET "https://api.example.com/user?id=1 UNION SELECT username,password FROM users--" sqlmap -u "https://api.example.com/user?id=1" --batch --dump

SQL Injection Attack Flow

Attacker Sends Malicious Input
API Accepts Unvalidated Input
SQL Query Executed
Database Compromised

Recommendation:

  • Use parameterized queries (prepared statements) to prevent SQL injection.
  • Sanitize and validate all inputs using whitelist validation.
  • Apply the principle of least privilege for database access.
  • Implement Web Application Firewall (WAF) rules to detect SQL injection attempts.
Secure Code Example:
// Vulnerable Code: query = "SELECT * FROM users WHERE id = " + userId; // Secure Code: PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?"); stmt.setInt(1, userId);

Vulnerability 3: Cross-Site Scripting (XSS)

Severity: Medium

Description:

The API did not properly sanitize user input, leading to a Reflected XSS vulnerability. This allows attackers to inject malicious JavaScript into API responses, which could be executed on the client-side.

Impact:

XSS could result in the theft of cookies, session tokens, and potentially lead to account hijacking.

Exploit:

By crafting a malicious request, an attacker could inject a script that would execute in the browser of any user interacting with the API response.

Exploitation Example:
curl -X GET "https://api.example.com/search?q=<script>alert('XSS');</script>" curl -X POST "https://api.example.com/comment" -d "text=<img src=x onerror=alert(document.cookie)>"

Recommendation:

  • Implement proper input sanitization and output encoding to prevent the execution of untrusted data in responses.
  • Use Content Security Policy (CSP) headers to mitigate XSS risks.
  • Validate and encode all user inputs before rendering them in responses.
  • Use HTTP-only and Secure flags for cookies.
CSP Header Example:
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline';

Vulnerability 4: Insecure Direct Object Reference (IDOR)

Severity: High

Description:

An attacker was able to access unauthorized resources by manipulating the object identifier in API requests (e.g., changing user ID or resource ID in the URL).

Impact:

This vulnerability allows attackers to access data from other users or services without proper authorization.

Exploit:

By altering parameters in API requests, attackers can access another user's data, violating data privacy.

Exploitation Example:
curl -X GET "https://api.example.com/documents/12345" -H "Authorization: Bearer USER_TOKEN" curl -X GET "https://api.example.com/documents/12346" -H "Authorization: Bearer USER_TOKEN" curl -X DELETE "https://api.example.com/documents/12347" -H "Authorization: Bearer USER_TOKEN"

By incrementing the document ID, the attacker can access or delete documents belonging to other users.

Recommendation:

  • Ensure that object identifiers are properly validated against user permissions before accessing or modifying resources.
  • Implement indirect reference maps instead of exposing direct database IDs.
  • Use UUIDs instead of sequential integers for resource identifiers.
  • Always verify authorization for every resource access request.

Vulnerability 5: Rate Limiting Issues

Severity: Medium

Description:

Some API endpoints lacked rate limiting, allowing attackers to flood the API with a large number of requests in a short period.

Impact:

This could allow attackers to perform brute force attacks on authentication endpoints or overwhelm the system, causing a Denial of Service (DoS).

Exploit:

By making rapid requests to the API without rate limiting, attackers could exhaust system resources or perform a brute-force attack on authentication mechanisms.

Exploitation Example:
for i in {1..10000}; do curl -X POST "https://api.example.com/login" -d "username=admin&password=test$i"; done python3 -c "import requests; [requests.post('https://api.example.com/login', data={'user':'admin','pass':i}) for i in range(10000)]"

Recommendation:

  • Implement rate limiting to restrict the number of requests from a single IP or account within a given time window.
  • Use exponential backoff for failed authentication attempts.
  • Implement CAPTCHA for sensitive endpoints after multiple failed attempts.
  • Monitor and alert on abnormal request patterns.
Rate Limiting Implementation Example:
// Express.js with express-rate-limit const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }); app.use('/api/', limiter);

4. Conclusion and Recommendations

The overall security posture of the tested API was found to be medium-risk, with critical vulnerabilities such as Broken Access Control and SQL Injection requiring immediate attention. The key recommendations for improving the security of the API are as follows:

Priority Recommendations:

  1. Enhance Authentication and Authorization Controls: Implement role-based access controls and ensure proper permission checks for every request.
  2. Address Input Validation Issues: Use parameterized queries for database interactions and ensure proper input sanitization to mitigate SQL Injection and XSS.
  3. Implement Rate Limiting: Protect against brute-force attacks and DoS by enforcing rate limits on sensitive API endpoints.
  4. Re-test Vulnerabilities: After remediating the identified vulnerabilities, conduct re-testing to verify the fixes.

Recommended Security Implementation Roadmap

Priority Action Item Timeline Status
Critical Fix Broken Access Control vulnerabilities 1-2 weeks Pending
Critical Remediate SQL Injection vulnerabilities 1-2 weeks Pending
High Implement proper input validation 2-3 weeks Pending
High Fix IDOR vulnerabilities 2-3 weeks Pending
Medium Implement rate limiting 3-4 weeks Pending
Medium Address XSS vulnerabilities 3-4 weeks Pending

5. Appendix

5.1 Proof of Concept (PoC)

SQL Injection PoC:

Example request:

GET /api/user?id=1' OR '1'='1

Expected outcome: Successful retrieval of all user data due to the injected SQL query.

XSS PoC:

Example payload:

<script>alert('XSS');</script>

Expected outcome: The script will execute on the client-side, displaying an alert box.

IDOR PoC:

Example request:

GET /api/user/profile?user_id=100 GET /api/user/profile?user_id=101

Expected outcome: Access to another user's profile data without proper authorization.

5.2 Tools Used

Burp Suite

Web vulnerability scanner and proxy tool for intercepting and modifying HTTP requests.

Postman

API development and testing platform for endpoint enumeration and testing.

SQLmap

Automated SQL injection and database takeover tool.

OWASP ZAP

Open-source web application security scanner.

Burp Collaborator

Service for detecting out-of-band vulnerabilities.

Python Scripts

Custom payload generation and automation scripts.

Tool Installation Commands:

sudo apt-get install burpsuite sudo apt-get install sqlmap sudo apt-get install zaproxy pip install requests beautifulsoup4 snap install postman

5.3 References

OWASP API Security Top 10 (2023)

Rank Vulnerability Description
API1:2023 Broken Object Level Authorization APIs tend to expose endpoints that handle object identifiers, creating a wide attack surface.
API2:2023 Broken Authentication Authentication mechanisms are often implemented incorrectly, allowing attackers to compromise tokens.
API3:2023 Broken Object Property Level Authorization Lack of proper authorization validation at the object property level.
API4:2023 Unrestricted Resource Consumption APIs do not impose restrictions on resource consumption (rate limiting, throttling).
API5:2023 Broken Function Level Authorization Complex access control policies with different hierarchies and roles.