Decoding JWT: Unveiling Vulnerabilities in API Security

12 min read

January 14, 2024

Exploring API Security: A Practical Guide to Uncovering Vulnerabilities
Decoding JWT: Unveiling Vulnerabilities in API Security

Table of contents

Introduction: Mastering JWTs in API Hacking

Welcome back to our enthralling series where the art of API hacking takes center stage! Having journeyed through various methodologies in the previous chapter, we're now set to dive deeper into a specific, yet critical aspect of API security – the world of JSON Web Tokens (JWTs).

In the realm of API hacking, understanding JWTs is not just beneficial; it's essential. These tokens are the keystones of authentication and authorization in numerous web applications. This chapter will shed light on the inner workings of JWTs, unraveling how they function, why they're so pivotal in APIs, and most importantly, how they can become potential targets for hackers.

Our exploration won't stop at theory. We'll venture into the practical world, donning our hacker's hats to uncover and exploit JWT vulnerabilities. Armed with tools like jwt_tool and Burp Suite, we'll demonstrate real-life hacking scenarios. You'll learn to identify weaknesses, test for vulnerabilities, and understand the attacker's perspective, which is crucial in fortifying your own APIs.

Get ready to immerse yourself in the intriguing world of JWTs within API hacking. Whether you're honing your hacking skills, seeking to fortify your APIs, or simply fascinated by the world of cybersecurity, this chapter promises to be a treasure trove of knowledge and hands-on learning.

Unlocking the Secrets of Authentication: A Journey into JWTs

First up on our agenda is a deep dive into the login portal of our application. We're embarking on a journey to unravel how users are authenticated and then authorized to access various URLs. It's like being a digital detective, piecing together the intricate puzzle of online security.

Do you recall the user we created in the registration form from the previous chapter? It's time to don our detective hats and intercept their login request. This is where the digital magic unfolds – we're about to witness a token spring into action. Picture it as a backstage pass; the moment the user logs in, a token is issued, swinging open the doors to various parts of the application.

upload in progress, 0
Token returned by the application

Now, our focus shifts to the token we've just uncovered. Consider it the master key, deftly managing access across the application's landscape. As we delve deeper, observing the requests within the application, we'll discover a consistent pattern: this token proudly parades in the headers of every request. It’s not just a key; it’s a VIP badge, dictating the realms accessible to our user.

JWT in request headers

And this brings us to the epicenter of our digital quest – these tokens are known as JWTs, short for JSON Web Tokens. They are the unsung heroes in the world of web applications, playing a pivotal role in managing authentication and authorization, particularly in APIs. Think of them as the Swiss Army knife for digital access. In today's chapter, we're setting off to explore the enigmatic yet fascinating world of JWTs. We'll delve into their mechanics and understand their vital role in our application's ecosystem. Brace yourself for an intriguing exploration into the world of JWTs

Introduction to JSON Web Tokens (JWTs)

Imagine you're at a carnival, and upon entering, you buy a ticket that grants you access to all the rides. This ticket is much like a JWT.

JWT structure

A JWT is a compact, self-contained string used for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Think of it as a secure package that contains important information (known as claims). These claims might include user identity, authorization data, or any other data you want to safely transfer.

When a user logs in to an application, the server creates a JWT with user-specific data and sends it back to the user. The user's device stores this JWT and includes it in the header of future requests to the server. This is like showing your ticket every time you want to get on a ride at the carnival.

Payload of the JWT decoded with CyberChef

The server, upon receiving a request with a JWT, decodes and verifies it. If the token is valid, the server proceeds with the request, knowing it's authenticated and authorized.

In short, JWTs are like secure, digital tickets used in the online world to ensure that the data being exchanged is authentic and authorized. They're widely used for authentication and information exchange in web applications, making online interactions smoother and safer.

Understanding the Vulnerabilities of JSON Web Tokens (JWTs)

However, like any system, JWTs come with their own set of vulnerabilities. Addressing these weaknesses is crucial to maintain the integrity and security of the applications relying on them. Let’s explore some of the main vulnerabilities associated with JWTs:

  1. Insecure Secret Keys: The strength of a JWT lies in its secret key, used for signing the token. If this key is weak or commonly known, attackers can easily decode and tamper with the token, compromising the security.
  2. Algorithm Manipulation: JWTs allow choosing the algorithm for signing. If an attacker changes the algorithm to a less secure one or 'none', it can lead to the system accepting a forged token.
  3. Exposed Sensitive Information: JWTs should not contain too much sensitive information, especially if not properly encrypted. Exposing such data can lead to privacy breaches and security risks.
  4. Lack of Token Expiration: Tokens without an expiration time can be risky, as they can be used indefinitely, potentially by unauthorized parties if they are intercepted.
  5. Flawed Token Validation: Proper validation of JWTs is essential. Without it, unauthorized users might gain access, much like someone slipping through a malfunctioning turnstile.
  6. Signature Stripping: In this attack, the signature part of the JWT is removed, leading to the acceptance of a potentially forged token if the system fails to verify its authenticity.
  7. Header and Payload Manipulation: Altering the information within a JWT can lead to unauthorized access or privilege escalation, similar to tampering with a ticket's details to gain unauthorized entry.

In essence, while JWTs are efficient and widely used for authentication and information exchange, understanding and mitigating their vulnerabilities is key to maintaining robust security in web applications. Just as safety measures in a carnival ensure a secure and enjoyable experience, addressing JWT vulnerabilities ensures a secure and trustworthy digital environment.

Main Tools for Analyzing JWT Security

In our exploration of JWT security, we will be utilizing a range of tools, each offering unique capabilities for analyzing and mitigating vulnerabilities in JWT implementations. These tools provide a comprehensive approach to ensuring robust JWT security.

  1. jwt_tool: This command-line utility excels in testing JWTs, allowing for the manipulation of tokens and the simulation of various attack scenarios.
  2. Burp Suite: An integrated platform for web security testing, Burp Suite offers features like traffic interception, automated scanning, and extensive analysis capabilities, including those for JWTs.
  3. jwt.io: An essential addition to our toolkit, jwt.io serves both as an educational resource and a practical tool for decoding, verifying, and generating JWTs. Its user-friendly interface makes it an excellent tool for quickly understanding and analyzing the structure and validity of JWTs.
  4. JWTCrack: Focused on cracking JWTs with weak secret keys, this tool is a testament to the importance of robust key management.
  5. JWTSpy: A Python-based tool for analyzing JWTs, JWTSpy identifies common vulnerabilities and misconfigurations, providing insights into potential security gaps.

Focusing on jwt_tool, Burp Suite, and jwt.io for Today's Analysis

For today's detailed analysis, we will be focusing on jwt_tool, Burp Suite, and jwt.io. This selection is strategic, allowing us to cover a wide range of testing and analysis scenarios:

  • jwt_tool offers specialized functionalities for JWT testing, such as token manipulation and vulnerability testing.
  • Burp Suite provides a broad array of features for intercepting and analyzing web traffic, making it invaluable for examining JWTs within HTTP requests.
  • jwt.io will be utilized for its simplicity and effectiveness in decoding and encoding JWTs, which is crucial for understanding the structure and integrity of the tokens we are analyzing.
Concatenatio of tools

Together, these tools form a comprehensive toolkit for our JWT security testing. We aim to use these tools to uncover any potential vulnerabilities and to ensure that the JWT implementations in our applications are secure, reliable, and resilient against various types of attacks.

The Adventure of Attacking JWTs

Now that we've armed ourselves with the essential knowledge to audit JWT tokens and familiarized ourselves with the most important tools, it's time to dive into the really exciting part – testing the security of the token! 😊

Unraveling JWTs: The Art of Token Identification

The first step in our adventure is a bit like detective work: we need to do some reconnaissance to uncover what algorithm is used for the signature and what secrets the payload holds. For this task, jwt.io is our go-to tool – it's like having a magnifying glass that quickly reveals everything we need to know. Take a look at the image below to see jwt.io in action.

jwt.io to decode the token

It's interesting to note that jwt_tool can also be used for this purpose.

python3 jwt_tool.py eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJyc2diZW5naUBnbWFpbC5jb20iLCJyb2xlIjoidXNlciIsImlhdCI6MTcwMzY5NTIwNywiZXhwIjoxNzA0MzAwMDA3fQ.AsLqfKslKe5_LRW7qan_C5WXO4vb11PAg4nVukyrLYH4cQKDDc5KrAx224VbddGiZMQI2DCEOYNmiQv55ryyie99jWHBVXXzDC-oUiNEegbswBIrAo1b5OM4t1C5ldbfyshdpkz4wqSQlIWi_CqH0F6r7BIe2DbwqI3EalY64pODNXWooEIjFVpwVwCUgY1fPPD8j_bcB39mXdBo8TBRi-jvVaQtzorXvRveL7FwskWcujLW4JudHzo4GofUoUJKaoPLv59dcjziPhOIRpXnnlArJxhH9AtXG5Ai75xBWPX5xffhYm4Ok6TK3o7wSPFVWXpZ0EP90In1qr8UAW3vzg

When we examine the JWT.io output, we notice something intriguing: the JWT's signature is marked as invalid. This could be a critical clue, hinting that the token may not be generated properly. It opens up the possibility of modifying the jwt payload and still having it accepted by the application – a potential security loophole.

Embarking on a JWT Vulnerability Scanning Expedition

With our preliminary reconnaissance through jwt.io wrapped up and the basic JWT information in hand, it's time to gear up for the next phase of our adventure: a vulnerability scan using jwt_tool. Think of this as setting out on a treasure hunt, where the treasure is hidden vulnerabilities waiting to be discovered.

python3 jwt_tool.py -t http://192.168.20.120:8888/identity/api/v2/user/dashboard -rh "Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJyc2diZW5naUBnbWFpbC5jb20iLCJyb2xlIjoidXNlciIsImlhdCI6MTcwMzY5NTIwNywiZXhwIjoxNzA0MzAwMDA3fQ.AsLqfKslKe5_LRW7qan_C5WXO4vb11PAg4nVukyrLYH4cQKDDc5KrAx224VbddGiZMQI2DCEOYNmiQv55ryyie99jWHBVXXzDC-oUiNEegbswBIrAo1b5OM4t1C5ldbfyshdpkz4wqSQlIWi_CqH0F6r7BIe2DbwqI3EalY64pODNXWooEIjFVpwVwCUgY1fPPD8j_bcB39mXdBo8TBRi-jvVaQtzorXvRveL7FwskWcujLW4JudHzo4GofUoUJKaoPLv59dcjziPhOIRpXnnlArJxhH9AtXG5Ai75xBWPX5xffhYm4Ok6TK3o7wSPFVWXpZ0EP90In1qr8UAW3vzg" -M pb| tee jwt_scan.txt

In this command, we're launching a probing expedition against various JWT vulnerabilities, seeking out any chinks in the armor that we might exploit to escalate privileges or access privileged information.

As we analyze the scan results, imagine each green highlight as a marker of treasure – these are the vulnerabilities detected by our trusty tool. It's quite astonishing to see how many there are! Now, the real fun begins as we leverage these vulnerabilities. Let's dive in and see how we can turn these findings to our advantage, potentially uncovering paths to privileged access or sensitive information.

Unleashing Burp Suite for JWT Testing

Let's up the ante in our JWT security exploration by bringing another player into the game – Burp Suite. But first, to make our tests even more effective, let's create another user in the application. It's like having an extra character in a video game, each with different abilities and access levels.

Registration of another user

In the request we are working with, which is the main one that comes up when we enter the dashboard, we can see that if we do not alter anything, it shows us information about the user with which we have accessed

Request without changing data

This is where Burp Suite steps in, acting like a digital scalpel. In the payload section of our token, we get the chance to tweak the data. What happens if we change the email to one that doesn't exist? It's like trying different keys in a lock until we find a mismatch. And indeed, the application responds by indicating the user doesn't exist. This is a telltale sign that the token signature might not be crafted or validated correctly.

Alteration of payload data (select only the payload zone for burp to recognize it)
Email does not exist

Now, let's turn the dial up. We aim to see if we can access information from another user just by knowing their email. With two users on the platform, we have the perfect setup for this test.

💡
Remember, in an API hacking audit, having at least two users – one with high privileges and one with lower ones – is crucial. It's like having two different lenses to view and understand the application's security landscape.

So, let's make a switch in the email within the payload. And voilà! We find that we can indeed access information from another user – a door that, in theory, should have remained closed to us. This discovery not only highlights a critical security flaw but also underscores the power of tools like Burp Suite in unearthing these vulnerabilities.

Listing another user's information

The Final Challenge: Attempting to Change Another User's Password

Equipped with our newfound insights, let's push the boundaries a bit further. We suspect that other endpoints might also have vulnerabilities. What if we try something riskier, like changing another user's password? It's like testing the waters to see how deep the security flaws go.

We start by capturing the request where we change the password for the user we're logged in with. It works like a charm; our password changes without a hitch. But now, let's spice things up. We tweak the payload, changing the email to that of another user. The goal? To see if we can reset their password. In this high-stakes game, we're using the Burp JSON Web Token plugin for the alteration, adding a new twist to our testing strategy.

Password change request
Invalid token detection

However, this endpoint seems to have a tighter security net. Despite our best efforts, it refuses to let us change another user's password. It’s a reminder that not all doors can be unlocked, even with the right set of tools.

We don't stop there. Running jwt_tool against this endpoint reveals something interesting – no green tests this time, indicating that this endpoint is not vulnerable. It's like finding a well-secured treasure chest that refuses to budge.

No vulnerability found

This experience underscores a crucial lesson: always test multiple endpoints. What fails on one might succeed on another. In the world of security testing, it's essential to cover all bases, leaving no stone unturned in our quest to ensure the application’s fortitude.

Fascinating Insight: The Storage and Impact of JWTs in Browsers

Here's an intriguing piece of information that might seem straightforward but is often overlooked by those new to the field or with limited development experience. JWT tokens are commonly stored in a browser's local storage. This storage method is what makes them persistent and enables their inclusion in all API requests.

But there's more to it. What's particularly interesting to note is that developers sometimes leave part of the payload outside the JWT, perhaps in another cookie's value. And here's where it gets fascinating – altering this payload (often the role or permissions specified in the JWT) can change how the front-end appears. This means that tweaking these details could potentially reveal more of the application or expand the scope of endpoints accessible to us.

It's a subtle yet powerful aspect of JWTs that highlights the importance of thorough security considerations in both backend and frontend development. Understanding this can give us a better grasp of how applications function and, importantly, how they can be made more secure.

JWT in local storage

Concluding Thoughts: A Journey Through the World of JWTs and Beyond

As we draw the curtain on this insightful exploration into JWTs and their role in API hacking, it's important to reflect on the journey we've taken. We delved into the intricate workings of JWTs, uncovering a particular vulnerability that revealed the nuanced challenges in securing APIs. However, this is just the tip of the iceberg. JWTs harbor a myriad of vulnerabilities, each requiring careful consideration and strategic defense mechanisms.

For those eager to dive deeper and uncover more about these vulnerabilities, I highly recommend visiting the Burp Suite website. It's a treasure trove of information, offering further insights and resources on the subject.

But perhaps the most crucial takeaway is the importance of asking "what if" questions. In our journey, we experimented by changing the email within a JWT, but what if we had altered the user's role to 'admin'? Such questions are the bedrock of effective security testing and ethical hacking. They push us to think beyond the obvious, to explore every possible angle, and to anticipate the moves of potential attackers.

Remember, the world of cybersecurity is constantly evolving, and staying ahead means never ceasing to question, explore, and learn. This article is just a starting point – your journey into mastering API hacking and understanding the complexities of JWTs is an ongoing adventure.

Chapters

Botón Anterior
Unveiling API Hacking: A Methodological Journey Through Recognition and Exploration

Previous chapter

Securing the Gates: Mastering BOLA and BFLA in API Security

Next chapter