CAPIE - Chapter 5.XTRA1
API Penetration Testing Report
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:
- Broken Access Control (BAC): Detected vulnerabilities where unauthorized users could
access privileged data.
- SQL Injection (SQLi): Potential for injection attacks in multiple API endpoints.
High Vulnerabilities:
- Improper Input Validation: API does not adequately validate user input, exposing it to
common attack vectors such as XSS and Command Injection.
Medium Vulnerabilities:
- Lack of Rate Limiting: The API does not implement rate limiting for certain endpoints,
potentially allowing for brute-force attacks.
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
- API documentation was reviewed, and API endpoints were enumerated using tools such as Burp Suite and
Postman.
- Authentication and authorization mechanisms were tested.
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
- Common vulnerabilities like IDOR, BAC, SQLi, and XSS were tested manually.
- Tools like SQLmap and Burp Suite were used to automate certain tests.
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
- Validated vulnerabilities with proof-of-concept (PoC) exploits, demonstrating how an attacker could
potentially exploit these vulnerabilities.
Stage 4: Reporting
- All findings were documented with detailed descriptions, exploitation steps, and recommendations for
remediation.
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:
- Enhance Authentication and Authorization Controls: Implement role-based access
controls and ensure proper permission checks for every request.
- Address Input Validation Issues: Use parameterized queries for database
interactions and ensure proper input sanitization to mitigate SQL Injection and XSS.
- Implement Rate Limiting: Protect against brute-force attacks and DoS by enforcing
rate limits on sensitive API endpoints.
- 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
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. |