courses

Qiling: Emulating a Windows Sample End to End

Qiling emulates a Windows PE on a Linux host without a Windows kernel and without Wine. The sample’s own instructions really execute, on Unicorn; everything below the sample — the Win32 API, the registry, the filesystem — is Python that Qiling supplies, and that you can replace.

That last clause is the whole reason to choose it. Speakeasy is faster to a first report and needs no Windows files at all. Qiling asks you to assemble a rootfs and then hands you the emulator’s internals. Pick it when you need to intervene: answer an API the way the sample does not expect, skip a check, read a buffer at the moment it is decrypted.

This page builds a working rootfs from a real Windows installation, emulates the specimen.exe from the Windows dynamic-analysis page, and shows the emulator missing two of its three known behaviors before fixing it.

Where this fits. Keep Dynamic Analysis of Windows Malware from Linux open alongside this page. It frames the three ways to run a PE on Linux and sets the discipline this page depends on: calibrate on a sample whose behavior you already know, and count the behaviors.

What a Qiling rootfs actually is

Qiling does not ship Windows DLLs or registry hives — Microsoft’s licence does not let it. The examples/rootfs submodule has a x8664_windows/ directory containing nothing but an empty bin/. You supply the rest.

The emulator needs two things from you:

Path under the rootfs Why
Windows/System32/*.dll Real DLLs. Qiling parses their exports and relocates them into the emulated address space, so imports resolve to real addresses.
Windows/registry/ Five hive files. Qiling opens all of them at startup, before the sample’s first instruction.

Three DLLs load on every run regardless of what the sample imports — ntdll.dll, kernel32.dll, user32.dll. On top of those, Qiling resolves api-ms-win-* virtual DLLs by scanning ntdll.dll, kernelbase.dll, and ucrtbase.dll for the requested symbol, so those three want to be present even when nothing names them.

The hives, and the one that does not exist

Qiling maps hive names onto filenames in Windows/registry/:

Qiling expects Comes from
SYSTEM, SOFTWARE, SAM, SECURITY C:\Windows\System32\config\
NTUSER.DAT a user profile, or config\DEFAULT
HARDWARE nowhere

HKLM\HARDWARE is a volatile hive. The kernel builds it in RAM at every boot from what it enumerates on the bus; there has never been a file for it. Qiling opens all six eagerly in RegHive.__init__, so a missing HARDWARE aborts startup with Windows registry hive not found — a message that tells you nothing about which hive. Give it the smallest valid hive you have as a stand-in; SECURITY is 64 KB and nothing in this exercise reads HKLM\HARDWARE anyway.

Building the rootfs

A mounted Windows volume is all you need — your own dual-boot partition, a VM’s disk image, or an installer’s install.wim. Mount it read-only if you can. qiling_rootfs.sh copies what is wanted:

$ ./qiling_rootfs.sh /run/media/you/Windows ~/qiling/rootfs/x8664_windows
/home/you/qiling/rootfs/x8664_windows: 25 DLLs, 6 hives
#!/bin/sh
# Build a Qiling x86-64 Windows rootfs from a mounted Windows installation.
set -eu

WIN="${1:?usage: qiling_rootfs.sh <mounted-windows-root> <rootfs-dir>}"
OUT="${2:?usage: qiling_rootfs.sh <mounted-windows-root> <rootfs-dir>}"

SYS32="$WIN/Windows/System32"
CONF="$SYS32/config"

mkdir -p "$OUT/Windows/System32" "$OUT/Windows/registry"

# Paths a sample writes to must already exist -- Qiling's CreateFile does not
# create parent directories, it just returns INVALID_HANDLE_VALUE.
mkdir -p "$OUT/Users/Public" "$OUT/Windows/Temp" "$OUT/ProgramData"

# Windows stores these with mixed case (KernelBase.dll, IPHLPAPI.DLL). Look
# them up case-insensitively and write them out lowercase.
for want in ntdll kernel32 kernelbase user32 advapi32 msvcrt ucrtbase \
            ws2_32 dnsapi mswsock iphlpapi urlmon wininet vcruntime140 \
            gdi32 shell32 shlwapi ole32 oleaut32 crypt32 bcrypt \
            sechost rpcrt4 psapi version; do
    src=$(find "$SYS32" -maxdepth 1 -iname "$want.dll" -print -quit)
    [ -n "$src" ] && cp "$src" "$OUT/Windows/System32/$want.dll"
done

for h in SAM SECURITY SOFTWARE SYSTEM; do
    cp "$CONF/$h" "$OUT/Windows/registry/$h"
done
cp "$CONF/DEFAULT" "$OUT/Windows/registry/NTUSER.DAT"
cp "$CONF/SECURITY" "$OUT/Windows/registry/HARDWARE"

chmod -R u+w "$OUT"

Two details that cost time if you skip them:

Case. Windows stores KernelBase.dll and IPHLPAPI.DLL with mixed case. Qiling’s loader does fall back to a case-insensitive search of the host path, so either form works once copied — but a naive cp "$SYS32/kernelbase.dll" silently copies nothing on a case-sensitive filesystem, and the failure surfaces much later as unresolved api-ms-win-* imports.

Directories the sample writes to. Qiling’s CreateFile opens a real host file under the rootfs; it does not create parent directories. A sample dropping to C:\Users\Public\ gets INVALID_HANDLE_VALUE unless $ROOTFS/Users/Public/ exists. Pre-create the usual drop sites.

The rootfs is Microsoft’s code. Do not commit it, and do not pass it around. Everyone who needs one builds it from a Windows installation they already have a licence for. The script is the shareable artifact.

The specimen

The subject is the benign dropper from the Windows dynamic-analysis page — a Run-key write, a file drop, and a C2 name lookup, cross-compiled with MinGW:

$ x86_64-w64-mingw32-gcc -O1 -nostartfiles -nostdlib \
      -o specimen.exe specimen.c -lkernel32 -ladvapi32 -lws2_32
$ python3 -c "import pefile; pe=pefile.PE('specimen.exe'); \
    print(sum(len(e.imports) for e in pe.DIRECTORY_ENTRY_IMPORT), 'imports')"
11 imports

Eleven imports across three DLLs, and three behaviors. Hold onto the number three.

The naive run

Thirteen lines gets a PE executing:

from qiling import Qiling
from qiling.const import QL_VERBOSE

ql = Qiling(["specimen.exe"], "/home/you/qiling/rootfs/x8664_windows",
            verbose=QL_VERBOSE.DEFAULT)
ql.run()

It runs, and the trace looks healthy — until you read it against the ground truth:

[!] 	api RegCreateKeyExA (advapi32) is not implemented
[!] 	api RegCreateKeyExInternalA (kernelbase) is not implemented
[!] 	api RtlOpenCurrentUser (ntdll) is not implemented
[!] 	api ZwQueryInformationToken (ntdll) is not implemented
[=] 	CreateFileA(lpFileName = "C:\\Users\\Public\\dropped.bin", ...) = 0xa0000001
[=] 	WSAStartup(wVersionRequested = 0x202, lpWSAData = 0x80000001ce48) = 0x0
[!] 	api getaddrinfo (ws2_32) is not implemented
[=] 	FatalExit(ExitCode = 0)

One of the three behaviors is in that trace. The drop is there — CreateFileA returned a handle, WriteFile followed. The other two are gone:

And the process ends in FatalExit, not the ExitProcess(0) the specimen calls — the run derailed and the summary line still looks like a clean exit.

This is the same trap as the Speakeasy result on the Windows dynamic-analysis page: a plausible, well-formatted, incomplete report. An unimplemented API is a warning line in a wall of warning lines, not an error. If you had not known the answer was three, nothing here would have told you that two behaviors were missing.

Filling the gaps

Qiling’s answer to a missing API is that you write it. ql.os.set_api() takes a name and a handler, with three interception modes:

Mode Effect
QL_INTERCEPT.CALL (default) Your handler replaces the implementation. The only option when there is nothing to replace.
QL_INTERCEPT.ENTER Runs before the real handler; may rewrite the arguments.
QL_INTERCEPT.EXIT Runs after, and sees the return value; may rewrite it.

A handler is an ordinary function wrapped in @winsdkapi, which declares the calling convention and the parameter types so Qiling can unmarshal the stack for you. Here is RegCreateKeyExA, from qiling_specimen.py:

@winsdkapi(cc=STDCALL, params={
    'hKey'                 : HKEY,
    'lpSubKey'             : LPCSTR,
    'Reserved'             : DWORD,
    'lpClass'              : POINTER,
    'dwOptions'            : DWORD,
    'samDesired'           : REGSAM,
    'lpSecurityAttributes' : POINTER,
    'phkResult'            : POINTER,
    'lpdwDisposition'      : POINTER
})
def hook_RegCreateKeyExA(ql: Qiling, address: int, params):
    # HKEY_CURRENT_USER is the LONG 0x80000001 cast to a pointer, so on
    # x86-64 it arrives sign-extended as 0xffffffff80000001. Qiling's handle
    # table is keyed on the 32-bit value; mask before looking it up.
    hive = ql.os.handle_manager.get(params['hKey'] & 0xffffffff)
    keyname = f"{hive.name}\\{params['lpSubKey']}"

    behaviors.append(f"persistence: creates {keyname}")

    if not ql.os.registry_manager.exists(keyname):
        ql.os.registry_manager.create(keyname)

    # Hand back a handle whose obj is the key path. Qiling's RegSetValueEx
    # reads handle.obj, so a bare hive handle (obj=None) is not good enough.
    handle = ql.os.handle_manager.search_by_obj(keyname)

    if handle is None:
        handle = Handle(obj=keyname)
        ql.os.handle_manager.append(handle)

    ql.mem.write_ptr(params['phkResult'], handle.id)

    return ERROR_SUCCESS

Three things in there are not obvious, and each one is a debugging session if you meet it cold.

lpClass is POINTER, not LPSTR. The SDK type is correct and it crashes the emulator. LPSTR makes Qiling resolve the argument by reading a C string at that address; the specimen passes NULL, the read returns None, and Qiling’s own argument logging — process_fcall_params in qiling/os/os.py — has handlers for int, str, bytearray, and tuple but none for None. The result is a KeyError: <class 'NoneType'> reported as Windows API Implementation Error, thrown before your handler body runs. Declaring the pointer types you do not need as POINTER sidesteps it; read the strings yourself with ql.os.utils.read_cstring() when you want them.

The handle arrives sign-extended. HKEY_CURRENT_USER is the LONG 0x80000001 cast to a pointer, so in a 64-bit register it is 0xffffffff80000001. Qiling’s handle table keys on 0x80000001, so an unmasked handle_manager.get() returns None.

The handle you return needs an obj. RegSetValueEx does ql.os.handle_manager.get(hKey).obj and uses the result as the key path. Returning the hive’s own handle — whose obj is None — poisons the next call rather than this one.

getaddrinfo is much simpler, because nothing downstream consumes its result here:

@winsdkapi(cc=STDCALL, params={
    'pNodeName'    : POINTER,
    'pServiceName' : POINTER,
    'pHints'       : POINTER,
    'ppResult'     : POINTER
})
def hook_getaddrinfo(ql: Qiling, address: int, params):
    host = ql.os.utils.read_cstring(params['pNodeName'])
    port = ql.os.utils.read_cstring(params['pServiceName'])

    behaviors.append(f"c2 lookup: {host} port {port}")

    # Report a miss rather than fabricating a sockaddr. A sample that only
    # resolves a name has already told us what we wanted to know; one that
    # branches on the answer is the reason to return success instead.
    return 0x2AF9      # WSAHOST_NOT_FOUND

Returning a failure is a deliberate choice, and the wrong one for some samples. A dropper that resolves a name and then gives up has already told you what you wanted. A dropper that branches on the answer — connecting, sending a beacon, decrypting a second stage only on success — needs you to write a sockaddr into ppResult and return 0, so execution continues down the interesting path. Qiling exists to let you make that choice per sample.

The two observers use ENTER and EXIT on APIs Qiling already implements, so the real behavior still happens:

opened = {}

def on_createfile(ql: Qiling, address: int, params, retval):
    """QL_INTERCEPT.EXIT -- runs after the real implementation returns."""
    if retval != INVALID_HANDLE_VALUE:
        opened[retval] = params['lpFileName']

def on_writefile(ql: Qiling, address: int, params):
    """QL_INTERCEPT.ENTER -- observe without replacing the implementation."""
    path = opened.get(params['hFile'], '<unknown handle>')
    behaviors.append(f"drop: {params['nNumberOfBytesToWrite']} bytes to {path}")

EXIT is what makes the handle-to-path mapping possible: the path is an argument, the handle is the return value, and only an exit hook sees both. Qiling’s file handles carry no name, so without this WriteFile can report a byte count but not a target.

The result

$ ./qiling_specimen.py --naive ~/qiling/rootfs/x8664_windows
1 of 3 behaviors observed:
  * drop: 24 bytes to C:\Users\Public\dropped.bin

$ ./qiling_specimen.py ~/qiling/rootfs/x8664_windows
3 of 3 behaviors observed:
  * persistence: creates HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
  * drop: 24 bytes to C:\Users\Public\dropped.bin
  * c2 lookup: updates.example-c2.test port 80

Both runs install the same two passive observers, so the counter measures the same thing either way. The difference is purely the two replacement hooks.

The side effects are real, and they are in your rootfs

Emulation is not a read-only operation. The registry write lands in a JSON diff beside the rootfs, and the drop lands on your disk:

$ cat ~/qiling/rootfs/x8664_windows/registry/specimen.exe_diff.json
{
    "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run": {
        "SecurityUpdate": {
            "type": "REG_SZ",
            "value": "C:\\Users\\Public\\dropped.bin"
        }
    }
}
$ cat ~/qiling/rootfs/x8664_windows/Users/Public/dropped.bin
not actually malicious

Note the path: registry/ at the root of the rootfs, not the Windows/registry/ the hives live in. Qiling reads hives from one place and writes the diff to another.

The diff is a genuinely useful artifact — it is a clean inventory of every registry write the sample made, which is what you would otherwise reconstruct from ProcMon. But it also means the rootfs accumulates state between runs. A second run of a sample that checks for its own Run key before installing it takes a different path than the first. Treat the rootfs as disposable:

$ rm -rf ~/qiling/rootfs/x8664_windows/registry
$ find ~/qiling/rootfs/x8664_windows/Users ~/qiling/rootfs/x8664_windows/Windows/Temp \
       -type f -delete

Or keep a pristine copy and cp -a it per sample. The DLLs are ~210 MB, so reflink or snapshot it if your filesystem can.

Where emulation stops

Qiling gets further than Speakeasy on this specimen because you wrote two functions, and that is the honest summary of the trade. Before reaching for it on real malware, know its edges:

Emulation is the right tool for reaching a specific moment cheaply and repeatably — the instant a buffer is decrypted, the branch an anti-debug check takes. It is the wrong tool for “what does this sample do”, because the answer is always “whatever it does on the parts I implemented”.

Key takeaways

References

Maintenance note: written against Qiling 1.4.6 (the version Arch and most distributions package) on Python 3.14, and checked against qiling master as of 29 October 2026, where the latest release is 1.4.11 (6 September 2026). All three workarounds on this page are still needed upstream: advapi32.py implements RegCreateKeyExW but not RegCreateKeyExA, wsock32.py implements gethostbyname but not getaddrinfo, and process_fcall_params in os/os.py still has no None handler. Re-check all three before next offering — the first two are plainly coverage gaps rather than design decisions, and a single upstream commit could make half this page unnecessary. The rootfs DLL list was collected from a Windows 11 24H2 installation (build 10.0.26100.9568); Qiling’s own docs/DLLX8664.txt still documents Windows 10 1803 files.