BLOG Hacking APIs (2) - Broken Authentication
David Schmid

Following our blog post series about the OWASP top ten security vulnerabilities in API security, this post focuses on "Broken Authentication."

In my last post we explored another top API security vulnerability, the so-called "Broken Object-Level Authorization" (BOLA), which focuses on authorization-level vulnerabilities. This time, we shift our focus to the authentication level.

Continuing from the last post, where I introduced an engaging festival analogy to explain BOLA, we now follow up with an even bigger festival. This time, we examine how groupies attempt to exploit broken authentication flaws in festival security to gain unauthorized access to the backstage area.

Further, we will explore how these vulnerabilities can arise in the context of API security, providing typical examples like OAuth Vulnerabilities, JWT Vulnerabilities, API Key Issues and Password Reset Functionality Vulnerabilities.

Join the tech and uncover critical vulnerabilities in APIs and beyond and how to safeguard against them...

Main Image Hacking APIs (2) - Broken Authentication

Table of Contents

A Festival with Broken Authentication

In my last blog post, we imagined a vibrant music festival to illustrate Broken Object Level Authorization (BOLA) in API security. We visualized a scene where attendees received color-coded wristbands corresponding to their ticket tiers, intended to restrict access to various zones - much like how APIs are supposed to restrict user actions based on their authorization levels. Unfortunately, due to some glaring authorization issues, a few crafty groupies managed to sneak into the backstage area, leading to rather critical situations.

In this post we will discuss Broken Authentication, the number two in the OWASP Top 10 API Security Risks - 2023 list of API vulnerabilities. Continuing our festival security saga, we now face a new, bigger, and greater festival where we take security more seriously than ever.

Imagine this: As a lesson learned from the last event, we are even double-checking wristbands at the gates to different zones and ensuring each backdoor accessing the backstage is supervised.

However, with a "nothing can go wrong anymore" attitude still in the air, we encounter a new issue...

This time, the oversight isn't in authorization but in something even more fundamental: Authentication.

Our festival's entry protocol involves a database where a cashier checks each attendee's first name and last name against the identity shown. The intention is solid: to ensure everyone entering has a valid ticket purchased under their name. To accommodate students, student IDs are also accepted as legitimate proof.

However, some attendees present fake student IDs that are sophisticated enough to pass a cursory glance, allowing individuals to claim tickets under different names registered in the database.

In hastily called task force meetings, we implement stricter ID controls and we updated the database calls to provide more information about the attendee such as birth date to further improve the checks.

Image Wristbands at a Festival

But just as we think we've addressed the issue, an even more critical failure occurs due to the rapidely implemented changes: a database crash. With no way to verify identities against ticket purchases, cashiers are forced to take attendees at their word. Suddenly, anyone claiming a ticket, even for high-tier backstage access, must be believed without any means to verify their claim.

A few observant groupies notice this lapse and word spreads quickly.

The flawed verification process in the authentication is exploited, leading to unauthorized individuals flaunting special backstage wristbands.

These wristbands, meant to be tightly controlled, become mere tokens as groupies present them as valid access passes. Despite growing suspicions, backstage security finds it impossible not to let them through.

Just like that, the backstage is overrun with unauthorized groupies, raising the glaring question:

How did this happen?

☕ Let's Have a Coffee Break

After this festival security saga, it’s time for a coffee break. Before we dive deeper into API security, let’s gather some sips, take a deep breath, and relax for a moment.

If the content within these pages enriches your journey, particularly our dive into API security topics, consider showing your support by buying me this coffee.

☕ Buy Me a Coffee

Let me insure that my posts are based on my personal opinions and experiences, shared openly and honestly. Your support not only helps with my caffeine needs but also enables me to continue exploring and sharing more about the fascinating world of APIs and technology. As a father of two, coffee is indeed the elixir that fuels my vigilance and creativity.

In addition to sharing my journey and insights, I specialize in crafting and engineering software solutions that empower and enhance your tech projects. Discover how I can help innovate and secure your applications and services.

🔍 Discover My Services

But now, let's go back to the topic...

Broken Authentication

Authentication is the process of verifying the identity of a user or system, ensuring that they are who they claim to be. It is distinct from authorization, which determines what they are allowed to do once inside the system (see "Authentication vs. Authorization" in the last post).

In our security festival saga, the entry protocol involved checking IDs against a database to verify ticket purchases and issuing wristbands as access tokens to the festival. However, a database crash forced cashiers to rely on trust without verification, exposing our festival system to unauthorized access.

Similarly, in the world of API security, broken authentication occurs when flaws in the authentication process allow attackers to assume the identities of other users. This is a critical security layer, because, without it, unauthorized users can gain access to sensitive data and functionalities, potentially leading to severe security breaches.

Just like checking IDs at the festival, API security often involves validating a user's credentials against a database. If fake identities or weak passwords can easily pass through, the system is compromised. Further, if an API continues to grant access despite failing to verify identities (like during a database crash), it can lead to session hijacking, where attackers use stolen authentication tokens to access restricted areas.

Authentication typically involves verifying credentials such as usernames and passwords, but it can also include more sophisticated methods like multi-factor authentication (MFA), biometric verification, or the use of tokens. When these methods are not implemented correctly or are compromised, attackers can exploit these weaknesses to gain unauthorized access.

Exploring Authentication Vulnerabilities

As we've seen, authentication is crucial for ensuring that only legitimate users gain access to sensitive data and functionalities. However, various vulnerabilities can undermine even the best-intended authentication systems.

The vulnerabilities listed below are based on my experiences as a security engineer and bug bounty hunter, as well as public research, primarily from the OWASP website. Some of these vulnerabilities are practical, while others are more theoretical. Additionally, some vulnerabilities are combinations of broken authentication and other issues, such as XSS.

Security should always be regarded as layered, and broken authentication is just one layer in a chain of possible vulnerabilities and attack vectors.

While this list is comprehensive, it is not exhaustive. I encourage readers to share their thoughts and insights in the comments if they feel something important is missing.

Disclaimer: The aim of the listings below is to improve security in services by understanding potential attack vectors and protecting against them. The intention is to improve security, not to exploit vulnerabilities, and to make the web a safer place for users. Some of the techniques discussed can be used for bug bounty hunting, which is a legitimate way to find and report vulnerabilities.

The further subsections require some knowledge of API design. If you are unfamiliar with the concept of APIs, I recommend my blog post about exposing APIs from a business perspective including some more research provided by the links.

Without further ado, let's explore some common authentication vulnerabilities in API security and how they can be exploited...

(1) OAuth Issues

OAuth is a powerful protocol that simplifies authentication across multiple platforms, allowing users to log in using credentials from a trusted provider like Google, Facebook, or GitHub. While this streamlines the user experience and reduces the need for multiple passwords, it also introduces unique challenges that, if not addressed, can lead to significant security vulnerabilities

(1-1) Improper Validation of Redirect URIs

One of the most common and dangerous vulnerabilities in OAuth implementations is the improper validation of redirect URIs. The redirect URI is the endpoint to which the OAuth provider sends the authorization code or token after the user grants permission. If an attacker can manipulate this URI, they can intercept the token and gain unauthorized access.

For example, an attacker creates a malicious site that mimics the legitimate application and tricks the user into authenticating. They manipulate the redirect URI to point to their malicious site:


https://legit-app.com/oauth/callback?redirect_uri=https://attacker-site.com/callback

Once the user authenticates, the OAuth provider sends the token to the attacker’s site, allowing the attacker to hijack the session.

(1-2) Insecure Storage of OAuth Tokens

OAuth tokens must be stored securely to prevent unauthorized access. If tokens are stored in insecure locations, such as local storage in a browser or in plaintext in a mobile app, attackers can easily steal them.

An attacker that gains access to a user's device and retrieves stored tokens from local storage or a poorly secured app can impersonate the user on the respective service and access sensitive information or perform actions on his behalf.

(1-3) Lack of Token Revocation

OAuth tokens should be revocable so that users or administrators can invalidate them if a compromise is suspected. Failure to implement proper token revocation mechanisms can allow attackers to use stolen tokens indefinitely.

Even if a user realizes their token has been stolen, without token revocation, the attacker can continue to use the token indefinitely, maintaining unauthorized access.

(2) Password Reset Functionality

Password reset functionality is a critical feature for user convenience, allowing them to regain access to their accounts if they forget their passwords. However, if not implemented securely, it can become a significant vulnerability. Attackers may exploit weaknesses in the password reset workflow to gain unauthorized access to user accounts.

Common vulnerabilities in Password Reset Functionality include:

(2-1) Weak Verification Steps

An attacker might leverage publicly available information or easily guessable details to pass verification steps. For instance, if the reset process only asks for the user’s email address or date of birth, which are often easy to obtain, the attacker can trigger a password reset. To mitigate this, it is essential to implement multi-factor authentication (MFA) during the password reset process, requiring additional verification steps such as a code sent to the user’s registered phone number or answers to security questions.

(2-2) Insecure Password Reset Links

Password reset links sent via email are often the first step in the reset process. If these links are predictable or not properly protected, attackers can forge or intercept them. For instance, a reset link like


https://example.com/reset?token=12345

is vulnerable if the token is predictable.

To secure password reset links, ensure that tokens are cryptographically secure and expire after a short period. Always use HTTPS to encrypt communication channels and protect the integrity of reset links.

(2-3) No Notification of Reset Attempts

If a user is unaware that a password reset attempt has been made on their account, they cannot take preventive action. An attacker could potentially reset the password and lock the legitimate user out without their knowledge. To prevent this, send an email notification to the user when a password reset is requested and again when the password is successfully reset. This alerts the user to any unauthorized attempts to access their account.

(2-4) Vulnerability in Update Procedures

When updating user account information, such as an email address, security measures must be stringent, especially when used for account recovery. Consider this API request used to update an email address (as provided by OWASP):


PUT /account
Authorization: Bearer {token}

{ "email": "{new_email_address}" }

In this process, the API authenticates the request using a bearer token but crucially does not verify whether the person making the request is indeed the rightful account holder because it does not require the current password at the time of the email change.

This oversight creates a significant security loophole. Bad actors who obtain the authorization token, perhaps through phishing, malware, or using an unsecured network, can change the email address associated with the user account without further verification. After updating the email to one they control, the attacker can initiate a password reset workflow.

(3) JWT Vulnerabilities

JSON Web Tokens (JWTs) are widely used for stateless authentication in modern web applications. They offer a URL-safe way to transmit claims between parties and are favored for their stateless nature, which simplifies server-side management.

JWTs are compact, URL-safe tokens typically composed of three parts:

  • Header: Specifies the type of the token and the algorithm used for the signature.

  • Payload: Contains the claims or the actual data the token is meant to carry. This includes predefined claims (registered claims), public claims, and private claims.

  • Signature: Secures the token against tampering and verifies that the sender of the JWT is who it says it is.

Here is an example of a decoded JWT:


Header:
{ "alg": "HS256", 
  "typ": "JWT" 
}

Payload:
{ "sub": "1234567890", 
  "name": "John Doe", 
  "admin": true, 
  "iat": 1516239022 
}

Signature:
  HMACSHA256( base64UrlEncode(header) + "." +
  base64UrlEncode(payload), secret)

    

In this example, the JWT uses HS256 (HMAC with SHA-256) as the signing algorithm. The payload indicates that the token belongs to an administrative user named John Doe. The signature is calculated by hashing the encoded header and payload with the secret key.

However, JWTs are susceptible to critical vulnerabilities if not properly handled. Understanding these vulnerabilities is crucial for maintaining robust security in your applications:

(3-1) Exposure of JWT Secrets

If the secret key used to sign JWTs is exposed in the source code or environment variables accessible to unauthorized users, attackers can forge valid tokens. This can lead to unauthorized access and manipulation of data. For example, if an attacker gains access to a repository containing the secret key, they can create their own tokens with arbitrary claims and gain access to protected resources.

Imagine that the secret key mySuperSecretKey used to sign JWTs is accidentally committed to a public GitHub repository. An attacker browsing through GitHub finds this key. With this secret key, the attacker can now create a forged token that grants administrative access.

The attacker could sign a payload similar to the following with the exposed secret key mySuperSecretKey:


{ "alg": "HS256", 
  "typ": "JWT" 
} 
{ "sub": "9876543210",
  "name": "Attacker", 
  "admin": true, 
  "iat": 1625252929 
}

    

A resulting JWT might look as follows:


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5ODc2NTQzMjEwIiwibmFtZSI6IkF0dGFja2VyIiwiYWRtaW4iOnRydWUsImlhdCI6MTYyNTI1MjkyOX0.mI6-JK0sbj-KgGbH64n2U1r1F0ZqZvLCkYIHDqIF2hY

    

When this JWT is used, the application verifies the signature using the secret key and, because the key matches, grants the attacker privileges to access an API service.

(3-2) Failure to Verify Token Signatures

If the authentication process fails to verify the JWT’s signature correctly, attackers can forge tokens by altering the payload and signing it with a weak or predictable key. For instance, if the alg field is set to none, the server might accept a token without a signature. This vulnerability allows attackers to modify the token's payload and bypass authentication checks entirely.

(3-3) Algorithm Confusion Attacks

Some JWT libraries allow the algorithm used for signing the token to be specified in the header. An attacker could modify the header to use a different algorithm, like changing HS256 to RS256, and then create a token with a weak signature that the server mistakenly accepts as valid. This type of attack exploits the server's trust in the algorithm specified in the token.

(3-4) Insecure Storage of JWTs

Storing JWTs insecurely on the client side, such as in local storage, can expose them to theft via XSS (Cross-Site Scripting) attacks. If an attacker injects malicious scripts into the client application, they can extract the JWT and use it to impersonate the user. For example, if a user visits a compromised site that executes a script, the script can read the JWT from local storage and send it to the attacker.

(3-5) Lack of Token Expiration and Revocation

If JWTs do not have an expiration time (exp claim) or if the system lacks a mechanism to revoke tokens, compromised tokens can be used indefinitely. This means that once an attacker gains access to a token, they can use it as long as they want, potentially causing long-term security issues. For instance, if an attacker steals a JWT without an expiration date, they can access protected resources indefinitely.

(4) API Key Issues

API keys are a common method for authenticating and authorizing users and applications to access an API. They act as a simple bearer token that must be included in the API request for it to be accepted. However, like JWTs, API keys must be kept secret to ensure the security of the API and its users. Exposing API keys in client-side code or repositories can allow attackers to access the API with the same privileges as the key owner. Understanding and mitigating these risks is crucial for maintaining secure API access.

(4-1) Exposure in Client-Side Code

If API keys are hardcoded in client-side JavaScript or stored in mobile application binaries, attackers can easily extract them. Tools like browser developer tools, reverse engineering, or even simply viewing the source code can reveal these keys.

(4-2) Exposure in Source Code Repositories

Developers may inadvertently commit API keys to public source code repositories like GitHub. Attackers can dork for exposed keys using various tools and gain unauthorized access to the API.

(4-3) Lack of Usage Restrictions

An API key without usage restrictions can be used from any IP address, at any time, and for any purpose, increasing the risk of abuse if the key is compromised.

(4-4) No Expiration or Rotation

API keys that never expire can be used indefinitely if compromised. Attackers can maintain access without the key owner knowing.

(4-5) Insufficient Monitoring and Logging

Without proper monitoring and logging, unusual or malicious usage patterns may go undetected. An attacker could exploit an API key for a long period without the owner’s knowledge.

(5) Brute Force Protections

Brute force attacks are a common method used by attackers to gain unauthorized access to accounts by systematically trying numerous combinations of usernames and passwords until they succeed. Effective brute force protections are essential to safeguard against these attacks. Without adequate measures, attackers can exploit vulnerabilities to repeatedly attempt logins until they find the correct credentials.

(5-1) Missing Rate Limiting

An attacker might script multiple login attempts in rapid succession, cycling through a list of common passwords or using credential stuffing (using lists of breached username/password pairs) to gain access. Therefore it is necessary to apply rate limits to restrict the number of login attempts from a single IP address within a specified timeframe.

To further explore missing rate limiting we can have a look at the example in the OWASP website on exploiting grqphQL to bypass rate limiting:

POST /graphql

{
  "query": "mutation {
	login (username: "{username}", password: "{password}") {
      token
    }
  }"
}

If the credentials are valid in this request, the server returns an authentication token. This token is essential as it must be included in subsequent API requests to verify the user's identity.

To bypass rate limiting mechanisms in this example, attackers might try to exploit weaknesses in how rate limiting is applied. In GraphQL, one such weakness is the ability to batch multiple queries in a single request. This allows an attacker to attempt multiple login attempts within a single HTTP request:

POST /graphql

{"query":"mutation{login(username:\"victim\",password:\"password1\"){token}}"},
{"query":"mutation{login(username:\"victim\",password:\"123456\"){token}}"},
{"query":"mutation{login(username:\"victim\",password:\"qwerty\"){token}}"},
...
{"query":"mutation{login(username:\"victim\",password:\"password123\"){token}}"},

(5-2) Lack of Account Lockouts

Similarly to above but on the attempt level, if there was no penalty for numerous failed loggin attempts, an attacker can repeatedly try to guess a user's password.

(5-3) Absence of CAPTCHA

Bots are capable of making thousands of attempts per minute and can therefore bombard the login endpoint with an enormous amount of attempts. Therefore CAPTCHA challenges after a certain number of failed login attempts or during the login process itself add a layer of protection against automated attacks.

(5-4) Insufficient IP Whitelisting and Blacklisting

If an attacker repeatedly tries to log in from a specific IP address or a range of addresses known to be associated with malicious activity, the lack of proper IP whitelisting and blacklisting can leave your system vulnerable. Implementing IP whitelisting allows you to restrict access to your application from trusted IP addresses only, particularly for administrative and sensitive operations. Conversely, blacklisting known malicious IP addresses or those exhibiting suspicious behavior can help block potential attackers.

(6) Login Flows

Examining the security of login flows is crucial for ensuring that tokens cannot be generated or hijacked during the authentication process. This involves scrutinizing every step of the login process to identify potential vulnerabilities that attackers could exploit to gain unauthorized access. Here are several key areas to focus on:

(6-1) Token Interception

An attacker can try to intercept tokens during transmission using man-in-the-middle (MitM) attacks where he eavesdrops on the communication between the client and server to capture sensitive information such as authentication tokens. As an instance, the use of HTTPS to encrypt data transmitted between the client and server prevents attackers from intercepting tokens and other sensitive information.

(6-2) Token Redirection

An attacker manipulates the login flow to redirect tokens to an attacker-controlled endpoint. This can happen if the redirect URIs are not properly validated. Therefore validate all redirect URIs and ensure they match pre-registered, trusted addresses. Implement exact matching and avoid accepting dynamically generated or user-provided URIs.

(6-3) Session Fixation

An attacker forces a user to authenticate with a known session ID, allowing the attacker to hijack the session after authentication. As a mitigation regenerate session IDs upon successful authentication to ensure that the session ID used during login is not the same as the one used post-authentication.

(6-4) Cross-Site Request Forgery (CSRF)

An attacker tricks a user into performing actions without their knowledge by exploiting the user’s authenticated session. For instance, a user could be tricked into clicking a link that initiates a login flow with their credentials. Therefore implement anti-CSRF tokens that are unique to each session and verify these tokens on the server side to ensure the authenticity of requests.

(7) Account Takeover Techniques

Account takeover techniques exploit a range of vulnerabilities to gain control over users' accounts, leading to potentially severe data breaches and unauthorized actions.

Attackers often employ phishing attacks to trick users into revealing their credentials by mimicking legitimate login pages or sending deceptive emails. Once the attackers obtain these credentials, they can access the user's account and perform unauthorized activities.

Preventing account takeovers requires a multi-faceted approach. Implementing comprehensive security measures such as multi-factor authentication (MFA) can add an extra layer of protection, making it more difficult for attackers to gain access even if they have the user's credentials.

User education is also critical; educating users on recognizing phishing attempts and the importance of using strong, unique passwords can reduce the risk of credential theft.

Preventing Broken Authentication Vulnerabilities

To safeguard against Broken Authentication vulnerabilities, it is essential to implement robust security measures. Here are some best practices to help prevent these vulnerabilities, as provided by OWASP at API2:2023 Broken Authentication:

Conclusion

In this post, we explored the concept of Broken Authentication through a festival analogy, highlighting how minor security oversights can lead to significant breaches. We examined how Broken Authentication applies to API security, emphasizing the need for robust authentication mechanisms and following best practices to improve the security of authentication mechanisms and protect against vulnerabilities.

By understanding the complexities of authentication mechanisms, we can safeguard our APIs from malicious access. Implementing comprehensive security measures such as multi-factor authentication, secure token storage, and stringent verification processes are crucial steps in fortifying our systems.

However, authentication is just one piece of the API security puzzle. In our next article, we will continue the festival security saga by diving into the world of Broken Object Property Level Authorization (BOPLA), another critical vulnerability in API security.

Stay tuned as we unravel more challenges related to authorization and explore strategies to further fortify our APIs against this pervasive threat.

Comments

Sunny -

Nice article.

Leave a Comment

Please preserve the rules of respect and avoid any shadow that might fall upon the realm. Keep your discourse pure and use simple characters. Your scroll shall contain no more than a thousand characters.

Only the worthy may share their wisdom beneath the sacred tree of insight. To prove yourself a true hero and not a shadowy automation, solve this puzzle:

captcha