Basics of API Security – Part 1

API Security

In this blog post we will be covering the basics of API security. According to me the best way for covering the basics would be to go through and understand OWASP Top 10, with some hands on. Thus, in this blog post I’ll be explaining what are OWASP top 10 and we will also setup a lab environment where we will be doing hands on.

For hands on, I’ll be using the Vulnerable API or vAPI. The OWASP top 10 vulnerabilities covered under this setup are a version older than 2023, thus it is covering vulnerabilities like Injection and missing vulnerabilities like SSRF but we will cover that using another setup which is made specifically for SSRF. This setup I’ll be covering under OWASP API7 vulnerability discussion, which will be covered in part 2 of this blog post. Now with all of this out of the way, let us begin with our setup.

Setting up vAPI

Git clone vAPI from the link provided above. Navigate to the folder and follow the following steps. I’m using docker to run my setup.

docker-compose up -d

For the first time the command will pull all the required docker components and once pulled successfully deploy the containers. The deployed containers can be seen below.

Thus as shown below, 3 containers are deployed:

  • vapi_www
  • phpmyadmin/phpmyadmin
  • mysql:8.0

Next we will import the vAPI postman collection inside postman. Postman collection for this project can be found in vapi/postman folder. Import the same directly to get started with the APIs.

Before proceeding, make sure to check out the environment variable section. By default it is set to localhost. Change that to the appropriate IP in case you are running postman on different machine. Like in my case I decided to run vAPI on Kali Virtual box where as my postman ran on the host machine. So I changed the {{host}} environment variable’s value to my Kali Virtual Box’s IP.

Once done, I would also recommend to redirect your traffic to burp, by setting a proxy in postman.

One last thing that we would need as part of this setup is mobile device. For this we can use something like bluestacks or Android studio. I’m using android studio. Now, like me if you too are using docker deployed vAPI, you’ll not be able to run android studio and docker on the same machine, because HYPERV and docker don’t really like each other. Therefore I’m, running android studio on the host machine and vAPI on Kali Virtual box as stated earlier.

We will not go into Android studio installation and setup details in this blog. There are numerous blog posts out there for the same. So, once you are done with the setup and launched your emulator device, you’ll need to install the APK provided as part of this project. The same can be found at vapi/Resources/API3_APK folder. Just drag and drop the APK into the emulator. I’m using Pixel 3a as the android emulator image.

This should conclude our initial setup of VAPI, and now let the learning begin.


OWASP API Top 10 – 2023

We will be covering following OWASP Top 10 as part of this 2 part blog post


API1 – Broken Object Level Authorization (BOLA)

What is BOLA?

Broken object level authorization occur by manipulating one or multiple parameters of an API. These parameters can be anything from sequential integers, UUIDs, or generic strings. Once an adversary is able to guess the value of that parameter and alter them accordingly leading to access of unauthorized data. This occurs only if the backend authorization checks are missing.

These kind of attacks are usually common on API endpoints because An API doesn’t open user sessions and will treat every query received as an independent request. This means every query needs to include an authorization header to let the API know that the request is legit and can be processed safely. This check has to happen on server side and is usually missed, leading to BOLA.

Examples

<u>URL</u>
http://{{host}}/vapi/api1/user/{{api1_id}}
<u>Headers</u>
Authorization-Token: {{api1_auth}}

In the above example a get request is being generated with app1_id parameter. An adversary will generally look to manipulate this value and get to the unauthorized data. The authentication part is being handled by the Authorization Token which is randomly generated but using the same a back-end check must be done to see if the user is authorized or not. Otherwise an authenticated user will be able to get access to unauthorized data, and this may lead to Horizontal Privilege Escalation or Vertical Privilege Escalation.

Mitigations

  1. Implementing proper Authorization Mechanisms: – Authorization comes into picture once a user has authenticated themselves. Many API calls might be checking for Authentication but if they are missing authorization checks they will end up exposing sensitive data to users who should not have access to it. Proper checks should be in place across all API calls which make sure whoever is accessing the API is an authorized person.
  2. Randomizing the UUIDs: – UUIDs or Universally Unique Identifiers are nothing but random set of string which when appended to an API leads to a certain data or response from the server. Many times developers end up using this as a guessable value, either by using incremental values or guessable names which exposes these APIs to be easily guessed by an adversary. Rather, these values should be a complete random value of string which are not guessable at all. This will make an adversary’s attack surface shorter.

vAPI Steps

Open the API1 folder and we can see one post request to create one user and one Get request to retrieve the user. Filling in the POST details creates a new user.

And in the GET request shows us what we just added. For this exploit, we can send the request to Burp and try modifying the api1_id parameter to 1.

http://{{host}}/vapi/api1/user/{{api1_id}}

As we can see we are able to access the other user’s details as well and reveal the flag.


API2 – Broken Authentication

What is Broken Authentication?

This vulnerability occurs when the authentication mechanism is not setup properly and therefore can be bypassed by an adversary leading to a complete compromise of that user account.

Example

Scenario 1 – Credential Stuffing

URL: – http://{{host}}/login

Body: –

{
    "email":"",
    "password":""
}

In the example above, the login form passes email and password as 2 parameters. An adversary can run an automated attack fuzzing the 2 parameters until a satisfactory response is received.

Scenario 2 – Weak Authorization

URL: – http://{{host}}/forgotpasword

Body: –

Authorization: Bearer <token>

{
	"email": "<new_email_address>",
	"password": "<newpassword>",
	"confpassword": "<confpassword>"
}

In the scenario above if the authorization token is not mapped properly with individual user and then is not validated in the back-end, an adversary will be able to change password of a victim and takeover the victim’s account.

Mitigation Steps

  • Rate limiting, should be in place to ensure that an adversary is not able to call an API in such a manner that it may impact availability or cause financial losses.
  • CAPTCHA, is a great option for putting a stop to automated attacks, in places such as login, forgot password pages etc. CAPTCHA can be implemented to stop automated attacks.
  • Lockout Mechanism should be in place to discourage bruteforce attacks.
  • Whitelisting – Limit who can call the API and from and from where.

vAPI Steps

For this the POST request looks something like following:

{
    "email":"",
    "password":""
}

So we enter bogus values in email and password, and submit to see the response. Following response is received:

{
    "success": "false",
    "cause": "usernameOrPasswordIncorrect"
}

One positive thing to note here is the error message, is a generic error message and does not tell us whether username is incorrect or password is. This is a good practice. The attack we will be performing here is brute force attack. For the same, list of credentials is provided in the vapi repository.

Navigate inside the vAPI git repo and go to the location vapi/Resources/API2_CredentialStuffing

Here you can find creds.csv. The file contains comma separated email and password list. For the purpose of bruteforcing we will get emails in one file and passwords in another. The same is accomplished by using following command.

cat creds.csv | cut -d ',' -f1 > emails.txtcat creds.csv | cut -d ',' -f2 > passwords.txt

Now that we have our list of emails and passwords we need to try all the combinations of them. For the same we will use fuff.

ffuf -u <http://192.168.1.83/vapi/api2/user/login> -w ~/github/vapi/Resources/API2_CredentialStuffing/emails.txt:FUZZ1 -w ~/github/vapi/Resources/API2_CredentialStuffing/passwords.txt:FUZZ2 -d '{"email":"FUZZ1", "password":"FUZZ2"}' -X POST -H "Content-Type: applcication/json" -mc 200 -mode pitchfork -s

Here we are fuzzing the email and password parameters. The meaning of the switches used in the above command is as follows

  • u: Provides the target URL
  • w: The word list to be used and assign a variable against that wordlist in this case FUZZ1 for emails and FUZZ2 for password
  • d: Post data to target. In this case against email we give the list of email.txt denoted by FUZZ1 and password for password.txt denoted by FUZZ2
  • X: defines what method to use POST, GET etc.
  • H: is used to add headers
  • mc: is used to filter out only 200 response code
  • s: is for silent mode (Turn off Verbose)
  • mode is type of bruteforce attack which is pitchfork in our case. We can also use cluster bomb if pitchfork fails.

Running the above commands results in 3 successful login attempts.

Using the same when we try to login, we are successful and we get the token.


API3 – Broken Object Property Level Authorization

What is Broken Object Property Level Authorization?

This vulnerability occurs when an API endpoint exposes more information than it needs to. The information leakage can range from sensitive to very sensitive. At times, an adversary might also be able to manipulate the exposed sensitive information

Example

Scenario 1 – Sensitive information Disclosure

Upon submitting a request the application replies with a response in which it is exposing sensitive information.

POST /reportuser

Response:

{
  "operationName":"reportUser",
  "variables":{
    "userId": 313,
    "reason":["offensive behavior"]
  },
  
  "query":"mutation reportUser($userId: ID!, $reason: String!) {
    reportUser(userId: $userId, reason: $reason) {
      status
      message
      reportedUser {
        id
        fullName
        recentLocation
      }
    }
  }"
}

In the example above, the user reports another user for offensive behavior and the server responds with id, fullname and location of the reported user.

Scenario 2 – Parameter Addition

A user books a hotel room but the amount option is not available to the user while booking the room.

{
  "approved": true,
  "comment": "Check-in is after 3pm"
}

But while submitting the request the adversary adds the “total_stay_price” parameter to the request and was able to book the hotel with the desired price.

{
  "approved": true,
  "comment": "Check-in is after 3pm",
  "total_stay_price": "$1"
}

Mitigation Steps

  • The response of the parameter should never contain unnecessary sensitive information. An unnecessary information is such. information that servers no purpose to the user it is responding to. Response should be structured according to the business/functional requirements.
  • Thoroughly validate the user input. Never pass user input directly to a variable.
  • Which object property can be modified should be properly defined.

vAPI Steps

Navigate to vapi/Resources/API3_APK and install “TheCommentApp.apk” application to the android virtual machine.

Next, set the proxy so that the traffic routs through burp. In my case the proxy was set to 127.0.0.1:8080.

Open the app and give it a baseurl which should be where our vAPI instance is running.

Next, go to postman and navigate to API3. There we see an option to create a user. Using the same we create an admin user with password as admin and submit to create a user for us to login in the android app.

Once the user is created we are successfully able to login into the app, where we see an option to comment. Once we hit the comment and look at the response, we are able to see that the request reveals sensitive information about the person who commented.

[
	{
		"id":1,
		"postid":"1",
		"deviceid":"flag{api3_0bad677bfc504c75ff72}",
		"latitude":"45.5426274",
		"longitude":"-122.7944111",
		"commenttext":"THIS POST IS SH***Y",
		"username":"baduser007"
	}
]

As shown above, information such as deviceid, latitude, longitude and username are sensitive information which should not have been revealed.

Leave a Reply

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