#!/usr/bin/env python3
"""Emulate specimen.exe under Qiling and count the behaviors it exhibits.

Ground truth, from windows_dynamic.md, is three behaviors: a Run-key write,
a file drop, and a C2 name lookup.

Both modes install the same two passive observers, on CreateFileA and
WriteFile, so the counter is measuring the same thing either way. --naive
stops there and reports what Qiling's own API coverage can see: one of the
three. Without it, two replacement hooks fill the gaps and all three become
observable.

    ./qiling_specimen.py --naive ~/qiling/rootfs/x8664_windows
    ./qiling_specimen.py         ~/qiling/rootfs/x8664_windows

Written against Qiling 1.4.6. The two API gaps this works around are still
present on qiling master as of October 2026.
"""

import sys

from qiling import Qiling
from qiling.const import QL_VERBOSE, QL_INTERCEPT
from qiling.os.windows.api import *
from qiling.os.windows.const import *
from qiling.os.windows.fncc import *
from qiling.os.windows.handle import Handle

naive = "--naive" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("--")]
rootfs = args[0] if args else "rootfs/x8664_windows"

behaviors = []


@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):
    """advapi32!RegCreateKeyExA -- the ANSI twin Qiling does not ship.

    Qiling implements RegCreateKeyExW but not ...ExA, so an ANSI dropper
    walks past the emulator and into the real advapi32 code, where it dies
    in a pile of unimplemented ntdll calls.

    lpClass and lpSecurityAttributes are declared POINTER rather than LPSTR
    and LPSECURITY_ATTRIBUTES on purpose: both are NULL here, a NULL string
    resolves to None, and Qiling's own argument logging has no handler for
    None -- so the correct SDK types crash the emulator before this function
    is even entered.
    """
    # 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


@winsdkapi(cc=STDCALL, params={
    'pNodeName'    : POINTER,
    'pServiceName' : POINTER,
    'pHints'       : POINTER,
    'ppResult'     : POINTER
})
def hook_getaddrinfo(ql: Qiling, address: int, params):
    """ws2_32!getaddrinfo -- Qiling implements only gethostbyname."""
    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


# Qiling's CreateFileA does open a real file under the rootfs, but the handle
# it returns carries no name, so WriteFile alone cannot say what was written
# to. Remember the mapping on the way out of CreateFileA.
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}")


ql = Qiling(["specimen.exe"], rootfs,
            verbose=QL_VERBOSE.DEFAULT if naive else QL_VERBOSE.OFF)

# Passive observers on APIs Qiling already implements. These are installed in
# both modes, so the two runs are counting the same way.
ql.os.set_api('CreateFileA', on_createfile, QL_INTERCEPT.EXIT)
ql.os.set_api('WriteFile', on_writefile, QL_INTERCEPT.ENTER)

# Replacements for the two APIs Qiling has no implementation for. Without
# these the Run key and the C2 host are simply not in the trace.
if not naive:
    ql.os.set_api('RegCreateKeyExA', hook_RegCreateKeyExA)
    ql.os.set_api('getaddrinfo', hook_getaddrinfo)

ql.run()

print(f"\n{len(behaviors)} of 3 behaviors observed:")
for b in behaviors:
    print(f"  * {b}")
