List of API Attacks

March 18, 2024
10
min

In today's digital world, APIs play a crucial role, enabling different software systems to communicate and allowing developers to create advanced solutions. Unfortunately, the essential role of APIs is revealing a key concern: API attacks.

Research conducted by Google Cloud among tech leaders from large US companies revealed that over half (53%) have postponed the introduction of new services or applications because of API security worries. This revelation underscores the pressing need for a more comprehensive understanding of API attacks and the corresponding security countermeasures. 

This article delves into the most prominent forms of API attacks, their underlying methodologies, and robust countermeasures to fortify them and make them resilient.

Summary of crucial API attacks

API attack Description
Broken object level authorization (BOLA) The attacker manipulates a reference to an internal implementation of an object to gain unauthorized access to other objects.
Mass assignment The attacker sends unexpected properties in payload requests to gain unauthorized access to object properties.
Brute-force attacks The attacker submits a large volume of inputs to bypass a safety measure.
Denial of service (DOS) attacks Depending on the application context, the attacker floods the server with traffic or requests.
Business logic abuse The attacker manipulates the application to cause it to use resources or perform operations in a way that is detrimental to the business or organization.

In-depth exploration: top attacks that threaten APIs

Broken object-level authorization (BOLA)

Object-level authorization represents a critical access control approach typically implemented in the API’s code. Its primary objective is to ascertain that only users with the appropriate permissions can access requested resources or objects. When this control breaks, APIs open themselves up to the notorious risk highlighted as the most common in the OWASP Top 10 API list of 2023: broken object-level authorization (BOLA), also referred to as insecure direct object references (IDOR).

BOLA occurs when API endpoints fail to verify whether a user possesses the necessary authority to access a particular object. It allows attackers to manipulate the object ID transmitted in a request, leading to unauthorized access to confidential data. Whether about the business or individual users, this data becomes a lucrative target for attackers seeking to capitalize on API security oversights.

In 2022, Coinbase’s Advanced Trading feature exposed a significant BOLA vulnerability that could have had severe ramifications for the platform and its users. The flaw was due to a missing logic validation check within a retail brokerage API endpoint. This lapse permitted users to trade on specific order books while utilizing mismatched source accounts.

To illustrate, while processing a trade, the request used critical parameters such as product_id (defining the product being traded, like ETH to EUR), source_account_id (indicating the account selling the funds), and target_account_id (designating the account to receive the converted currency).

The request to Coinbase’s advanced trading endpoint to sell ETH-EUR

An attacker discovered that after manually modifying the product_id parameter, the Coinbase backend failed to validate the legitimacy of the associated wallets in the transaction.

A valid BTC sale resulting in $1,060.73 after manipulating the request

In practical terms, the tester sold 0.0243 BTC for $1,060.73 without having any BTC, just by changing the product_id in an ETH-EUR order.

The key measure to combat BOLA is integrating access control checks on the object level. This acts as a gatekeeper, ensuring that any user accessing a particular object is first validated for the necessary permissions.

As a supplemental measure, using globally unique identifiers (GUIDs) for record IDs can enhance security. GUIDs are not a standalone security solution, but due to their randomness, they make it more challenging for attackers to guess or manipulate IDs, bolstering data security.

{{banner-small-1="/design-banners"}}

Mass assignment

Mass assignment attacks pose a significant vulnerability to APIs that naively convert client parameters directly into the properties of server-side objects. This seemingly convenient feature becomes a high-risk backdoor for cyber attackers: By slipping unexpected properties into the request payload, attackers can tamper with the values of object properties initially meant to be externally inaccessible. This leads to substantial risks, ranging from privilege escalation and data tampering to bypassing security mechanisms, thus severely compromising the system’s integrity.

Mass assignment receives its name from the attack on the object property level that involves assigning (or overwriting) multiple attributes of an object at once. Attackers can uncover vulnerable properties by guessing object properties, probing other API endpoints, reading API documentation, or simply inserting extra object properties into request payloads. APIs expose underlying application implementations, including properties’ names, which unfortunately makes the exploitation of mass assignment that much easier.

Let’s examine the code snippet below as an example:

@app.route('/api/user/update', methods=['POST'])
def update_user():
    user = User.query.get(request.json['id'])
    user.update(**request.json)
    return jsonify(user.to_dict())

A Flask API endpoint vulnerable to mass assignment

Suppose the code snippet belongs to a banking application with an API endpoint to update the user profile, including attributes like name, email, and password.

The line user.update(**request.json) introduces a vulnerability by blindly updating the user details with data from the request.

We see that the application does not strictly allowlist these attributes. An attacker can exploit a simple update picture request by adding an account_balance attribute in the request payload to modify the account balance.

POST /api/user/update
{
	"name": "Legitimate User",
  "email": "legitimate@user.com",
	"picture": "1337.png",
	"account_balance": "$750,945,742.00"
}

A malicious “update picture” request that updates the attacker’s account_balance.

To thwart mass assignment attacks, it’s vital to carefully control properties that can be updated in the model. Avoid methods that blindly bind client input to code or database entities—opt for precise input binding or the judicious use of ORM functionalities.

Furthermore, validating any incoming properties against a predefined allowlist is also paramount. This ensures that only legitimate properties, specifically approved, are assigned to the model, thereby filtering out potential threats.

Brute-force attacks

Brute-force attacks exploit the risk of broken authentication in APIs. They don’t employ clever tricks or exploit specific vulnerabilities; attackers simply overwhelm the system with many attempts by programmatically submitting many requests to an API endpoint, guessing a value or set of values such as passwords or authorization tokens. When it involves a list of previously leaked usernames and passwords, this is called credential stuffing.

As an example, an attacker might try a brute-force attack against a login API endpoint, trying many username and password combinations in the hope of eventually guessing correctly.

@app.route('/api/login', methods=['POST'])
def login():
    username = request.json['username']
    password = request.json['password']
    user = User.query.filter_by(username=username).first()
    if user and user.check_password(password):
        return jsonify(user.to_dict())
    else:
        return "Invalid username or password"

A login API endpoint, vulnerable to brute-force attacks

In the code above, the login function retrieves a username and password from an incoming request and checks them against a database. The user’s information is returned if a matching username is found and the password checks out; otherwise, an error message is returned.

The main issue here is that there is no mechanism in place to limit repeated login attempts. An attacker can continuously send requests with different password combinations for a given username (or even try various usernames) without repercussions. Over time, this “brute-force” approach might allow the attacker to guess the correct password for an account.

Blocking brute-force attacks requires a nuanced strategy that integrates rate limiting across all API endpoints. Some API security tools provide a configurable rate-limiting feature, effectively capping the number of attempts by a user, thereby decelerating potential attacks.

Supplementing the defense with CAPTCHAs adds a user authenticity test to discern genuine users from bots. Additionally, implementing multi-factor authentication considerably heightens security thresholds by requiring varied identification forms, though it’s essential to also safeguard these authentication methods (like pins, OTPs, or biometric inputs) from brute-force attacks.

{{banner-small-2="/design-banners"}}

Denial of service (DoS) attacks

APIs are often designed without enforcing strict limitations on client interactions or resource consumption, an oversight that can pave the way for DoS attacks. For example, in GraphQL APIs, although objects typically cannot have multiple properties with identical names, aliases offer a workaround. Aliases allow users to intentionally specify a bundle of properties they desire from the API and retrieve numerous instances of the same object type within a single request.

This feature, while beneficial, introduces a potential vulnerability. Most endpoints employ rate limiters to thwart brute-force attacks. However, many limiters only consider the count of HTTP requests and not the actual operations executed. Since aliases enable the bundling of multiple queries within a single HTTP request, crafty attackers can exploit this loophole to bypass rate restrictions, emphasizing the crucial need for robust security mechanisms.

In the example below, an attacker exploits a medical system where doctors generate detailed health reports by simultaneously requesting the generation of a massive number of reports:

POST /report/generate

[

	{"query": "mutation {report1: generateReport(patientId: \"1\") {reportId, details}}"},

  {"query": "mutation {report2: generateReport(patientId: \"2\") {reportId, details}}"},

  ...

  {"query": "mutation {report9999999999: generateReport(patientId: \"9999999999\") {reportId, details}}"},

]

An aliased request for 9999999999 health reports to cause a DoS.

In the highlighted attack, an evil actor exploits a medical system by generating health reports for 9,999,999,999 unique patient IDs. Due to these reports’ intricate and data-heavy nature, this influx can incur enormous cloud-based operational costs when CPU, memory, and storage needs surge. Furthermore, the system risks crashing or drastically slowing down, potentially preventing medical professionals from accessing vital patient data. Such scenarios emphasize the potential dangers of DoS attacks in critical applications, especially those managing sensitive information like medical data.

To prevent DoS attacks, apply rate limiting on all API endpoints, restricting the number of requests a user or IP address can make within a specific timeframe. To use rate limiting, you can set up rules that define how many requests are allowed per user or IP address in a given period, such as a certain number of requests per minute or hour.

Monitoring resource-intensive tasks, like database queries or complex computations, is also crucial to prevent undue strain on the system and maintain user availability.

Also, setting operation limits in GraphQL APIs, such as capping the number of unique fields or aliases the API can handle, is crucial in strengthening protection against threats. By examining the API request structure and limiting query depth, we can also prevent issues from deeply nested queries that might burden server resources.

Business logic abuse

Business logic abuse represents a sophisticated type of cyber-attack where attackers manipulate an application’s functionality to harm the business or organization. This abuse often aligns closely with the OWASP risk concerning unrestricted access to sensitive business flows. These exploits typically necessitate a thorough understanding of the API’s business model. After discerning this, perpetrators identify and target sensitive business flows to inflict damage.

An API endpoint that unveils a sensitive business flow and fails to limit its accessibility is ripe for exploitation. While the consequences of such breaches may not always manifest in explicit technical fallout, they can wreak havoc on a business in many ways.

Let’s consider an ecommerce application that allows users to apply discounts to their orders. Assume the application uses an API endpoint to apply the discounts:

POST /api/discount/apply
{
  "userId": 12345,
  "discountCode": "SUMMER20"
}

A POST request to apply a discount code

@app.route('/api/discount/apply', methods=['POST'])
def apply_discount(request_body):
user_id = request_body["userId"]
    discount_code = request_body["discountCode"]

    # Missing: Authentication check, authorization check, and usage limit check.
    apply_discount_to_user_order(user_id, discount_code)
    return {"message": "Discount applied successfully!"}

A vulnerable apply discount API Endpoint

Due to a lack of proper understanding of the business flow and poor access control, the API endpoint simply applies the discount without validating the userId and the frequency of discountCode usage.

Attackers could exploit this in a few ways:

  1. They could repeatedly use the same discountCode for their orders, getting a discount every time.
  2. They might programmatically try a range of discountCode values to find and use valid codes.
  3. If an attacker knows other users’ IDs (or can guess them), they could also misuse discount codes on behalf of other users, causing potential confusion or financial discrepancies.

A foundational defense against such abuse is server-side validation of all business rules. To enhance this, consider the following measures:

  • Rate limiting: Deters repeated malicious activities
  • Device fingerprinting: Offers meticulous device tracking and identification
  • Systematic analysis via reinforcement learning: Leverages evolving machine learning models to precisely detect anomalies, such as irregular endpoint access bypassing standard flows, enhancing the adaptability of security systems
  • Human detection mechanisms via runtime protection: Provides agile defenses primed to recognize and counter immediate API threats while distinguishing legitimate users from bots

Embedding tools that deploy the advanced strategies above can further elevate protection against business logic abuses, offering comprehensive and state-of-the-art security.

{{banner-large-white="/design-banners"}}

Conclusion

API security has evolved into a critical element in the overall security of today’s intricately connected systems. As the frequency and sophistication of API attacks intensify, there is a heightened need for preemptive security strategies. Utilizing advanced tools streamlines this endeavor and amplifies the protection layers. However, consistent vigilance and staying informed about new threats are essential for professionals in this rapidly changing domain. Businesses must continuously refine and adapt defensive methods to ensure adequate protection against evolving risks.

Contact Impart Security at try.imp.art for more API security tips and best practices and be sure to follow us on LinkedIn for the latest product news and updates.

Like this article?

Subscribe to our LinkedIn Newsletter to receive more educational content

Subscribe Now
Chapter
1

Guide To API Security Best Practices

Learn how to protect customer data and improve security posture with 8 essential API security best practices.

Chapter
2

API Pentesting Methodology

Learn how to scope an API, address the top five attacks, and report and retest vulnerabilities during API penetration testing.

Chapter
3

API Attacks

Learn how API attacks, such as Broken Object Level Authorization, can lead to unauthorized access to confidential data and how to protect against them.

Chapter
4

API Security Monitoring

Understand the best practices for monitoring your API, as well as some key features to look for when evaluating an API monitoring solution.

Chapter
5

API Security Testing

Learn how to evaluate the security of an API and prevent common threats and vulnerabilities with twelve essential API security testing best practices.

Chapter
6

API Security Tools

Learn how to use API security tools for offensive and defensive strategies, such as OWASP ZAP, Burp Suite, ffuf, Kiterunner, Postman, Swagger, and Im

Chapter
7

API Security Solutions

Learn how to select a robust API security solution with features, best practices, and guidelines to ensure secure data exchange.

Chapter
8

Secure API Development

Explore a detailed guide to API development with security at its core, covering the entire SDLC. Gain insights into best practices and practical tips for comprehensive API protection.

Chapter
9

API Gateway Security

Learn how to secure your API gateway with 8 best practices, from authenticating users to rate limiting and hardening your apps.

Chapter
10

OWASP Top 10 API

Learn how to prevent API security breaches with OWASP API Security Top 10 and implementing best practices for attack prevention.

Chapter
11

API Authentication Security Best Practices

Learn how to implement robust API authentication security measures with best practices and example solutions.

Chapter
12

API Discovery

Learn how to discover, document, and manage APIs for organization owners and developers with this article on API discovery best practices.