Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Pentesting APIs

You're reading from   Pentesting APIs A practical guide to discovering, fingerprinting, and exploiting APIs

Arrow left icon
Product type Paperback
Published in Sep 2024
Publisher Packt
ISBN-13 9781837633166
Length 290 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Maurício Harley Maurício Harley
Author Profile Icon Maurício Harley
Maurício Harley
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Part 1: Introduction to API Security
2. Chapter 1: Understanding APIs and their Security Landscape FREE CHAPTER 3. Chapter 2: Setting Up the Penetration Testing Environment 4. Part 2: API Information Gathering and AuthN/AuthZ Testing
5. Chapter 3: API Reconnaissance and Information Gathering 6. Chapter 4: Authentication and Authorization Testing 7. Part 3: API Basic Attacks
8. Chapter 5: Injection Attacks and Validation Testing 9. Chapter 6: Error Handling and Exception Testing 10. Chapter 7: Denial of Service and Rate-Limiting Testing 11. Part 4: API Advanced Topics
12. Chapter 8: Data Exposure and Sensitive Information Leakage 13. Chapter 9: API Abuse and Business Logic Testing 14. Part 5: API Security Best Practices
15. Chapter 10: Secure Coding Practices for APIs 16. Index 17. Other Books You May Enjoy

Testing for NoSQL injection

We have covered a reasonable ground of SQL injection attacks, but the fact is there is a considerable number of applications (and API endpoints) on the internet that need to handle unstructured data, such as documents, emails, social media posts, images, and audio and video files. For these use cases, relational databases are not the best choice since not all elements inside such databases have direct relationships, which would cause its management an unfair task. Carlo Strozzi introduced the concept of NoSQL databases in 1998 with his Strozzi NoSQL open source software (OSS) proposal. Since then, we’ve seen the release of many awesome products out there, such as MongoDB, Apache Cassandra, and Neo4j, just to name a few.

As these databases, as their type implies, are not SQL ones, they do not use SQL for making queries or responding to them. Hence, our SQL injection techniques do not work here. We need to approach them in another way. In this scenario, there are basically three types of attacks that we can leverage to achieve success: syntax injection, object injection, and operator injection. Let’s separately cover each of them.

Syntax injection

Syntax injection stands out as the prevalent form of NoSQL injection. In this type of attack, the pentester embeds harmful code within user input, which the API then integrates into a NoSQL query. This injected code has the potential to disrupt the syntax of the query, evade filters, or even trigger the execution of unauthorized commands within the database.

The core concept of a NoSQL syntax injection attack revolves around manipulating user input. The pentester crafts malicious code and injects it into parameters that are then incorporated into the NoSQL query by the vulnerable API. One common scenario where NoSQL syntax injection attacks occur is in API endpoints that handle user authentication. For instance, an API might have a login endpoint where users submit their credentials for authentication. If the API uses a NoSQL database to store user data and does not properly sanitize user input, attackers can inject malicious code into the login credentials to bypass authentication checks or gain unauthorized access to user accounts.

In a NoSQL syntax injection attack, you as a pentester can leverage various techniques to evade detection and achieve your objectives. For example, you might use wildcard characters, regular expressions, or other syntax manipulation techniques to craft payloads that disrupt the query’s structure or evade input validation mechanisms. By carefully constructing their payloads, you can exploit vulnerabilities in the API endpoint and compromise the integrity and confidentiality of the database.

Here’s how it works. Consider an API endpoint that does user authentication with the help of a NoSQL database. The endpoint accepts GET requests in the following format:

GET /api/login?username=$username&password=$password

Internally, the API endpoint translates the request into a NoSQL query like this:

db.users.find({ username: '$username', password: '$password' })

Observe that there was absolutely no validation or filtering of the input provided by the requester, neither on the username nor on the password fields. We have a candidate for a NoSQL syntax injection attack! We could slightly change this request to something like the following:

GET /api/login?username[$regex]=.*&password[$regex]=.*

We just manipulated the query to use a regular expression that represents any username and any password (. matches any character and * matches 0 or more occurrences of the preceding character). We just bypassed the authentication control of the endpoint…

Object injection

NoSQL object injection attacks pose a distinct threat to APIs that interact with these types of databases. Unlike traditional NoSQL attacks that target the raw query itself, object injection attacks exploit weaknesses in how APIs handle user-provided data.

Imagine an API uses a secret language (serialization) to convert user data into a format the NoSQL database understands. You as a pentester can exploit vulnerabilities in this translation process. You could craft malicious data that, when translated (deserialized) by the API, manipulates internal object structures. This can lead to unexpected consequences, potentially allowing you to run unauthorized code or access sensitive data you shouldn’t.

A common scenario involves APIs that serialize user-supplied data (such as JSON) before storing it in the NoSQL database. If the API doesn’t check the data carefully before translation, a pentester can sneak in malicious objects that exploit weaknesses in the deserialization process. Think of it like tricking the translator into saying something completely different than what you intended. This allows you to gain an unfair advantage within the system.

As an example, we can consider an API endpoint that allows users to filter products based on price and category. The following JavaScript code shows a possible query that this endpoint could build to send to the database:

const filterObject = { 
    price: { 
        $gt: req.query.minPrice 
    }, 
    category: req.query.category 
};
db.products.find(filterObject);

The filterObject constant receives data directly provided by the requester (minPrice and category). This is then used on the db.products.find query. Continuing with our example, a valid GET request to select products with a minimum price of 100 and belonging to the furniture category would be the following:

GET /products?minPrice=100&category=furniture

It doesn’t matter if it’s a GET or POST request. The same approach can be used for pretty much any verb here. How can we transform this into an object injection attack? Simple. We insert an initially unexpected object as part of the query. With this, the endpoint will grant us admin access besides checking the original product’s category. Look at the following example:

GET /products?minPrice=100&category={"$and": [{category: "furniture"}, {"isAdmin": true}]}

If the endpoint is not correctly configured to sanitize this input, admin access to the database could be granted, and then other stages of the attack could happen. The isAdmin object was not intended to be part of a legitimate query, but because I previously knew that this database would accept it as a possible parameter (of course, after doing my enumeration/fingerprinting tasks), I’m a bit safer to assume it will work. The success of a NoSQL object injection attack largely depends on how the API handles user-supplied objects and incorporates them into its operations. Nevertheless, the fundamental concept of altering object structure to achieve unauthorized access or tamper with data holds true across different NoSQL database platforms.

Operator injection

At this stage, you may have already deduced we are talking about inserting NoSQL operators as part of this sort of attack. Yeah – I was quite a Captain Obvious here, but consider this an attempt to give you some relaxation after this massive reading. Fortunately, you already have access to a small yet useful table with some operators that could be leveraged here.

NoSQL databases offer a tempting combination of power and flexibility, but they also introduce new security challenges. NoSQL operator injection attacks lurk in the shadows, waiting to exploit APIs that interact with these databases. These attacks target vulnerabilities in APIs that build queries “on the fly” based on user input. Devious attackers can then inject specially crafted data to manipulate how the database interprets the query. This attack has some similarities with syntax injection; however, this one is not breaking the initially predicted syntax of a query but just twisting it.

Imagine an API that allows users to search for products based on various filters, such as price or category, as we’ve previously seen. The API might construct a NoSQL query that dynamically incorporates user-supplied values. Here’s the problem: if the API doesn’t carefully check this user input, you can sneak in malicious operators. These operators, which are normally used for legitimate filtering, can be twisted to alter the query’s logic entirely. Think of it like someone manipulating the search bar on a library website to return unexpected results. Sounds familiar?

Let’s keep with our example of a website that provides products that in turn are organized into categories. An endpoint to show all products belonging to the tools category could be something like the following:

GET /api/products?category=tools

This translates into the following NoSQL query:

db.products.find({ category: '$category' })

Simple, yet powerful. Now, suppose the user I’m using to interact with this endpoint does not have access to see products belonging to other categories, but the endpoint is not fully applying this control. So, how could I bypass it? Take a look:

GET /api/products?category[$ne]=tools

The $ne part corresponds to a NoSQL operator that means “not equal.” So, we are asking the API endpoint to show all products whose categories are not tools. Fantastic, isn’t it?! I’ve provided a list of MongoDB operators for your convenience. Observe not all NoSQL databases follow the same rule, so you can either try to fingerprint the backend database or combine operators from different database engines:

Operator

Meaning

$eq

Matches values that are equal to a specified value

$ne

Matches all values that are not equal to a specified value

$gt

Matches values that are greater than a specified value

$gte

Matches values that are greater than or equal to a specified value

$in

Matches any of the values specified in an array

$lt

Matches values that are less than a specified value

$lte

Matches values that are less than or equal to a specified value

$nin

Matches none of the values specified in an array

Table 5.1 – MongoDB comparison operators (Source: MongoDB official documentation)

Now, let’s take a look at this in practice with an exercise.

Exploiting NoSQL injection on crAPI

It’s time to get back to our old friend, crAPI. We well know it exposes a considerable number of endpoints, so let’s verify if there’s one we can pick to exercise this. Start your crAPI instance. Let’s also use our other friend, Burp Suite, to help us with this quest. Launch Burp Suite and start a new project with the defaults. You will need to use Burp’s browser in your lab since all services are listening locally (localhost). Access crAPI. If you still don’t have an account, create one by following the straightforward process. After logging in, go to the Shop area, as shown in Figure 5.5:

Figure 5.5 – crAPI’s Shop area

Figure 5.5 – crAPI’s Shop area

Observe our initial balance: $100. Our objective here is to buy an item for less than what it really costs or increase our balance. If we have a coupon, we can add its code using the corresponding button. The point is, we don’t have any code – yet… Click on the Add Coupons button and type anything. You will receive an error message:

Figure 5.6 – Invalid coupon code

Figure 5.6 – Invalid coupon code

This part of crAPI uses a NoSQL database (MongoDB, to be more precise) to store the coupons. Now, go to Burp Suite to check the HTTP connection history. The last item will show you which endpoint crAPI is using to check this code. You will realize it is /community/api/v2/coupon/validate-coupon. We also confirm the endpoint returns a 500 error code with an empty JSON structure. Now, let’s use another resource of Burp to help us discover crAPI’s coupons. Figure 5.7 shows an example of sending a request to the coupon validation endpoint:

Figure 5.7 – crAPI’s coupon validation endpoint

Figure 5.7 – crAPI’s coupon validation endpoint

We’ll do something similar to what we did with the vAPI Python application in the SQL injection section. Right-click on this coupon validation request (still on the HTTP history tab) and select Send to Intruder, then move to this section of the tool. The first subsection you’ll see is Positions. Observe the request structure is a simple JSON structure with a single key and value:

{
  "coupon_code": "blabla"
}

We want to fuzz the "blabla" part with lots of junk that will be pulled from the payload list. Select this whole "blabla" text, including the double quotes, and click on the Add § button. This is used to instruct Burp on which section of the request must be fuzzed. You will see the text is now surrounded by §. Set Attack type as Sniper. Now, move to the Payloads subsection. Set Payload type as Simple and click on the Load… button on the block that says Payload settings [Simple list]. You can load multiple files at once. Do this if you have more than one. Deselect the last checkmark that says URL encode these characters. This will avoid unnecessary encoding when submitting the payloads to the target. Finally, click on Start Attack. Remember – Burp Community may take more time as the Intruder feature has intentionally received some delays between sent payloads.

Again, switch to the Response tab inside Intruder’s attack screen. Many of the attempts will result in error codes, such as 422 in this example, but should you be successful, you will have at least one 200 code, like the one on the following screenshot, which will disclose a coupon code to you. The TRAC075 code means $75:

Figure 5.8 – crAPI disclosing a coupon code after a NoSQL injection attack

Figure 5.8 – crAPI disclosing a coupon code after a NoSQL injection attack

Pick this coupon and add it to the corresponding area of the website. It will be accepted, and your balance will increase, as shown in Figure 5.9. Lucky, lucky!

Figure 5.9 – Valid coupon code added

Figure 5.9 – Valid coupon code added

You can see your balance has increased by $75, as shown in Figure 5.10. Rich!

Figure 5.10 – Balance increase after the coupon code was added

Figure 5.10 – Balance increase after the coupon code was added

Congratulations! You will never have to spend more for a single product on crAPI’s shop. Sorry – just another terrible icebreaker. The list of payloads I used for this attack can be easily found in the references that I put in the Further reading section. Do not forget to check them as there is a vast amount of material that you can use in your pentesting endeavors. Next, we will learn about user input validation and sanitization.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image