Optimal Strategies for Enhancing API Security
Consequences – API Leaking Data
What happens when an API's security is weak? Here are a few examples:
- T-Mobile Alerts 2.3 Million Customers of Data Breach Tied to Leaky API
2. Google To Shut Down Google+ As Social Network Bug Exposed Private Data
3. ?
4.
Lets understand the causes of the API breaches
API Security Categorie
Let's take a look at the diagram to understand the key categories for API security
Most Commonly known API Vulnerabilities
DISTRIBUTED DENIAL OF SERVICES
API DDoS attack are executed to overload an API service. Since each hacker sends normal traffic volumes, these attacks are difficult to detect.
SQL INJECTION & DATA ATTACKS
Hackers or insiders with credentials can access systems or data, leading to extraction, deletion, manipulation, injection, or code injection.
MOST EXPLOITED API VULNERABILITIES?
RBAC & ABAC VULNERABILITIES
Granting precise resource access may create numerous RBAC roles or ABAC rules, prone to exploitation if inadequately tested. Detecting privilege escalation (RBAC) and unauthorized resource access (ABAC) is challenging. Such vulnerabilities fuel major API attacks, risking hefty regulatory fines for companies.
BUSINESS LOGIC FLAWS
Coding errors lead to technical vulnerabilities like SQL injections. Conversely, business logic vulnerabilities stem from application functionality mistakes. APIs are prime targets for exploiting these vulnerabilities. Traditional security tools can't detect business logic vulnerabilities.
ROLE BASED ACCESS CONTROL
What is RBAC?
- Permissions are granted to each role based on requirements.
- Users can be assigned to multiple roles.
- As a best practice, roles should NOT have overlapping permissions.
Limitations of RBAC
- Regressions in the permissions granted to each role often introduced as a result of new features or application updates.
- Users can often accumulate unnecessary roles leading to excess permissions.
- RBAC vulnerabilities have contributed to the most prominent API attacks and could cost companies extremely high fines for breaching regulatory guidelines like GDPR.
Here is an example of breach RBAC from Google+
GOOGLE+ PRIVILEGE ESCALATION VULNERABILITY USER DATA FROM 52.5 MILLION ACCOUNTS EXPOSED
How was this hack perpetrated?
- "People: get" API endpoint was designed to let developers request basic information associated with a user profile.
- A software update in November 2018 introduced a privilege escalation (RBAC) vulnerability in the Google+ People API that allowed third-party app developers to view users' information even if a user profile was set to not-public.
What won't work in stopping these kinds of attacks
- SAST & DAST scanning solutions will not help detect these exploits as they focus on injection and fuzzing attacks rather than privilege escalation vulnerabilities.?
Static application security testing (SAST) and dynamic application security testing (DAST) are two ways to find security problems in apps. SAST checks the app's inner workings and code to spot issues, like a detective inspecting a crime scene. Meanwhile, DAST tests the app from the outside, like a guard patrolling the perimeter, searching for weaknesses that could be exploited by intruders. SAST pores over the source code, while DAST scans the running app as it operates.
ATTRIBUTE BASED ACCESS CONTROL
What is ABAC?
- ABAC stands for Attribute Based Access Control. Unlike RBAC (Role Based Access Control), ABAC employs policies that articulate a complex Boolean rule set capable of evaluating various attributes.
- Object attributes define the object or API resource being accessed, while action attributes specify the attempted action, such as read, delete, or view.
Limitation of ABAC
- Granting fine-grained access to API resources often results in a proliferation of ABAC rules, which can be exploited if not thoroughly tested.
- ABAC rule regressions frequently occur due to the introduction of new features or updates to applications.
- ABAC vulnerabilities have contributed to significant API attacks, potentially resulting in substantial fines for companies that violate regulatory standards like GDPR.?
Here is an example of breach ABAC from CITI
CITI ABAC Vulnerability - Exposing Financial Data of 360,000 Customers
How was this breach executed?
- The breach exploited parameter tampering within the APIs.
- A lack of ABAC validation or role assignment enabled any authenticated user within the application to request API resources belonging to any other user/customer simply by knowing their account number.
- The use of predictable account numbers (e.g., incremental numbers such as 100034567, 100034568, etc.) allowed attackers to input repeated account numbers tens of thousands of times, granting access to account data.
What measures won't be effective in preventing such attacks?
SAST & DAST scanning solutions are ineffective in detecting these exploits as they primarily target injection and fuzzing attacks, rather than unauthorized access to API resources.?
Things to keep in Mind
- Only expose the interface we needed.
- Only collect and share the data we need.
- Only grant access to the people and system we need.
- Think like a bad guy.
Be Smarter about Data
- Don’t collect it if you don’t have to
- Secure it in flight (SSL/TLS)
- Encrypt in at rest.?
API Security Pitfalls
Allowing access to your API over HTTP
APIs are accessed from code, so there is no need to support a redirect from HTTP to HTTPS. Lock your API further down by enabling HSTS.
Use HTTPS, otherwise no use of any other mechanism
§? There is no valid excuse to not use HTTPS anymore
- Let's Encrypt offers free certificates for all
- Performance is no longer an issue
§? APIs are accessed directly from within an application
- Makes setting up HTTPS easier, as you do not need to support a redirect from HTTP.
- Simply disable HTTP for your API endpoints altogether
§? Network-based attacks can still attempt a fallback to HTTP
- Configure HTTP Strict Transport Security (HSTS) to prevent this from happening
- HSTS will tell the browser to use HTTPS for every request, regardless of the scheme
Strict-Transport-Security: max-age=31536000
"The max-age attribute in the HTTP Strict Transport Security (HSTS) policy should be set to 31536000 seconds, or one year. This attribute tells user agents that a host is a known HSTS host for one year after receiving the Strict-Transport-Security header field"
Unlimited access to an API is a bad idea
§? Unlimited access to an API can have dangerous consequences
- Denial of service is possibly the best case scenario
- Extracting information or brute forcing access codes are a lot worse
§? Many rate-limiting strategies can be used
- Limiting the data per connection property (IP address)
- Limiting the data per user (account/ access token / API key)
- Limiting the data per application property (user account / resource type)
- Limiting the data based on context (region / type of app)
PAGINATION LIMITS TO PREVENT DDOS ATTACKS
Implementing pagination limits is essential for preventing DDoS attacks. When endpoints return lists of entities, pagination helps manage traffic effectively by limiting the number of search results displayed at once. This strategy helps prevent overwhelming network loads caused by excessive search queries.
Offset Pagination:
Offset pagination is one of the most straightforward paging methods. It gained popularity particularly among applications utilizing SQL databases, as LIMIT and OFFSET are already integrated into the SQL SELECT Syntax. Implementing limit/offset paging requires minimal business logic.
Here's how it works:
1.????? The client initiates a request for the most recent items: GET /items?limit=20
2.????? Upon scrolling or navigating to the next page, the client sends a second request: GET /items?limit=20&offset=20
领英推è
Insecure direct object references
Always set a basic authentication check with applicable authorization checks (e.g. ownership of a resource)
§? Predictable identifiers enable the enumeration of resources.
- Unsafe if resources are not shielded by strict authorization checks.
- Many APIs only check authentication status, but not which user is authenticated.
§? The only correct mitigation is implementing accurate authorization checks
- E.g. checking if the current user is the owner of the resource
§? The use of non-predictable identifiers is a complementary approach.
- UUIDS are a good example of such an identifier.
- Just be careful about using them as primary keys in the database
The Properties of cookies
§? Cookies are a mess, but they are compatible with the web
- Browsers store and send cookies by design.
- Cookies are present on all requests, including those coming from DOM elements
- Cookies are compatible with web mechanisms such as CORS, SSE, WebSockets, ...
§? Securing cookie-based mechanisms requires a lot of effort
- Cookie security flags need to be configured correctly
- Cookie prefixes offer additional security, but require modifying the name
- Cookies enable a nasty attack called Cross-Site Request Forgery (CSRF)
§? Cookies are a nightmare to support in non-web applications
The properties of custom headers
Cookies are often frowned upon in an API world, and custom headers are preferred. Both have vastly different security properties, so make sure you understand them fully.
§? Custom headers are straightforward, but can be hard to use
- Not handled automatically, so the application needs to store and send the value
- The browser will not attach it to requests coming from DOM elements
- The use of mechanisms such as CORS, SSE, WebSockets, ... becomes more difficult
§? Securing header-based mechanisms is also surprisingly difficult
- You have to decide where to store the data in the client application
- You're likely to mess up attaching the header to outgoing requests
- But the good news is that custom headers do not suffer from CSRF
§? Custom headers are a breeze to use in non-web applications.
?
Cross-Site request forgery
"Cross-site request forgery (CSRF), also known as one-click attack or session riding, is a type of cyber attack that tricks a user into performing actions on a web application that they are authenticated to. CSRF attacks exploit the trust a web application has in an authenticated user. For example, a CSRF attack can trick a user into transferring funds, changing their email address, or making a purchase. A successful attack against an administrative account can compromise an entire server, potentially resulting in complete takeover of a web application."
Here is a exacmple to explain Cross-site request forgery (CSRF)
CROSS-SITE REQUEST FORGERY
§? CSRF exists because the browser handles cookies very liberally.
- They are automatically attached to any outgoing request.
- By default, there's no mechanism to indicate the source or intent of a request
§? Many APIs are unaware that any context can send requests
- GET and POST requests are easy to trigger using DOM elements or XHR
- PUT and DELETE requests are a different story
- Defending against CSRF requires explicit action by the developer
§? A traditional CSRF defense is using hidden form tokens
?
Underestimating the importance of CSRF
CSRF attacks exist when cookies are used for keeping session state. Verify if you're vulnerable and implement appropriate defences.
If you do not use cookies, you do not need to worry about CSRF
?
THE RELATION BETWEEN CSRF AND CORS
§? Cross-origin HTTP requests have always existed in the web
- Examples are loading images from other origins, or submitting forms across origins
§? CSRF matters in an API supporting “traditional" HTTP requests
- GET/POST requests with traditional content types and no custom headers
- These requests can easily be forged using traditional HTML elements
§? APIs using "non-traditional" HTTP requests fall under the protection of CORS
- Such a request can only be sent from JavaScript using XMLHttpRequest
- Such a request triggers the Cross-Origin Resource Sharing (CORS) security policy
- Such a request will only be allowed if the server explicitly approves it
?
COMMON CORS MISCONFIGURATIONS
Origin: https://www.example.com
§? Allowing partial matching against the Origin header
- Comparing using startsWith() or endsWith() methods
§? Allowing the null origin
- The null origin is used by contexts that should be isolated by default (e.g. sandbox)
§? Only checking the domain, and not the entire origin
- HTTP pages cannot be trusted, even if they seem to be served by your own domain
§? Reflecting back the value from the Origin header
- This allows every page to access your API, without any restrictions
?
Insecure CORS configuration / implementation
CORS policies are crucial to prevent a malicious site from accessing your API in a legitimate user's name. Do not allow more access than necessary, and verify your implementation.
?
UNDERESTIMATING THE IMPACT OF XSS
"Cross-site scripting (XSS) is a security vulnerability that allows attackers to inject malicious code into web pages. This code is executed by the victim, allowing the attacker to bypass access controls and impersonate users. Attackers often use XSS by sending a malicious link to a user and tricking them into clicking it. If the app or website doesn't have proper data sanitization, the malicious link will execute the attacker's code on the user's system. As a result, the attacker can steal the user's active session cookie."
Stealing data from localStorage is only a single consequence of XSS.
XSS means game over. You lost.
INPUT VALIDATION IS AN IMPORTANT FIRST LINE OF DEFENSE
§? Limiting the number of valid inputs reduces the attack surface
- Untrusted data should be validated before using it
- The restrictions that can be imposed depend on the type of content
§? Best practices for input validation
- Only accept content types that you expect, and reject everything else
- Validate every input against its expected data type
- Impose sensible length restrictions, and always set a strict upper bound
- Always use a secure parser to process input
?
Lack of input validation
A lack of input validation is the enabler for various other attacks. Ensure that input validation is as strict as possible without triggering false positives
?
However, checking the input can only take you part of the way
§? Input validation targets symptoms, not the root cause of the issue
- Injection needs to be addressed in the code, not at the input level
§? Once the data is complex enough, validation bypasses will exist
- Validation or sanitization is hard to get right, so do not solely rely on them
- A good example are the huge XSS filter evasion cheat sheets
§? And sometimes, it's just not the API's responsibility
- Cross-site scripting in web applications is the perfect example
- The API has no idea where the data will be used, so it cannot render it safe
- The client-side application needs to handle this, as e.g. Angular does out of the box
?
Relying on input validation
Even though input validation is a good first line of defence, it will fail as the only defence. Do not rely on input validation alone.
Summary
In conclusion, the consequences of weak API security can be severe. Understanding the causes of these breaches, such as vulnerabilities in Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC), is crucial. While measures like input validation are important, they only address part of the issue. Proper security measures, including HTTPS implementation, rate limiting, and effective CORS policies, are essential to mitigate risks. Ultimately, a multi-layered approach is necessary to safeguard against API vulnerabilities effectively.
Fullstack Senior Developer to Build Scalable and Secure Web Experiences | Solution Architect | Angular | Typescript | React | NestJS | Code Review Expert | Clean Code Expert
11 个月Very well explained.
Software Engineer 2 at Microsoft
11 个月Very useful...
Gen AI engineer and leader | LLM | RAG | NLP
11 个月This is a good article on the importance of API security!
Full Stack Developer, Ninja in .NET, Angular, Node.js, SQL
11 个月Nice read, good to see mentioning of impact when having leaky APIs ??
Sr. Project/Program Manager at Nagarro
11 个月With increased usage of APIs widely across industry, everyone must adhere to the best security standards