According to a recent report from Imperva (a Thales company), organizations lose $94- $186 billion every year to vulnerable or insecure APIs abused by bots. The report highlights that this security threat accounts for up to 11.8% of global cybersecurity events and losses, highlighting a new trend in cyberattacks.
In this article, we want to provide an overview of these attacks and how to prevent them by implementing best practices for API protection.
What are API's?
APIs (Application Programming Interfaces) enable software systems to communicate and share data, particularly in web applications and cloud services. Their versatility and usability have made them a prominent feature in modern app development, especially for web and mobile applications, making them a prime target for attackers.
Common API vulnerabilities
Hackers can abuse APIs in various ways without any particular tool. With a simple browser, they can carry out the following common types of attacks:
BROKEN OBJECT-LEVEL AUTHORIZATION (BOLA)
In BOLA attacks, users can manipulate API endpoints to access data they should not have access to. This occurs when API requests don’t properly check whether the user is authorized to access a specific object (e.g., retrieving another user’s data by guessing object IDs).
Example:
GET /api/user/1234
If the API doesn’t verify the user’s object ownership (e.g., user ID 1234
), attackers can change the ID to access other users’ data.
BROKEN USER AUTHENTICATION
Weak or improperly implemented authentication allows attackers to compromise user identities. This can happen through poorly stored credentials, weak password requirements, or lack of multi-factor authentication (MFA).
Best practices
To prevent and remediate BOLA and broken user authentication, implement strong authentication and authorization techniques:
- OAuth 2.0 / OpenID Connect: Use industry-standard protocols for secure authorization.
- JWT (JSON Web Tokens): Use signed tokens to authenticate users and ensure that tokens are securely stored (e.g., in HTTP-only cookies to prevent XSS).
- MFA (Multi-Factor Authentication): Strengthen user authentication with a second factor (e.g., SMS codes, authenticator apps).
EXCESSIVE DATA EXPOSURE
APIs sometimes return more data than necessary, relying on the client to filter it. Attackers can exploit this and access sensitive information in responses. For example, an API might return a user’s full profile, including sensitive information, when only the username is needed.
MASS ASSIGNMENT
Mass assignment occurs when APIs automatically bind user input to internal objects, allowing attackers to modify sensitive fields that developers never intended to expose.
Example: A signup API may inadvertently allow users to assign themselves administrative privileges by submitting extra fields in a POST request.
{
"username": "user1",
"password": "password123",
"isAdmin": true
}
Best practices
Implement data filtering and output validation techniques to prevent excessive data exposure and mass assignment. This means only exposing the necessary data in API responses by restructuring sensitive fields and eliminating what’s not needed. Implement strict filtering and validation on both the client and server sides.
LACK OF RATE LIMITING
APIs without rate limiting allow attackers to send unlimited requests, enabling brute-force attacks, Denial of Service (DoS) attacks, or account enumeration attempts.
Best practices
Limit the number of API calls an IP or user can make within a time window to mitigate DoS attacks and brute force attempts.
For example, in nginx:
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/m;
server {
location /api/ {
limit_req zone=api_limit burst=10 nodelay;
}
}
}
SQL INJECTION AND NoSQL INJECTION
Insecure user input handling allows attackers to inject malicious SQL/NoSQL queries through API endpoints.
Example of an SQL Injection:
GET /api/users?username=admin' OR 1=1 --
The query retrieves all users because 1=1
always evaluates to true.
Best practices
Sanitize all inputs and enforce strict validation for both client-side and server-side requests. Always use parameterized queries or ORM frameworks to prevent SQL and NoSQL injection.
Example (SQL Prepared Statement in Python):
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
How to prevent common API vulnerabilities
Besides attack-specific best practices, we strongly recommend to implement the following best practices to harden the working environment of your APIs:
Best practices
- Use HTTPS for all traffic: Ensure all API communications are encrypted using TLS (HTTPS) to protect against man-in-the-middle (MITM) attacks. Avoid HTTP and ensure that sensitive data (e.g., access tokens) is not transmitted over insecure channels.
- Use API gateways and security tools: API gateways can help by offering built-in security features such as authentication enforcement, rate limiting, logging and monitoring, and input validation. For example, AWS API Gateway integrates with AWS Lambda and offers API security features like throttling and logging.
- Use secure API keys and access tokens: Never expose API keys or tokens in client-side code (e.g., Javascript running in the browser). Rotate keys regularly and use short-lived access tokens with limited scopes.
- Audit and log API requests: Maintain detailed logs of API requests to detect suspicious activity. This will help identify potential security incidents and conduct post-incident forensics.
- Implement content security policies (CSP): A well-defined Content Security Policy (CSP) can reduce risks from XSS attacks by controlling which resources (scripts, styles, etc.) can be executed on a page.
Example of a CSP Header:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-scripts.com
In addition to these basic practices, we also suggest some advanced security practices that will go a long way in strengthening your app security and users’ data:
Advanced security practices
- API Security testing:
- Dynamic Analysis (DAST): Simulate attacks on the API to identify vulnerabilities during runtime.
- Static Analysis (SAST): Analyze API code for security flaws, especially for sensitive logic.
- Penetration Testing: Regularly test APIs through manual or automated pen-testing methods to uncover potential weaknesses.
- Use Web Application Firewalls (WAFs): WAFs monitor and filter HTTP requests and help protect APIs against attacks like XSS, SQL injection, and DoS.
- Continuous security monitoring: Use automated tools to monitor APIs for security threats in real-time. Solutions like AWS CloudWatch, Datadog, or SIEM tools can help identify anomalies in API usage.
Bot exploitation of APIs
Hackers can find exploiting APIs tedious because it’s a trial-and-error process. However, using bots makes this process much faster and more effective. This new trend primarily targets large organizations and can exploit APIs with the following techniques:
CREDENTIAL STUFFING
Operating at a massive scale, bots utilize stolen or leaked credentials to attempt authentication into APIs. This high-volume tactic preys on users who practice password reuse across multiple platforms.
How It Works: Attackers use automated bots to try combinations of username/email and password against login APIs to find valid credentials. Once they are successful, they can take over accounts, steal data, or commit fraud.
Impact:
- Account takeover (ATO)
- Fraudulent transactions
- Data theft
Best practices
CAPTCHAs (Completely Automated Public Turing Tests to Tell Computers and Humans Apart) play a crucial role in the fight against bot abuse. They achieve this by presenting a challenging task that only humans can solve, effectively distinguishing legitimate users from automated bots.
Examples are Google reCAPTCHA and hCaptcha.
Limitations: While practical for preventing bots, CAPTCHAs can also create friction for legitimate users and degrade the user experience.
SCRAPING AND DATA HARVESTING
Malicious bots target APIs to extract large amounts of publicly or privately accessible data. This includes scraping for product prices, personal user information, intellectual property, or any valuable data.
How It Works: Bots make numerous API requests, usually at a fast rate, to systematically extract data from a platform. These bots often disguise themselves as legitimate users to avoid detection.
Impact:
- Intellectual property theft
- Loss of competitive edge
- Violation of privacy regulations (e.g., GDPR)
Best practices
- Implement rate limiting and throttling with IP and user-specific rate limiting.
- Implement bot management tools and machine learning-based systems that identify abnormal behaviour and block or challenge suspicious traffic.
- Deploy bot detection mechanisms that analyze the behaviour of API requests to distinguish between legitimate users and bots. These tools monitor factors such as:
- The speed and volume of API requests
- Request patterns (e.g., headless browsers)
- User-agent headers
DENIAL OF SERVICE (DOS) AND DISTRIBUTED DENIAL OF SERVICE (DDOS)
Botnets can flood APIs with large requests, overwhelming servers and making them unavailable to legitimate users. In a DDoS attack, a distributed network of compromised machines (botnets) floods the API with traffic from many sources simultaneously.
How It Works: Attackers use networks of bots (botnets) to generate huge volumes of API requests, exhausting server resources like CPU, memory, or bandwidth and causing service outages.
Impact:
- Service disruptions
- Financial losses
- Reputational damage
Best practices
Implement IP Blocking and geo-fencing: block or throttle requests from IP addresses associated with malicious activity. Similarly, geo-fencing allows you to limit access to APIs from specific countries or regions where your service is unavailable.
Considerations: Attackers can bypass IP blocking using proxy networks and VPNs. Therefore, this should be part of a broader strategy.
Example of geo-blocking with nginx:
geo $remote_addr $allowed_country {
default no;
123.456.789.000 yes; # Whitelist IP ranges
}
server {
if ($allowed_country = no) {
return 403;
}
}
INVENTORY HOARDING AND CARDING ATTACKS
Some bots are programmed to abuse eCommerce APIs by hoarding items in carts to create artificial scarcity or complete fraudulent purchases using stolen credit card information. These “inventory hoarding” bots reserve items without completing purchases, while “carding” bots test stolen credit cards by making small transactions through the API.
Impact:
- Reduced availability of products for legitimate users
- Fraudulent transactions
- Increased operational costs due to inventory mismanagement
Best practices
Use OAuth 2.0 for secure access to APIs, and issue short-lived API tokens that require user authentication. Limit the scope and access privileges of these tokens to mitigate the impact of stolen tokens.
- Enforce strict token expiration and refresh mechanisms.
- Use API keys or access tokens with granular scopes to limit what bots can access.
ABUSING RATE LIMITS
Malicious actors may intentionally exploit misconfigured or absent rate limits to send an excessive number of requests, overwhelming the API backend and degrading other users’ performance.
Impact:
- Resource exhaustion (memory, CPU, bandwidth)
- Degraded API performance
Best practices
Leverage User Behavior Analytics (UBA) to monitor standard behaviour patterns and flag suspicious activity. For example, a legitimate user may attempt one login, while a bot may quickly attempt multiple logins across different accounts.
Techniques:
- Monitor metrics like login frequency, the number of failed login attempts, and resource consumption patterns.
- Integrate UBA into your API security layer to detect and block unusual activity.
FAKE ACCOUNT CREATION OR ACCOUNT ABUSE
Bots are often used to create fake accounts at scale, which are later used for spamming, phishing, or other malicious activities. This can also involve abusing the sign-up API by creating thousands of accounts in a short period of time.
Impact:
- Flooding systems with fake accounts
- Spam and malicious activities
- Skewing metrics and analytics
Best practices
Use device fingerprinting to identify devices making API requests uniquely. This helps differentiate genuine users and malicious bots, even if they use different IPs or browser headers.
How It Works: Fingerprinting involves collecting data points like user-agent strings, screen resolution, installed fonts, and other characteristics difficult for bots to mimic.
Deploy fake API endpoints, also known as honeytokens, that legitimate users would never access. Bots that interact with these endpoints can be easily identified and blocked, enhancing the security of your API.
Example: Create a decoy API endpoint (/api/adminpanel
) that is invisible to legitimate users but would attract bots attempting to find admin functionalities. Any requests to this endpoint are a signal of malicious activity.
Advanced security practices
- AI-based bot detection: Machine learning and AI-based bot detection solutions offer more sophisticated defences. These systems learn from standard API usage patterns and adapt to detect evolving bot behaviours.
Benefits:
- Reduced false positives by understanding legitimate behaviour.
- Automated detection and response in real-time.
Examples:
- Distil Networks (now part of Imperva) offers machine learning-based bot mitigation.
- PerimeterX provides behaviour-based bot detection using AI.
- Token binding: Use token binding to ensure that API tokens can only be used with the specific client device that originally requested them. This technique prevents bots from stealing and reusing tokens on different devices or networks.
- Client Certificates and mutual TLS (mTLS): Use Mutual TLS (mTLS) to authenticate both the API server and the client making the request. This can ensure that only authorized clients can interact with the API, blocking bots that lack valid client certificates.
Example: Set up mTLS in your API gateway (e.g., AWS API Gateway, NGINX) to enforce certificate-based authentication.
Costs vs benefits: the ROI of implementing API security best practices
Implementing best practices for APIs in the development phase can be costly and skew your budget or customer quote. So, is it all worth it?
Yes, it is. The benefits of implementing API security best practices, including defences against bot abuse, far outweigh the costs. These practices protect against immediate threats and enhance long-term operational efficiency, reduce financial risks, and improve customer trust.
Just consider that the average cost of a data breach for large corporations has reached an all-time high of $4.45 million globally, according to IBM’s 2023 Cost of a Data Breach report.
For SMBs, the average data breach cost is significantly higher when factoring in indirect costs such as customer turnover and reputation damage. A good planning number for a medium-sized business facing a modest breach of under 250,000 records is $8 million to $10 million, with about one-third of this cost attributed to lost business due to a damaged reputation.