Qiling: Emulating a Windows Sample End to End
- What a Qiling rootfs actually is
- Building the rootfs
- The specimen
- The naive run
- Filling the gaps
- The result
- Where emulation stops
- Key takeaways
- References
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:
- No
RegCreateKeyExA. Qiling implementsRegCreateKeyA,RegCreateKeyW, andRegCreateKeyExW— but notRegCreateKeyExA, which is the one a C dropper calls. The cascade of unimplementedntdllcalls after it is the tell: having no handler, Qiling let the sample fall through into the realadvapi32.dllcode it loaded from your rootfs, which promptly needed a dozenRtl*andZw*internals Qiling also lacks. - No
getaddrinfo.gethostbynameis implemented;getaddrinfo, which is what anything written this century calls, is not. The C2 hostname never appears in the trace.
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:
- Coverage is a long tail. Two gaps in eleven imports, in a specimen with no C runtime. Real malware imports hundreds of functions, and the ones a packer or an anti-analysis check calls are exactly the obscure ones nobody has implemented yet.
- Unimplemented is not an error. It is a warning, and execution continues
into the real DLL, where it usually dies in a way that does not look like a
missing API. Grep your trace for
not implementedbefore you trust any report. - Emulation is detectable. No kernel, no scheduler, no real timing.
GetTickCountdeltas,rdtscratios, and a thread count of one are all giveaways, and none of them need a VM-detection library. - Nothing reaches the network. That is the point — but it also means a sample whose behavior is entirely “download stage two” has no behavior to observe. Pair emulation with a KVM guest and FakeNet-NG when the payload is remote.
- It is slow. Unicorn on an instrumented Win32 layer; fine for a dropper, not for something that spins for thirty seconds before acting.
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
- The rootfs is yours to build. Qiling ships no Microsoft code. The DLLs come from a real installation you have a licence for; the script to collect them is the artifact you share.
HKLM\HARDWAREhas no file. It is volatile, built in RAM at boot. Qiling opens it anyway; supply a stand-in hive.- Pre-create the drop directories. Qiling’s
CreateFiledoes not make parents, it just fails — and a failed drop looks like a sample that did not drop. RegCreateKeyExAandgetaddrinfoare missing. The ANSI and modern variants of two of the most common malware APIs, both with an implemented sibling that makes the gap easy to miss.- An unimplemented API costs you a behavior, silently. The sample falls through to the real DLL and derails somewhere unrelated. Ground truth is the only thing that catches it.
- The correct SDK parameter type can crash the emulator. A
NULLstring declaredLPSTRresolves toNone, which Qiling’s argument logging cannot format. Declare unused pointers asPOINTER. - Decide what your hook returns, per sample. Failing
getaddrinfois right for a dropper that gives up and wrong for one that branches on success. This choice is the reason you picked Qiling. - Emulation leaves state in your rootfs. The registry diff and dropped files persist across runs. Reset between samples.
References
- Qiling Framework — source,
examples/rootfssubmodule, and the DLL lists indocs/DLLX8664.txt. https://github.com/qilingframework/qiling - Qiling — documentation, installation, and Windows rootfs setup. https://docs.qiling.io/
- Qiling —
rootfssubmodule repository. https://github.com/qilingframework/rootfs - Qiling — Windows Emulation wiki page. https://github.com/qilingframework/qiling/wiki/Windows-Emulation
- Unicorn Engine — the CPU emulator Qiling drives. https://www.unicorn-engine.org/
- Microsoft Learn —
RegCreateKeyExA. https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeyexa - Microsoft Learn —
getaddrinfo. https://learn.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfo - Microsoft Learn — predefined registry keys, including the volatile
HKEY_LOCAL_MACHINE\HARDWARE. https://learn.microsoft.com/en-us/windows/win32/sysinfo/predefined-keys - Microsoft Learn — registry hives and their backing files. https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-hives
- Lucas Georges — “API set resolution”, on
api-ms-win-*virtual DLLs. https://lucasg.github.io/2017/10/15/Api-set-resolution/ - SANS ISC — “Qiling: A true instrumentable binary emulation framework.” https://isc.sans.edu/diary/27372
- RFC 2606 — Reserved Top Level DNS Names (
.test). https://www.rfc-editor.org/rfc/rfc2606 - MinGW-w64 — the cross-compiler that builds the specimen. https://www.mingw-w64.org/
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.pyimplementsRegCreateKeyExWbut notRegCreateKeyExA,wsock32.pyimplementsgethostbynamebut notgetaddrinfo, andprocess_fcall_paramsinos/os.pystill has noNonehandler. 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 owndocs/DLLX8664.txtstill documents Windows 10 1803 files.