Basics of API Security – Part 2

In the first part of this 2 part blog post series, we have covered vAPI setup and OWASP Top 3. In this part we will continue with the remaining 7 vulnerabilities. If you have not covered that I would suggest reading Part one first. Lets get started right away.

To quickly revise following are the API OWASP Top 10: –


API4 – Unrestricted Resource Consumption

What is Unrestricted Resource Consumption?

This vulnerability occurs when there is no rate limiting applied to the API endpoint resource and an adversary could consume the endpoint without any restriction to it. Usually to exploit this an adversary launches automated attacks where the script sends multiple requests to the same endpoint causing disruption of the service or even DoS in some cases.
As described under OWASP guidelines, an API is vulnerable to Unrestricted Resource Consumption if any of the following limits are missing or misconfigured:

  • Execution timeouts
  • Maximum allocable memory
  • Maximum number of file descriptors
  • Maximum number of processes
  • Maximum upload file size
  • Number of operations to perform in a single API client request (e.g. GraphQL batching)
  • Number of records per page to return in a single request-response
  • Third-party service providers’ spending limit

Examples

Scenario 1 – No rate limit

A forgot password functionality present in one of the application allows a user to send an OTP to their number as part of 2 factor authentication. Each message costs 5 Rupees for local messages and 20 Rupees for international message.

POST /sms/send_reset_pass_code

{
  "phone_number": "7685940301"
}

Since there is no rate limit on this API, an adversary can call this API endpoint repetitively which can cause a huge financial loss to the organization in a matter of minutes.

Scenario 2 – Unrestricted File Upload

An API endpoint allows a user to upload files, but there is no limit on the size of the file or number of files that a user can upload.

POST /upload_file

{
  "file_info": " 
  {
    uploadFile(name: \"nosize.pdf\", base64_encode: \"R0FOIEFOR0xJVA…\")
  }

Here an adversary can do 2 thins.

  1. Upload a file which is huge in size thus filling up the storage space on the server side.
  2. Upload multiple files resulting in filling up of storage space on the server side.

Mitigation Steps

Define and enforce limits on consumption of server side resource.

  • Define and enforce limits on number of times a user can call an API endpoint. This limit can be based on number of interactions a user can have with an endpoint within a timeframe. The should be defined based on business needs.
  • Set billing alerts on endpoints which generate direct cost against organization.

vAPI Steps

Looking at API4 folder we can see total 3 endpoints. one for sending the OTP to the registered mobile number. Second for verifying the OTP and third for fetching the details. To solve this we need to guess the valid OTP to proceed.

So we first generate a request to send an OTP to the desired number. And since we don’t have the means to receive the OTP, next step is to guess the same.

Since there is no rate limit set on how many attempts a user can make in guess the valid OTP, we can automate this. For the same we can use a wordlist which has list of all the 4 digit numbers starting from 0000 to 9999. Using the wordlist we can run the script until a valid response is received. For this we will use the ffuf utility, with the following command.

ffuf -u http://192.168.1.71/vapi/api4/otp/verify -w /usr/share/SecLists/Fuzzing/4-digits-0000-9999.txt:FUZZ -d '{"otp":"FUZZ"}' -X POST -H "Content-Type: applcication/json" -mc 200

And as shown in the screenshot below, after letting it run for some time, we receive a successful message. The OTP found is “1872”.

Putting in the same OTP provides us with a success message with following response.

{
    "success": "true",
    "key": "FZvjaFlMgUfnpFJDhKx-92xeXx_sCr7Y"
}

And once we are Authenticated, we can call the /vapi/api4/user get details endpoint to get our flag.

[
    {
        "id": 1,
        "firstname": "john",
        "lastname": "flag{api4_ce696239323ea5b2d015}"
    }
]

API5 – Broken Function Level Authorization

What is Broken Function Level Authorization

When an adversary is able to access a functionality which by business logic should have not been accessible, is when the application is said to be vulnerable to Broken Function Level Authorization. For example a regular user is able to access an endpoint which should only be accessible by an admin user. Also, similarly user 1 might be able to access endpoints which should only be accessible by user 2, and vice versa.

Example

Scenario 1

An application have a maker and checker functionality. Maker can raise a bug request using the /api/bug/submit endpoint. And to approve the bug the checker can call the /api/bug/approve/{{bug_id}} endpoint to approve the raised but. But due to lack of authorization check the maker themselves are able to call the endpoint and approve the raised bug.

{
  "bugid": "23",
  "approval_status":"success"
}

Scenario 2

An API contains an endpoint that should be exposed only to administrators – GET /api/admin/v1/users/all. This endpoint returns the details of all the users of the application and does not implement function level authorization checks. An attacker who learned the API structure takes an educated guess and manages to access this endpoint, which exposes sensitive details of the users of the application.

Mitigation Steps

  • Proper Authorization checks should be put in place using authorization tokens which are validated rigorously in the backend against each API endpoints.
  • A manual assessment for each endpoint should be performed against all the business logic test cases, in order to make sure they are meeting business expectations.

vAPI Steps

This challenge gives us 3 API endpoints using the first we are able to fetch the details of one user and using the second we are able to fetch them.

The trick seems to be on the GET API endpoint. If somehow we are able to manipulate the user id parameter of the endpoint we might be able get a hold of unauthorized information. Changing the value from 0 to 1 does not work and gives us an error.

Next we can try automating the attack by trying various guessable values that we can put in the place of app5_id parameter. For the same we will be using ffuf utility, which will utilize wordlist containing guessable API endpoints parameters. After few failed attempts we are able to get the endpoint using which we are able to expose all the user details. The endpoint is as follows:

http://192.168.1.71/vapi/api5/users

And the command used for the same is as follows:

ffuf -u http://192.168.1.71/vapi/api5/FUZZ -w /usr/share/SecLists/Discovery/Web-Content/api/objects-lowercase.txt:FUZZ -X GET -H "Content-Type: applcication/json" -H "Authorization-Token: dGVzdHVzZXIyOnRlc3QxMjM=" -mc 200 -s

As shown in the image below we get a 200 OK response for this endpoint.

Calling the same endpoint we are able to see all the users details.


API6 – Unrestricted Access to Sensitive Business Flows

What is Unrestricted Access to Sensitive Business Flows?

All the applications are created to serve a purpose and function in harmony to the logic of serving that purpose. An application is vulnerable to Unrestricted access to sensitive business flows when an adversary is able to circumvent that logic and cause harm to the logic of that application.

Example

  • An adversary able to buy an item on a shopping website and while checking out the item, the adversary is able to alter the amount of the bought item, leading to financial loss to business.
  • While trying to buy a product from a seller’s website, the application gives an option to apply for coupons to get discounts. But the coupons are easy to guess and bruteforcable. An adversary can automate the coupon guessing script using a custom built coupon list and get discounts based on coupons found.

Mitigation Steps

  • Write user stories for each functionality of the application while application is under development. These user stories should be submitted to the security teams who can submit evil stories against the given user stories. These evil stories would serve as a guideline for the developers for the areas they need to take care while building the application.
  • Conduct a thorough manual pentest of the application. Proper functioning of the application should be explained to the team performing the pentest and due care should be taken to make sure all the logical scenarios are covered as a part of the pentest that could harm the business.

vAPI Steps

There are 2 API endpoints present as part of this exercise. First is POST endpoint where you are able to add a user with other details. Filling in the details and submitting those adds the user which we can get the details of from the GET API.

As shown in the figure, 100 credits were added and we also get a hold of the flag.


API7 – Server Side Request Forgery

What is SSRF?

SSRF or server side request forgery occurs when an adversary is able to manipulate a request submitted to the server in such a way that the response received from the server reveals sensitive information about the server itself. Using this the adversary can also edit the files present at server side.

Example

Scenario 1

A social network allows users to upload profile pictures. The user can choose either to upload the image file from their machine, or provide the URL of the image. Choosing the second, will trigger the following API call:

POST /api/profile/upload_picture

{
  "picture_url": "http://example.com/profile_pic.jpg"
}

An attacker can send a malicious URL and initiate port scanning within the internal network using the API Endpoint.

{
  "picture_url": "localhost:8080"
}

Based on the response time, the attacker can figure out whether the port is open or not.

Scenario 2

An application has implemented webhooks as part of new functionality of the application, where a user can check for upcoming events by navigating to their handler page. But instead of putting the http url an adversary is able to access internal files hosted on the server by using file:/// attribute.

file:///etc/passwd

Mitigation Steps

Mitigating by Design:

  • Implement segregation on network level for the APIs responsible for fetching resources remotely, thus the segregation should not allow the endpoints to fetch local resources.
  • Implement whitelisting on what can be fetched using the endpoints.

Code Based Fixes:

  • Disable redirections.
  • Define the protocols that can be used while using the endpoint.
  • If using XML configure DTD properly so that only the required info can be fetched.
  • Validate user input properly.

SSRF Demo

To perform SSRF hands on I’ve used BenjiTrapp’s repo which can be found here. For installation I would recommend using docker instance of it. The installation instructions are provided in the repo itself. But the easiest way to download and deploy the instance is as follows.

$ docker pull ghcr.io/benjitrapp/ssrf-playground:main
$ docker run docker run --name ssrf-playground -p 8080:80 -d -t ssrf-playground

After the instance is setup open the webpage and follow along. Navigate on the browser to where the ssrf-playground is hosted. In my case it is
http://192.168.1.83:8080/

In the text box use the file:/// protocol to access the internal files. For example:

file:///etc/flag.txt to grab the flag
file:///etc/passwd to grab the passwd file


API8 – Security Misconfiguration

What is Security Misconfiguration?

When an API endpoint is not hardened before implementation and might be running on default configurations which have publicly known exploits/entrypoints. Security misconfiguration can also occur when systems are not patched to their latest version, or extra features of the endpoint are enabled.

Example

Scenario 1

A third party API endpoint is implemented which has a default authentication mechanism with publicly available secret key. While implementing the endpoint the developer is suppose to reset the password and change it. But this was not done leading to an adversary able to authenticate themselves.

Scenario 2

An API endpoint implemented CORS but instead of properly defining the list of valid URLs that can have access to the endpoints’s content it is set to * which can lead to a malicious website having access to the victim’s data.

Mitigation Steps

  • Configure CORS properly such that the Access-Control-Allow-Origin header is defined properly.
  • Enable authentication on critical resources, so that sensitive information cannot be passed until an authorized user is present.
  • Only allow trusted sites
  • Disallow wildcards.

vAPI Steps

Open API7 and using the post request create a new user. After that login to the user using the second endpoint.

Using the third endpoint send the get key request to receive the key. Send the request to burp and notice that in the response Access-Control-Allow-Origin is set to * .
In the request, add origin: superevil.com and send the request to see that in the response Access-Control-Allow-Origin is reflecting the domain which we set.


API9 – Improper Inventory Management

What is Improper Inventory Management?

When older versions of an API reveal sensitive information which can lead to potential compromise of the currently running version of the API is when an API is said to be vulnerable to Improper inventory management.

Example

An API is running on a version 5 which loads as
coupons/category/v5/fetch
But when v5 is changed to v3 or v2 it was found that those versions were still live and responding.

Mitigation Steps

  • Older versions of API endpoints should be removed from production environment once newer versions are available.
  • The versioning of the API should not be made guessable easily

vAPI Steps

Open API9 and submit the POST request with bogus pin, to get a response. Send the request to Burp.

Since we don’t know the pin we get an empty body back. In the response we could see that there is rate limit and we only have 3 tries left, therefore we cannot bruteforce here. The endpoint path also suggests that this is a version 2 of this endpoint. After changing the version to 1 we could see that the older version of the API is present and there is no rate limit implemented here.

Since there are 4 stars present in the PIN parameter we can guess that the pin length could be 4 digit. For bruteforcing we will use ffuf with the following command:

ffuf -u http://192.168.1.83/vapi/api9/v1/user/login -w /usr/share/SecLists/Fuzzing/4-digits-0000-9999.txt -X POST -d '{"username":"richardbranson","pin":"FUZZ"}' -H "Content-Type: application/json" -fs 0

Upon running the same we could see that the PIN 1655 comes as success.

Submitting the same on v2 endpoint gives us a successful response.


API10 – Unsafe Consumption of APIs

What is Unsafe Consumption of APIs?

An API is vulnerable to Unsafe Consumption of APIs when an API consumes data from a third party API and adopt weaker security standards such as communicating over unencrypted channel or does not validate/sanitize the data received or redirects are not restricted or there is no rate limit implemented.

Examples

Scenario 1

An API is integrated with a backend API of another application where API 1 is consuming data from API 2. Because the integration is a backend internal communication, the connection is made over HTTP and the data received from the API 2 is not validated/sanitized. An adversary present inside the network could intercept the traffic and insert malicious payload in API 2 which could compromise the application of API 1.

Scenario 2

An API integrates with a third-party service provider to safely store sensitive user medical information. Data is sent over a secure connection using an HTTP request like the one below:

POST /user/store_phr_record
{
  "genome": "ACTAGTAG__TTGADDAAIICCTT…"
}

Bad actors found a way to compromise the third-party API and it starts responding with a 308 Permanent Redirect to requests like the previous one.

HTTP/1.1 308 Permanent Redirect
Location: https://attacker.com/

Since the API blindly follows the third-party redirects, it will repeat the exact same request including the user’s sensitive data, but this time to the attacker’s server.

Mitigation Steps

Whenever consuming an API from a different resource following points should be checked: –

  • Always consume APIs over an encrypted channel
  • While consuming the data, it should be made suer that all the parameters are properly sanitized and validated.
  • Check for any redirections and follow them only if it is required by the logic in place. This can be achieved by preparing an allow list.
  • Put a limit on how much resource consumption can the third party API do and never let it exceed that.
  • Implement time out in case of third party not responding.

As this is related to how the API is being consumed, it can be vulnerable to any of the above 9 explained vulnerabilities. This vulnerability is more to deal with a proper security architecture setup which if misconfigured on any of the above talked points can lead to attacks such as Denial of Service or information leakage or confidentiality or integrity loss to the data being consumed. It should also be noted that a third party might be providing it’s services to multiple such clients and if they do not follow proper data consumption security guidelines, might end up compromising data for all of their clients.

Leave a Reply

Your email address will not be published. Required fields are marked *