top of page

OWASP API Testing Guide: A Visual Guide to OWASP API Testing with vAPI

Updated: Apr 7

API testing is like cooking: follow the OWASP recipe, and your code won't taste like a security disaster!

Introduction to Pen Testing with OWASP API Top 10


In this blog, we're taking a deep dive into the world of API security through practical lab setups and real-world scenarios with the goal of learning how to test APIs as per OWASP Top 10 API Security Risks. We'll also look into the OWASP API Top 10 vulnerabilities of 2023, more details of which are available in our previous blog. If you're looking to bolster your understanding, please check out our previous blog dedicated to these vulnerabilities to gain a comprehensive understanding.


OWASP API Testing Guide Thumbnail

We want to introduce you to an exceptional lab tutorial named VAPI. This dedicated resource is tailored specifically toward honing your skills in the realm of API security assessments. Using VAMPI, you'll have the opportunity to navigate through real-world scenarios, uncover vulnerabilities, and gain hands-on experience in a controlled and safe environment. Consequently, you'll be able to apply your knowledge and improve your expertise in API security assessments.

Using Postman for API Penetration Testing

Postman is a versatile tool for API penetration testing, enabling efficient request creation, authentication testing, payload manipulation, and response analysis. With features like scripting for automation and dynamic data generation, Postman seriously simplifies identifying and addressing security vulnerabilities in modern APIs, making it an essential tool for developers and security testers.


Setting up the vAPI Lab

Prerequisites: a working virtual instance of Kali Linux and Linux fundamentals.


"vAPI" stands for Vulnerable Adversely Programmed Interface which is a Self-Hostable API project that mimics the OWASP API Top 10 scenarios through practical exercises. To create our vAPI instance for testing, it's important to add Docker to our Kali instance. This will allow us to download and run various vulnerable containers for testing purposes easily.

Install Docker by following the provided instructions. Confirm Docker is working by running the command:


sudo docker run hello-world

Adding VAPI to your Kali machine

  1. Create a directory called "api_pentesting" and Navigate to it

  2. Clone the VAPI git repository

  3. Navigate to the cloned repository

  4. Bring up the setup using docker


mkdir api_pentesting
cd api_pentesting
git clone https://github.com/roottusk/vapi.git
cd vapi
sudo docker compose up -d

While inside the "~/api_pentesting/vapi" directory, you can execute the command "docker-compose ps -a" to confirm that vAPI is running.

Accessing the vAPI app

On your local browser: http://127.0.0.1/vapi

From a different VM: You can use the VM's IP address (say, http://192.168.1.26/vapi )


vAPI home page
vAPI home page


OWASP API1:2023 Testing for Broken Object-Level Authorization

API1:2023 highlights a crucial point: APIs often have different points for managing things, and these can potentially create security gaps known as Object Level Access Control issues. It's similar to having your front doors unlocked. To prevent this, we need to ensure that whenever something uses an "identifier" from a user, there's a check to make sure that the said user is actually allowed to access it.

For our example, let's imagine the ID is like a key. Normally, you should only be able to open your door, right? But if we change the key (ID) by just a little, we might be able to open someone else's door too. In the same way, we'll use Burp Suite to show how changing this ID parameter can let us access someone else's information. This demonstrates why it's so important to make sure only the right people can access certain things to keep everyone's data safe and private.


OWASP:2023 API 1 BOLA testing

Next, route this request through Burp Suite and forward it to the Repeater tool.


Routing request to Repeater in burpsuite

Now, we're obtaining the information of a distinct user, showcasing a clear instance of a BOLA vulnerability.

Let's proceed to investigate by attempting an ID value of 1. Consider the possibility that the initial user created might be an admin user.


Solving BOLA in vAPI for flag

In this case, we retrieve the data of another user and also uncover the flag for this specific task:


flag{api1_d0cd9be2324cc237235b}

OWASP API2:2023 Testing for Broken Authentication

As outlined in API2:2023, authentication mechanisms are frequently subject to flawed implementations, enabling attackers to compromise authentication tokens or exploit vulnerabilities to assume other users' identities, either temporarily or permanently. Such compromises undermine the overall security of the API by undermining its ability to accurately identify clients and users.


To illustrate this vulnerability, consider the scenario where we lack the email and password that are required during user creation. Instead, we input random email and password values, capturing the request in Burp Suite. We then proceed to send the request to the Intruder tool (right-click -> Send to Intruder) for further analysis.


Upon observation, it's evident that the payload position is already configured for both the email and password fields.


Additionally, within the vAPI environment, there is a catalogue of email and password combinations separated by commas. In our instance, this compilation is located at


~/api_pentesting/vapi/Resources/API2_CredentialStuffing/creds.csv

creds.csv file content

We proceeded to relocate this compilation to our vAPI installation directory.


As anticipated, payload positions for both email and password values are pre-configured. To execute a Pitchfork attack, proceed to the Payloads tab.

At this point, import the content of the creds.csv file into the payload list for both payload sets.


Intruder tab with payload configured
Intruder tab with payload configured

Loading Payloads in intruder
Loading Payloads in Intruder

In the payload processing rule, opt for the Match/replace option. Add,


,([^\s,]+) 

to the match regex and leave the replace field blank.


Setting payload rule in burpsuite

For payload set 2, insert


([\w.-]+@[a-zA-Z\d.-]+.[a-zA-Z]{2,}) 

in the match field and again leave replace empty. With this configuration, initiate the attack. Additionally, ensure that the "URL-encode these characters" option is unchecked for both positions before starting the attack.


Adding payload processing rule in Burp

Allow a few hours for the process to unfold. Keep in mind that the Intruder module in Burp Suite Community Edition operates at a reduced pace during brute force attempts. Afterward, sort the outcomes based on their status. Make sure to navigate back to the beginning of the list to identify the results displaying a 200 status.


Finished attack in Intruder burpsuite

Sample Response in Intruder

Now, we can return to Postman and, while still in the API2 section of the collection, initiate a "Get Details" query. Within the Headers section of the request, paste any of the obtained tokens into the Value field for the Authorization-Token key (all three tokens will be valid).


Using Auth Token in Postman

In the details of the second user, you'll discover the flag:


flag{api2_6bf2beda61e2a1ab2d0a}

This situation highlights a key lesson: while the application verifies user authentication, it doesn't adequately verify user authorization. This vulnerability stems from broken user authentication. Additionally, the app allows for credential stuffing and lacks the implementation of a rate-limiting policy. These security flaws can lead to unauthorised access and the potential misuse of sensitive data.


OWASP API3:2023 Testing for Broken Object Property Level Authorization


API3:2023 (a.k.a. BOPLA) arises when the access control for individual properties of an object is inadequately enforced or verified. Essentially, this vulnerability allows unauthorised access to specific sensitive properties of an object that should only be accessible to designated users or roles.


This scenario encompasses both API3:2019 Excessive Data Exposure and API6:2019 Mass Assignment. It focuses on the main problem, which is the lack of validation of authorization at the object property level. As a result, unauthorised individuals can gain access to or manipulate information they shouldn't have access to.

To illustrate this, let's begin by creating a user and then attempting to retrieve the details of the newly created user.


Creating User for VAPI in Postman

The request was successfully executed. We proceed by employing the "Get User" request to access the information pertaining to the newly created user.


Get User in VAPI

In this scenario, we observe that the user's credit value stands at zero. To manipulate this value, transitioning the "Get User" request from a GET to a PUT while embedding a "credit":"100" entry within the request body will not yield the desired outcome.


Instead, the course of action involves generating a fresh user and integrating the "credit" parameter within the request body. It's imperative to remember to include a comma at the end of the "password" line for accurate formatting.


Create User with payload in VAPI

With the newly created user, let's employ the "Get User" request once more to retrieve and display the data associated with this user.


VAPI get User API3 solve flag

Upon examining the response, you'll notice that the value you added to the "credit" field in the previous request has been successfully processed. As a result, you've accomplished this task and earned the flag:


flag{api6_afb969db8b6e272694b4}

OWASP API4:2023 Testing for Unrestricted Resource Consumption

API4:2023 highlights the resource-intensive nature of satisfying API requests, involving crucial elements such as network bandwidth, CPU, memory, storage, and external services like emails, SMS, phone calls, or biometric validation. Service providers frequently offer these resources through API integrations, and costs are typically incurred per request. Successful attacks targeting this vulnerability can lead to denial-of-service (DoS) situations or a significant increase in operational expenses.


To illustrate this vulnerability, we can navigate to the API4 section within the collection. Here, we attempt a request to send an OTP (one-time password) code to a specified mobile phone number. This action is intended to log us into the user account linked to the provided cell phone number. In the response body, we observe that a 4-digit code has been dispatched to the user's device. However, since we lack access to the user's device, we are unable to retrieve the OTP code.


This vulnerability emphasises the potential for malicious actors to exploit APIs to trigger resource-intensive actions, causing service disruptions or financial strain on the targeted system.


OTP fuzzing API in VAPI

Upon triggering the action to send an OTP code to the provided mobile phone number, we gain access to the associated user account. The response body confirms that a 4-digit code has been dispatched to the user's device. However, due to the unavailability of the user's device, we are unable to retrieve the actual OTP code, necessitating the exploration of an alternative approach.

In this scenario, our request is met with a 403 forbidden response code, indicating that the OTP code we submitted is incorrect. This situation prompts us to explore further by employing a fuzzing technique.


By right-clicking on the request, we can conveniently transfer it to Burp Suite's Intruder module for in-depth analysis. This allows us to automate the process of sending multiple variations of the request with different inputs to uncover any vulnerabilities or weaknesses.


Loading OTP fuzzing API in Burp Suite Intruder

  1. Here, observe that a payload marker is already positioned on the 4-digit code.

  2. Choose "Sniper Attack" as the mode and navigate to the Payloads tab.

  3. Select "Numbers" as the payload type.


These settings enable the Intruder module to systematically iterate through a range of numbers, effectively brute-forcing the 4-digit OTP code. This process aims to uncover a valid code that grants access, addressing the lack of resources and rate-limiting vulnerability present in API 4 Unrestricted Resource Consumption.

  • After obtaining the key from the response body, follow these steps to continue:

  • Return to Postman, and within the API4 section, locate the "Get Details" query.

  • In this query, you'll notice an "Authorization Token" field.

  • Paste the previously acquired key value into the "Authorization Token" field.

  • With the key in place, proceed to send the query.


By inserting the key into the "Authorization Token" field, you're granting the necessary authorization for the "Get Details" query. This step allows us to access and retrieve further information related to the request.


API4 solution Flag for VAPI

Upon sending the query with the key in the "Authorization Token" field, you'll receive a response containing the user's details, along with the flag specific to this task:


flag{api4_ce696239323ea5b2d015}

OWASP API5:2023 Testing for Broken Function Level Authorization


API5:2023 shows us how important it is to have elaborate access control policies that include numerous hierarchies, groups, and roles, as well as a blurry line between administration and normal functions. This complexity often paves the way for authorisation vulnerabilities. Very often, attackers can take advantage of these weaknesses to gain unauthorised access to other user's resources or administrative privileges.


To illustrate this vulnerability, we initiate the process by generating a user profile and subsequently attempting to retrieve the user's associated details.


API 5 for VAPI in Postman

Upon inspecting the response body (after intercepting it), we observe the successful creation of the user with an assigned ID of 2. Subsequently, proceed to employ the 'Get User' query to authenticate the newly created user. Upon inspecting the 'Get User' query, we find the associated details.


While reattempting the request, we find that it succeeds, and the response body now displays the information of all users, including the flag associated with this particular task:


flag{api5_76dd990a97ff1563ae76}

OWASP API6:2023 Testing for Unrestricted Access to Sensitive Business Flows


It's important to note that API6:2023 shows how business flows, like buying a ticket or leaving a comment, can be exposed without proper protections against the harm that could come from automated and excessive use of these features. The inherent design of the API and the lack of suitable countermeasures to prevent misuse that could have a negative impact on the business are the main causes of this vulnerability, not implementation flaws.

The potential consequences of this vulnerability are significant and diverse. As attackers exploit this weakness, they can manipulate sensitive business flows to cause detrimental effects on the impacted organization. This vulnerability's widespread occurrence underscores that it's a commonly encountered problem across numerous APIs. Detecting this vulnerability is of average complexity, indicating that it might not be immediately obvious or straightforward to spot in any given application.

At the time this article was written, the VAPI project was not yet updated for "Business Logic Flaw", which is a newly introduced vulnerability in this year's top 10 list. However, we can shed light on the importance of addressing this type of vulnerability by delving into a real-world HackerOne case using the "Curve" application.

"The Curve application highlights a component known as "Earn Curve Cash," which offers cashback rewards to users. In this framework, non-premium users are at first constrained to selecting the greatest of three retailers for cashback, whereas premium users appreciate the adaptability of choosing six or more retailers at the same time."

Reproduction Steps:

  1. Login to the non-premium user account.

  2. Navigate to "Earn Curve Cash" and select only 3 retailers (because you are a non-premium user) and click on "Confirm".

  3. You have now added 3 retailers to your account, and you don't have any option to edit or update the added retailers.

  4. Now go back to the "Earn Curve Cash" functionality and make sure to capture the request and response.

  5. Now change the response body to the below JSON content and turn off the burp interception.

  6. Now you can again select any three new retailers and click on "Confirm".

  7. You have now successfully updated or changed the retailers and can use the cashback on all the retailers associated with the curve application.

Vulnerability Credits: praseudo7


OWASP API7:2023 Testing for Server-Side Request Forgery

API7:2023 highlights a critical vulnerability known as Server-Side Request Forgery (SSRF). This type of flaw arises when an API fetches a remote resource without properly validating the user-supplied URI. Consequently, attackers can manipulate the application into sending unauthorized requests to unintended destinations, bypassing potential security measures like firewalls or VPNs.

To demonstrate this vulnerability, we move into the "Arena" directory and then further into the "ServerSurfer" subfolder in the vAPI application. From here, we initiate a GET request to illustrate how an SSRF attack can be executed.


SSRF OWASP API testing with postman

This particular request joins a URL as a GET parameter, demonstrating our intention to evaluate the framework for potential SSRF vulnerabilities. To improve our understanding, let's redirect this request through Burp Suite to encourage examination.


You'll be able to continue with these steps:

  1. Proxy the request into Burp Suite, as indicated.

  2. This will assist you in analyzing the request and its parameters more successfully.


Checking POST Data in vAPI

As evident by the request in the Repeater tool, the response body contains a substantial block of text encoded in base64, which serves as the content of the "data" field.

Upon decoding this text (using the decoder tab in Burp Suite), it becomes evident that it resembles the HTML content of the vAPI developer's website.


To make the method clearer, we begin by opening the web browser and exploring the site https://webhook.site. At this stage, we design a particular web address to return predefined content whenever it's queried. (proof of compromise)


We start by selecting the "New" button found at the upper-right corner of the interface. Inside the 'Content' field, enter our assigned flag for this challenge:


flag{this_is_your_flag}
 
Creating payload using webhook site

Note: Press Make to shut the discourse box, and copy the URL provided.


Copying URL with payload from webhook site

Return to Burp and insert this URL into the GET parameter of our previous request.


Succesful SSRF in VAPI

This time, the information field within the response body is much shorter. Utilize the left-side reviewer to interpret the string and recover the flag, clearly indicating an SSRF-style inclusion of the payload.


OWASP API8:2023 Testing for Security Misconfiguration


The API8:2023 emphasises the pressing importance of effective security configurations to ensure the confidentiality and integrity of APIs and the systems they rely on. These configurations often involve complex settings intended to enhance the flexibility and customization of APIs. However, in the absence of meticulous attention to security best practices during the configuration process, vulnerabilities can emerge, leading to a variety of potential attacks.


In this scenario, we delve into the API's configurations, shedding light on instances where security practices have been overlooked or not rigorously applied. By identifying these gaps, we underscore the necessity of diligent configuration management to thwart potential attacks and safeguard sensitive data and resources.


Now, let's explore how to practically apply this knowledge. Launch Postman and navigate to the designated API7 (NOTE: As of the writing of this article, the vAPI app has not been updated for the 2023 OWASP top 10 list) folder within the collection. Within this specific section, we proceed to demonstrate the concept by initiating a sequence of actions. We create a new user utilising the "Create User" request as outlined in the collection.


Testing API8 security misconfiguration in vAPI

After successfully creating a new user through the "Create User" request and receiving confirmation, proceed to perform the "User Login" request. No request body is required for this step.


Testing Security Misconfiguration using vAPI

Proceed by sending the "Get Key" request and forwarding it to Burp Suite through a proxy.


Checking Security Headers on request in vAPI

We observe the response headers as follows:


Access-Control-Allow-Origin: * 
Access-Control-Allow-Credentials: true
 

These headers indicate that the CORS policy for the given request is misconfigured, allowing it to be invoked from a third-party web application to access the resource and obtain sensitive information like the user's ID, username, password, and auth key.


To illustrate this vulnerability, send the request to the Repeater tool in Burp Suite. Add a random custom Origin: request header, and then proceed to send the request.


Sending request in Burp Repeater

You'll receive a response containing the required flag for this task in the body of the response upon sending the request:


flag{api7_e71b65071645e24ed50a} 

OWASP API9:2023 Testing for Improper Inventory Management


API9:2023 highlights the significance of comprehensive and up-to-date documentation for APIs, considering they often expose a larger number of endpoints compared to traditional web applications. Furthermore, maintaining a proper inventory of hosts and deployed API versions is crucial to mitigating issues like deprecated API versions and exposed debug endpoints.


To illustrate this vulnerability, we'll navigate to the API9 section within the collection. After logging in using the provided credentials, we'll intercept the request in Burp Suite. Followed by transferring the request to the repeater tab for a closer inspection. It becomes apparent that the API enforces a rate limitation of 5 (with a remaining current limit of 4). This signifies that we're only allowed 4 attempts to submit the correct pin, highlighting the significance of rate limiting in mitigating potential abuse.


We proceed with our testing by sending a login request utilising the provided credentials and directing the request through Burp Suite for interception and analysis.


Testing Inventory Management in vAPI app

The absence of a response body suggests that the login attempt was unsuccessful. This implies that the correct pin value for the user "richardbranson" is not in our possession.


Further scrutiny of the response headers reveals the presence of mechanisms enforcing rate limitations. One of our five login attempts has already been used up, leaving us with four. Consequently, conducting a credential-stuffing attack akin to what we performed in task 4 is unfeasible due to the constraints imposed by rate limiting.


To explore an alternative workaround, we investigate whether the v1 version of the API remains accessible. It's plausible that this earlier iteration might lack the rate-limiting implementation. To ascertain this, the next step involves modifying the URL path by replacing "v2" with "v1" and transmitting the modified query via Repeater for evaluation.


Loaded request in Repeater tab

Upon implementing the aforementioned change, the lack of response headers that were observed in previous efforts is noticeable. This omission indicates that the rate-limiting measures are absent from this particular version of the API (API version downgrading), allowing us to proceed with a brute-force attack against the API, giving us the PIN.


Following our successful brute force attack, we managed to identify a matching pin code: 1655.

Now, let's return to Burp Repeater and employ the acquired pin code, 1655, to conduct a test and validate its effectiveness.


vAPI flag for Improper inventory management

In this attempt, our login endeavour proved fruitful, as we received a successful response, granting us access to the page. Consequently, we are rewarded with the flag for this specific task:


flag{api9_81e306bdd20a7734e244}

OWASP API10:2023 Testing for Unsafe Consumption of APIs

API10:2023 emphasizes that a common vulnerability arises from developers placing substantial trust in data acquired from third-party APIs. This misplaced reliance often leads to the adoption of weaker security standards. In their efforts to exploit APIs, attackers frequently target integrated third-party services rather than attempting to directly compromise the target API.

In this context, attackers could exploit the compromised external APIs to launch various injection attacks against the target API. These attacks might encompass SQL injection, command injection, and other vulnerabilities that facilitate code execution. As a consequence, unauthorized control over the target API or even the underlying server could be attained. Additionally, attackers might initiate denial-of-service (DoS) attacks by manipulating or disrupting the data flow originating from the compromised external APIs. Such actions could result in adverse effects on the availability and reliability of the services provided by the target API. Let's explore SQL injection for this.


Loading Target URL in Intruder

SQL injection is a common vulnerability that allows an attacker to manipulate database queries and potentially gain unauthorized access to sensitive data.


You can follow the steps provided to test for injection vulnerabilities in the username or password fields by sending the request to Intruder and configuring the payload position and attack type as described.


Loading payloads in Burp Suite Intruder

We will follow these steps to test for SQL injection vulnerabilities using the provided payload list:


  1. In Burp Suite's Intruder, navigate to the Payloads tab.

  2. Under Payload Options, select "Payload type" as "Simple list".

  3. Click the "Add..." button to add payloads from the suggested list:


'
''
;%00
--
-- -
""
;
' OR '1
' OR 1 -- -
" OR "" = "
" OR 1 = 1 -- -
' OR '' = '
OR 1=1

More SQL injection payloads can be found in this SQLi wordlist.

Once the payloads are added, click "Start attack" to initiate the SQL injection testing.

By running this attack, we'll be testing each payload against the username field to check if the API is vulnerable to SQL injection attacks. Next, we review the responses to see if any of the payloads trigger unexpected behavior or reveal any sensitive information.

To perform the attack with the specified payload list, we can:

In the Payloads tab of Burp Suite's Intruder, scroll down to the "Payload Encoding" section.

Uncheck the "URL-encode these characters" option.

Make sure that the rest of the settings are configured as desired.

Finally, click the "Start Attack" button to initiate the attack with the provided payloads.

This will execute the attack against the target API's username field using the specified payloads without URL-encoding them. Observe the responses to identify any potential SQL injection vulnerabilities or unexpected behavior.


Using intruder to test SQLi

Based on the response analysis, it's clear that the API is susceptible to SQL injection attacks. The payload testing generated various response codes, including 403 (forbidden) and 500 (internal server error). The 500 code, coupled with the SQL syntax error message in the response, strongly suggests that input for the username key is directly used in SQL queries without proper input validation. The presence of a MySQL error message indicates the backend database's technology. This points to a potential vulnerability for SQL injection attacks.



This blog offers a comprehensive exploration of API security assessments, covering real-world scenarios like broken authorizations and injection attacks. This experience equips individuals with practical tools and techniques, enhancing their ability to safeguard sensitive data and contribute to a more secure digital environment. The insights gained from this blog and lab exercises will be crucial in protecting against API vulnerabilities.



References:

 

Register for instructor-led online courses today!


Check out our free programs!


Contact us with your custom pen testing needs at: info@darkrelay.com or WhatsApp.

1,362 views

2件のコメント


How r u


いいね!

Hi 👋

いいね!
bottom of page