### Emulate Binary with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Demonstrates how to emulate a binary file using Qiling. It involves setting up command-line arguments, the root filesystem path, and potentially a profile file for specific configurations. The `ql.run()` method starts the emulation. ```python from qiling import Qiling from qiling.const import QL_VERBOSE if __name__ == "__main__": # set up command line argv and emulated os root path argv = r'examples/rootfs/netgear_r6220/bin/mini_httpd -d /www -r NETGEAR R6220 -c **.cgi -t 300'.split() rootfs = r'examples/rootfs/netgear_r6220' # instantiate a Qiling object using above arguments and set emulation verbosity level to DEBUG. # additional settings are read from profile file ql = Qiling(argv, rootfs, verbose=QL_VERBOSE.DEBUG, profile='netgear.ql') # map emulated fs '/proc' dir to the hosting os '/proc' dir ql.add_fs_mapper('/proc', '/proc') # do the magic! ql.run() ``` -------------------------------- ### Initialize Qiling for Binary Emulation (Python) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Initializes a Qiling instance for emulating a binary. Requires `argv`, `rootfs`, and optionally `env`. Qiling automatically infers OS and architecture. Using host rootfs is not recommended. ```python from qiling import Qiling ql = Qiling(argv=['./program', 'arg1', 'arg2'], rootfs='/path/to/rootfs', env={'VAR1': 'value1'}) ql.run() ``` -------------------------------- ### Start Qiling Emulation Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Initiates the emulation process. This function can optionally take arguments to control the emulation's start address, end address, timeout duration, and maximum instruction count. ```python ql.run() ``` -------------------------------- ### Python Setup Versioning Example Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/checklist.md Illustrates how to set the version and development status within a Python package's setup.py file. This is crucial for package management and indicating the release stage (e.g., Production/Stable, Beta, development). ```python __version__ = "1.[x].[x]" 'Development Status :: 5 - Production/Stable' ``` ```python 'Development Status :: 3 - Beta' ``` ```python __version__ = "X.X.X" + "-dev" ``` -------------------------------- ### Clone and Install Qiling Framework from GitHub Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Clones the Qiling Framework from its GitHub repository (development branch) and installs it locally using pip. This method is recommended for developers. A virtual environment is advised. ```sh git clone -b dev https://github.com/qilingframework/qiling.git cd qiling git submodule update --init --recursive pip3 install . ``` -------------------------------- ### Install Qiling Framework (Development) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Installs the Qiling Framework from the development branch on GitHub using pip. This provides access to the latest features and bug fixes. A virtual environment is recommended. ```bash python3 -m pip install --user https://github.com/qilingframework/qiling/archive/dev.zip ``` -------------------------------- ### Qiling Framework Command-Line Options Examples Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/qltool.md Illustrates various command-line options for the Qiling Framework's 'qltool' for executing shellcode and binary files. These examples demonstrate specifying operating system, architecture, output format, and input files. ```bash # Shellcode execution examples ./qltool code --os linux --arch arm --format hex -f examples/shellcodes/linarm32_tcp_reverse_shell.hex ./qltool code --os linux --arch x86 --format asm -f examples/shellcodes/lin32_execve.asm # Binary file execution examples ./qltool run -f examples/rootfs/x8664_linux/bin/x8664_hello --rootfs examples/rootfs/x8664_linux/ ./qltool run -f examples/rootfs/mips32el_linux/bin/mips32el_hello --rootfs examples/rootfs/mips32el_linux ``` -------------------------------- ### Run Qiling Docker with Windows Rootfs Bind-Mount Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Starts a Qiling Docker container and binds mount local Windows DLLs and registry hives to the container's rootfs. This is useful for emulating Windows programs within Docker. ```sh docker run -dt --name qiling -v /analysis/win/rootfs/x86_windows:/qiling/examples/rootfs/x86_windows -v /analysis/win/rootfs/x8664_windows:/qiling/examples/rootfs/x8664_windows qilingframework/qiling:latest ``` -------------------------------- ### Python Docstring Example Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/contribution.md Provides a basic example of a Python docstring for a function. Docstrings are crucial for explaining the purpose and functionality of code elements, improving documentation and maintainability. ```python def ql_dumb_function(): """ This is a docstring """ pass ``` -------------------------------- ### Install Qiling Framework (Stable) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Installs the stable release of the Qiling Framework using pip. Ensure a Python virtual environment is activated before running this command. ```bash python3 -m pip install qiling ``` -------------------------------- ### Map Host Path to Emulated Path (Python) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Maps a file path on the host system to a virtual path within the emulated environment using `ql.add_fs_mapper`. This allows the emulated program to access host files or redirect file operations. ```python ql.add_fs_mapper(r'/dev/random', r'/dev/zero') ``` -------------------------------- ### Initialize Qiling for Shellcode Emulation (Python) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Initializes a Qiling instance for emulating shellcode. Requires `code` (bytes), `ostype`, and `archtype`. Optional parameters include `rootfs`, `endian`, and `thumb`. Other common arguments like `cputype`, `verbose`, and `profile` can also be provided. ```python from qiling import Qiling from qiling.const import QL_OS, QL_ARCH shellcode = b'\x90\xeb\xfe' ql = Qiling(code=shellcode, rootfs='/path/to/rootfs', ostype=QL_OS.LINUX, archtype=QL_ARCH.X86) ql.run() ``` -------------------------------- ### Emulate Shellcode with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Shows how to emulate shellcode using Qiling. When emulating shellcode, the architecture and OS type must be explicitly provided as arguments to the Qiling constructor, as they cannot be inferred automatically. The shellcode is provided as a bytes object. ```python from qiling import Qiling from qiling.const import QL_ARCH, QL_OS, QL_VERBOSE # set up a shellcode to emulate shellcode = bytes.fromhex (''' fc4881e4f0ffffffe8d0000000415141505251564831d265488b52603e488b52 183e488b52203e488b72503e480fb74a4a4d31c94831c0ac3c617c022c2041c1 c90d4101c1e2ed5241513e488b52203e8b423c4801d03e8b80880000004885c0 746f4801d0503e8b48183e448b40204901d0e35c48ffc93e418b34884801d64d 31c94831c0ac41c1c90d4101c138e075f13e4c034c24084539d175d6583e448b 40244901d0663e418b0c483e448b401c4901d03e418b04884801d0415841585e 595a41584159415a4883ec204152ffe05841595a3e488b12e949ffffff5d49c7 c1000000003e488d95fe0000003e4c8d850f0100004831c941ba45835607ffd5 4831c941baf0b5a256ffd548656c6c6f2c2066726f6d204d534621004d657373 616765426f7800 ''') # instantiate a Qiling object to emulate the shellcode. when emulating a binary Qiling would be able to automatically # infer the target architecture and operating system. this, however, is not possible when emulating a shellcode, therefore # both 'archtype' and 'ostype' arguments must be provided ql = Qiling(code=shellcode, rootfs=r'examples/rootfs/x8664_windows', archtype=QL_ARCH.X8664, ostype=QL_OS.WINDOWS, verbose=QL_VERBOSE.DEBUG) # do the magic! ql.run() ``` -------------------------------- ### Install Qiling Framework Development Branch with Pip Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/faq.md This command installs the latest development version of the Qiling Framework directly from its GitHub repository using pip. ```shell pip3 install --user https://github.com/qilingframework/qiling/archive/dev.zip ``` -------------------------------- ### Activate Python Virtual Environment (Windows) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Activates the 'qlenv' Python virtual environment on Windows systems. This command should be run from the directory containing the 'qlenv' folder. ```dos qlenv\Scripts\activate ``` -------------------------------- ### Activate Python Virtual Environment (Linux) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Activates the 'qlenv' Python virtual environment on Linux and macOS systems. This command should be run from the directory containing the 'qlenv' folder. ```sh . qlenv/bin/activate ``` -------------------------------- ### Build Keystone Engine from Source on macOS Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md This snippet outlines the process to compile and install the Keystone engine from its source code. It bypasses potential issues with pre-compiled binaries on newer macOS versions by using a manual build process. This method is recommended when standard installation methods fail due to architecture or dependency conflicts. ```shell git clone https://github.com/keystone-engine/keystone cd keystone mkdir build cd build ../make-share.sh cd ../bindings/python sudo make install ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Creates a Python virtual environment named 'qlenv' in the current directory. This isolates Qiling's dependencies from other Python projects. ```sh python3 -m venv qlenv ``` -------------------------------- ### Install Python 3 on Ubuntu/Debian Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Installs Python 3 using the system package manager on Ubuntu or Debian-based Linux distributions. This is a prerequisite for installing Qiling Framework. ```bash sudo apt install python3 ``` -------------------------------- ### Install Qiling Framework with EVM Module Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/evm.md Installs the Qiling Framework, including the EVM module, from its development branch. This involves cloning the repository, checking out the 'dev' branch, updating submodules, and performing an editable installation with the EVM extra dependencies. ```bash git clone https://github.com/qilingframework/qiling.git git checkout dev git submodule update --init pip3 install -e .[evm] ``` -------------------------------- ### Enable and Run Qiling Debugger (Python) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/qdb.md This Python snippet demonstrates how to initialize the Qiling emulator and enable the qdb debugger. It shows different ways to configure the debugger, such as enabling record and replay or setting an initial breakpoint. This code requires the 'qiling' library to be installed and assumes the presence of a rootfs directory. ```python from qiling import Qiling from qiling.const import QL_VERBOSE if __name__ == "__main__": ql = Qiling([r'rootfs/arm_linux/bin/arm_hello'], r'rootfs/arm_linux', verbose=QL_VERBOSE.DEBUG) ql.debugger = "qdb" # enable qdb without options # other possible alternatives: # ql.debugger = "qdb::rr" # switch on record and replay with rr # ql.debugger = "qdb:0x1030c" # enable qdb and setup breakpoin at 0x1030c ql.run() ``` -------------------------------- ### Python Relative Import Example Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/contribution.md Illustrates the use of relative imports within Python modules, which is preferred for internal Qiling modules. It also shows preferred ways to import built-in modules, either on a single line or individually. ```python from .mapper import QlFsMapper # ok import logging, os, re # ok import logging import re import os # no import logging, re import os ``` -------------------------------- ### Collect Windows DLLs and Registry Hives (Local) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Executes a batch script on a Windows system to collect necessary DLL files and registry hives for Qiling Framework emulation. Requires Administrator privileges. ```cmd examples\scripts\dllscollector.bat ``` -------------------------------- ### Pull Qiling Docker Image Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Pulls the latest Qiling Docker image from Docker Hub. This is a convenient way to use Qiling without local installation. ```bash docker pull qilingframework/qiling:latest ``` -------------------------------- ### Disk Emulation with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt Emulate physical disk access for firmware and bootloader analysis. This example shows how to emulate a Petya ransomware bootloader using a raw disk image. ```python from qiling import Qiling from qiling.os.disk import QlDisk # Emulate Petya ransomware bootloader ql = Qiling([r'examples/rootfs/8086_dos/petya/mbr.bin'], r'examples/rootfs/8086_dos') # Create disk emulation # 0x80 = BIOS disk index (first hard drive) emu_path = 0x80 emu_disk = QlDisk(r'examples/rootfs/8086_dos/petya/out_1M.raw', emu_path) # Map disk to emulated BIOS ql.add_fs_mapper(emu_path, emu_disk) # For Linux: use '/dev/sda' # For Windows: use r'\\.\PHYSICALDRIVE0' ql.run() ``` -------------------------------- ### Attach to Running Qiling Docker Container Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/install.md Attaches to a running Qiling Docker container with an interactive bash shell. This allows direct interaction with the Qiling environment inside the container. ```bash docker exec -it qiling bash ``` -------------------------------- ### INI Profile Configuration File for Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt An example INI file (`netgear.ql`) demonstrating how to configure Qiling's emulation environment. This file specifies settings for the MIPS architecture, such as memory mapping address and log directory, as well as network-related configurations like binding to localhost. ```ini [MIPS] mmap_address = 0x7f7ee000 log_dir = qlog log_split = True [NETWORK] bindtolocalhost = yes ``` -------------------------------- ### Hooking UEFI API: SetVariable Example Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/hijack.md Provides an example of hooking a UEFI `SetVariable` API using the `@dxeapi` decorator. This hook intercepts calls to set UEFI variables, reading the variable data and storing it in the Qiling's environment. It specifies parameters like `VariableName`, `VendorGuid`, `Attributes`, `DataSize`, and `Data`. ```python from qiling import Qiling from qiling.os.uefi.const import EFI_SUCCESS from qiling.os.uefi.fncc import * from qiling.os.uefi.ProcessorBind import * @dxeapi(params={ "VariableName" : WSTRING, "VendorGuid" : GUID, "Attributes" : UINT, "DataSize" : UINT, "Data" : POINTER }) def hook_SetVariable(ql: Qiling, address: int, params): data = ql.mem.read(params['Data'], params['DataSize']) ql.env[params['VariableName']] = bytes(data) return EFI_SUCCESS ``` -------------------------------- ### Hijack Standard Streams (stdin/stdout/stderr) with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt Control program input and output streams for automated testing. Examples demonstrate pre-feeding input using SimpleInStream and interactive input using InteractiveInStream. ```python from qiling import Qiling from qiling.extensions import pipe def crackme_solver(ql: Qiling) -> None: """Automatically solve crackme by providing correct input""" # Read expected input from memory or through analysis expected_flag = b'Ea5yR3versing\n' ql.log.info(f'Feeding solution: {expected_flag.decode().strip()}') # Example 1: Pre-feed input with SimpleInStream ql = Qiling([r'examples/rootfs/x86_windows/bin/Easy_CrackMe.exe'], r'examples/rootfs/x86_windows') # Replace stdin with pre-populated stream ql.os.stdin = pipe.SimpleInStream(0) ql.os.stdin.write(b'Ea5yR3versing\n') ql.run() # Example 2: Interactive input with InteractiveInStream ql = Qiling([r'examples/rootfs/x86_linux/bin/crackme_linux'], r'examples/rootfs/x86_linux') # Enable interactive mode (user can type input) ql.os.stdin = pipe.InteractiveInStream() # User will be prompted to type: L1NUX ql.run() ``` -------------------------------- ### Partial Execution of C Code with Sleep Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/snapshot.md A C program that sleeps for 3600 seconds and then prints 'Hello, World!'. This serves as an example for demonstrating snapshotting and partial execution in Qiling. ```c #include #include #include #include void func_hello() { printf("Hello, World!\n"); return; } int main(int argc, const char **argv) { printf("sleep 3600 seconds...\n"); sleep(3600); printf("wake up.\n"); func_hello(); return 0; } ``` -------------------------------- ### Python Type Hinting for Function Signature Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/contribution.md Shows how to use Python's type hinting to define the expected types for function arguments and return values. This enhances code readability and aids in static analysis and autocompletion. ```python def ql_is_multithread(ql: Qiling) -> bool: return ql.multithread ``` -------------------------------- ### Minimum Custom User Script for Qiling IDA Plugin Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/ida.md A basic Python script demonstrating the structure for custom user scripts in the Qiling IDA plugin. It includes placeholders for custom logic during prepare, continue, and step operations. No external dependencies are required beyond the 'qiling' library. ```python from qiling import * class QILING_IDA(): def __init__(self): pass def custom_prepare(self, ql): pass def custom_continue(self, ql:Qiling): hook = [] return hook def custom_step(self, ql:Qiling): hook = [] return hook ``` -------------------------------- ### Snapshot-Based Partial Execution with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt Execute code in stages with snapshots for incremental analysis. This example demonstrates saving a snapshot at a specific execution point and then restoring it to continue execution from that point. ```python from qiling import Qiling from qiling.const import QL_VERBOSE def save_snapshot_at_point(ql: Qiling, *args, **kwargs): """Save snapshot at specific execution point""" ql.log.info('Saving snapshot...') ql.save(reg=False, cpu_context=True, snapshot="/tmp/sleep_snapshot.bin") ql.emu_stop() # Stage 1: Execute until snapshot point ql = Qiling([r'examples/rootfs/x8664_linux/bin/sleep_hello'], r'examples/rootfs/x8664_linux', verbose=QL_VERBOSE.DEFAULT) X64BASE = int(ql.profile.get("OS64", "load_address"), 16) # Hook address where we want to snapshot ql.hook_address(save_snapshot_at_point, X64BASE + 0x1094) ql.run() # Stage 2: Restore from snapshot and continue execution ql = Qiling([r'examples/rootfs/x8664_linux/bin/sleep_hello'], r'examples/rootfs/x8664_linux') # Restore saved state ql.restore(snapshot="/tmp/sleep_snapshot.bin") # Continue from snapshot point ql.run(begin=X64BASE + 0x109e, end=X64BASE + 0x10bc) ``` -------------------------------- ### Python Exception Logging with ql.log.exception Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/contribution.md Demonstrates how to log exceptions using the `ql.log.exception` method in Python. This is useful for capturing detailed error information when an exception occurs, especially during error handling. ```python try: 1/0 except ZeroDivisionError as e: #print(e) ql.log.exception("Divide by zero!") ``` -------------------------------- ### Create Symbolic Link for Qiling IDA Plugin on Linux Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/ida.md Creates a symbolic link for the Qiling IDA plugin file (`qilingida.py`) in the IDA Pro plugins directory on Linux systems. This method ensures that updates to the Qiling framework are automatically reflected in IDA Pro. ```bash # Linux ln -s ~/.local/lib//site-packages/qiling/extensions/idaplugin/qilingida.py /path/to/your/ida/plugins/ ``` -------------------------------- ### Create Symbolic Link for Qiling IDA Plugin on Windows Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/ida.md Creates a symbolic link for the Qiling IDA plugin file (`qilingida.py`) in the IDA Pro plugins directory on Windows systems. This method ensures that updates to the Qiling framework are automatically reflected in IDA Pro. ```bash # Windows mklink C:\absolute\path\to\IDA\plugins\qilingida.py C:\Users\\AppData\Roaming\Python\\site-packages\qiling\extensions\idaplugin\qilingida.py ``` -------------------------------- ### Hooking Windows API: memcpy Example Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/hijack.md Demonstrates how to hook the Windows `memcpy` API using the `@winsdkapi` decorator. This allows for custom handling of memory copying operations, specifying calling conventions and parameter types. The hook reads data from the source to the destination memory addresses. ```python from qiling import Qiling from qiling.os.windows.api import * from qiling.os.windows.fncc import * @winsdkapi(cc=CDECL, params={ 'dest' : POINTER, 'src' : POINTER, 'count' : UINT }) def my_memcpy(ql: Qiling, address: int, params): dest = params['dest'] src = params['src'] count = params['count'] data = bytes(ql.mem.read(src, count)) ql.mem.write(dest, data) return dest ``` -------------------------------- ### Create Symbolic Link for Qiling IDA Plugin on macOS Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/ida.md Creates a symbolic link for the Qiling IDA plugin file (`qilingida.py`) in the IDA Pro plugins directory on macOS systems. This method ensures that updates to the Qiling framework are automatically reflected in IDA Pro. ```bash # Macos ln -s /usr/local/lib//site-packages/qiling/extensions/idaplugin/qilingida.py /Applications//ida.app/Contents/MacOS/plugins/ ``` -------------------------------- ### Patch Emulated Memory (Python) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/howto.md Patches a specified memory address within the emulated environment using `ql.patch`. This is useful for overriding code or data to alter program flow or fix issues during emulation. The example shows patching with a NOP sled for x86. ```python ql.patch(0x401100, b'\x90' * 8) ``` -------------------------------- ### Emulate Netgear Router Firmware with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt This snippet demonstrates basic emulation of Netgear R6220 router firmware using the Qiling framework. It sets up the emulation environment by defining command-line arguments, root filesystem path, and loading profile settings. It also maps the virtual /proc filesystem to the real one and runs the emulated firmware. ```python from qiling import Qiling from qiling.const import QL_VERBOSE argv = r'examples/rootfs/netgear_r6220/bin/mini_httpd -d /www -r "NETGEAR R6220" -c **.cgi -t 300'.split() rootfs = r'examples/rootfs/netgear_r6220' ql = Qiling(argv, rootfs, verbose=QL_VERBOSE.DEBUG, profile='netgear.ql') # Load profile settings # Map /proc to real filesystem ql.add_fs_mapper('/proc', '/proc') ql.run() ``` -------------------------------- ### Python: Initialize Qiling with Custom Profile Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/profile.md This Python code demonstrates how to initialize the Qiling Framework with a custom profile. It defines a function `my_sandbox` that takes the executable path and root filesystem as arguments, instantiates Qiling with a specified profile ('netgear.ql'), adds a filesystem mapper, and runs the emulation. The example usage within the `if __name__ == "__main__":` block shows how to call `my_sandbox` with specific arguments for a Netgear R6220 device. ```python from qiling import * from qiling.const import QL_VERBOSE.DEBUG def my_sandbox(path, rootfs): ql = Qiling(path, rootfs, verbose=QL_VERBOSE.DEBUG, profile= "netgear.ql") ql.add_fs_mapper("/proc", "/proc") ql.run() if __name__ == "__main__": my_sandbox(["rootfs/netgear_r6220/bin/mini_httpd","-d","/www","-r","NETGEAR R6220","-c","**.cgi","-t","300"], "rootfs/netgear_r6220") ``` -------------------------------- ### Filter Qiling Logs with Regular Expressions Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/print.md This snippet illustrates how to filter Qiling log entries using a regular expression assigned to the `ql.filter` attribute. This allows users to focus on specific log messages, such as those starting with a particular pattern. ```python from qiling import Qiling if __name__ == "__main__": ql = Qiling([r'examples/rootfs/arm_linux/bin/arm_hello'], r'examples/rootfs/arm_linux') # show only log entries that start with "open" ql.filter = '^open' ql.run() ``` -------------------------------- ### Emulate UEFI with Qiling Framework Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/demo.md This Python script demonstrates how to emulate UEFI firmware using the Qiling Framework. It sets up an environment with a pre-loaded NVRAM, hooks the RegisterProtocolNotify API to force notifications, and then runs the UEFI binary. Dependencies include Qiling and pickle. ```python import sys import pickle sys.path.append("..") from qiling import * from qiling.os.uefi.const import * def force_notify_RegisterProtocolNotify(ql, address, params): event_id = params['Event'] if event_id in ql.loader.events: ql.loader.events[event_id]['Guid'] = params["Protocol"] # let's force notify event = ql.loader.events[event_id] event["Set"] = True ql.loader.notify_list.append((event_id, event['NotifyFunction'], event['NotifyContext'])) ###### return EFI_SUCCESS return EFI_INVALID_PARAMETER if __name__ == "__main__": with open("rootfs/x8664_efi/rom2_nvar.pickel", 'rb') as f: env = pickle.load(f) ql = Qiling(["rootfs/x8664_efi/bin/TcgPlatformSetupPolicy"], "rootfs/x8664_efi", env=env) ql.os.set_api("hook_RegisterProtocolNotify", force_notify_RegisterProtocolNotify) ql.run() ``` -------------------------------- ### Get Qiling Object Reference in IDAPython Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/ida.md This snippet shows how to obtain references to the Qiling plugin, emulator, and the core Qiling object within the IDAPython output window after the plugin has been set up. This allows for manual control and interaction with the Qiling environment. ```python ql_plugin = ida_ida.ql_plugin qlemu = ql_plugin.qlemu ql = qlemu.ql ``` -------------------------------- ### Initialize Qiling for Binary Emulation Source: https://context7.com/qilingframework/rtfd.io/llms.txt Initializes the Qiling framework for emulating an executable binary. It supports automatic OS and architecture detection and allows configuration of arguments, rootfs, environment variables, verbosity, profile, and multithreading. The function takes the binary path and optional arguments as input. ```python from qiling import Qiling from qiling.const import QL_VERBOSE # Initialize Qiling for binary emulation ql = Qiling( argv=[r'examples/rootfs/x8664_linux/bin/x8664_hello', 'arg1', 'arg2'], rootfs=r'examples/rootfs/x8664_linux', env={'PATH': '/bin:/usr/bin', 'HOME': '/root'}, # optional environment variables verbose=QL_VERBOSE.DEBUG, profile='custom.ql', # optional profile configuration file multithread=True # enable multithreading support ) # Execute the emulation ql.run() ``` -------------------------------- ### Python Property Implementation for Class Members Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/contribution.md Illustrates the use of Python's `@property` decorator to implement class members, offering a more readable and maintainable approach compared to direct attribute access. It includes an example of initializing a private attribute and exposing it via a public property. ```python class QlOsDumb: def __init__(self): #self.dumb = 1 self._dumb = 1 @property def dumb(self): return self._dumb def do_something(self): print(self.dumb) ``` -------------------------------- ### qltool CLI Commands for Binary Emulation Source: https://context7.com/qilingframework/rtfd.io/llms.txt A collection of bash commands demonstrating the usage of the `qltool` command-line interface for emulating binaries. It covers executing binaries with arguments, verbose disassembly, GDB debugging, shellcode execution (hex and assembly), code coverage, timeouts, environment variables, multithreading, and launching the interactive TUI. ```bash # Execute binary with arguments $ ./qltool run -f examples/rootfs/x8664_linux/bin/x8664_hello \ --rootfs examples/rootfs/x8664_linux \ --args arg1 arg2 arg3 # Alternative syntax (implicit filename and args) $ ./qltool run --rootfs examples/rootfs/x8664_linux \ examples/rootfs/x8664_linux/bin/x8664_hello arg1 arg2 # Execute with verbose disassembly $ ./qltool run -f examples/rootfs/mips32el_linux/bin/mips32el_hello \ --rootfs examples/rootfs/mips32el_linux \ --verbose disasm # Enable GDB debugging $ ./qltool run -f examples/rootfs/x8664_linux/bin/x8664_hello \ --rootfs examples/rootfs/x8664_linux \ --gdb 127.0.0.1:9999 # Execute shellcode from hex string $ ./qltool code --os linux --arch x86 --format hex \ --input "31c050682f2f7368682f62696e89e3505389e131d2b00bcd80" # Execute shellcode from assembly file $ ./qltool code --os linux --arch arm --format asm \ -f examples/shellcodes/linarm32_tcp_reverse_shell.asm # Execute with code coverage $ ./qltool run -f binary --rootfs rootfs \ --coverage-file output.cov --coverage-format drcov # Execute with timeout $ ./qltool run -f binary --rootfs rootfs --timeout 10000000 # Execute with custom environment variables $ ./qltool run -f binary --rootfs rootfs \ --env '{"LD_PRELOAD":"hijack.so", "DEBUG":"1"}' # Execute with multithread support $ ./qltool run -f binary --rootfs rootfs --multithread # Launch interactive TUI (Terminal User Interface) $ ./qltool qltui ``` -------------------------------- ### Clone and Checkout Development Branch with Git Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/faq.md This snippet shows how to clone the Qiling Framework repository and switch to the development branch for testing or contributing. ```shell git clone https://github.com/qilingframework/qiling.git git checkout dev ``` -------------------------------- ### Configure Qiling Logging Verbosity Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/print.md This example shows how to set the verbosity level for Qiling's logging. The `verbose` parameter can be set using constants from `qiling.const.QL_VERBOSE` to control the amount of log output, from disabled to debug and disassembly. ```python from qiling.const import QL_VERBOSE ql = Qiling([r'/bin/ls'], r'examples/rootfs/x86_linux', verbose=QL_VERBOSE.DEBUG) ``` -------------------------------- ### Python Fuzzing Integration with AFL++ in Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt This Python script integrates Qiling with AFL++ for coverage-guided fuzzing. It sets up Qiling to receive input from AFL, places the input into the emulated environment (e.g., stdin), and starts the fuzzing loop. It also includes hooks for crash conditions and the AFL fuzzing start. ```python import sys import os from qiling import Qiling from qiling.const import QL_VERBOSE from qiling.extensions import pipe, afl def main(input_file: str): # Initialize Qiling with minimal verbosity for speed ql = Qiling(["./target_binary"], "rootfs", verbose=QL_VERBOSE.OFF, console=False) # Setup stdin for AFL input ql.os.stdin = pipe.SimpleInStream(sys.stdin.fileno()) def place_input_callback(ql: Qiling, input_data: bytes, persistent_round: int) -> bool: """Called by AFL to place input for each iteration""" # Write fuzzer input to stdin ql.os.stdin.write(input_data) # Can also write to specific memory location: # ql.mem.write(0x1000, input_data) return True def start_afl_fuzzing(ql: Qiling): """Start AFL fuzzing loop""" afl.ql_afl_fuzz( ql, input_file=input_file, place_input_callback=place_input_callback, exits=[ql.os.exit_point] ) # Get base address base_address = ql.loader.images[0].base # Hook crash condition to abort ql.hook_address(lambda x: os.abort(), base_address + 0x1225) # Start AFL at target function ql.hook_address(start_afl_fuzzing, base_address + 0x122c) ql.run() if __name__ == "__main__": main(sys.argv[1] if len(sys.argv) > 1 else "@@") ``` -------------------------------- ### Bash Commands for AFL++ Fuzzing with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt This snippet provides the bash commands required to compile an AFL target wrapper and run the AFL fuzzer. It demonstrates how to set up the fuzzing environment, specifying input and output directories, and the target executable. ```bash # Compile AFL target wrapper # afl-clang-fast wrapper.c -o fuzzer # Run AFL fuzzer $ afl-fuzz -i input_dir -o output_dir -- ./fuzzer @@ ``` -------------------------------- ### Update PyPI Package Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/checklist.md Command to upgrade the Qiling package on PyPI using pip3. This ensures that users have the latest version of the framework installed. ```bash pip3 install qiling --upgrade ``` -------------------------------- ### Hook Interrupts (Generic) Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/hook.md A generic hook for handling interrupts. The specific interrupt type or number is not specified in this example, implying it might catch all or a default set. ```python ql.hook_intr() ``` -------------------------------- ### Execute EVM Smart Contract Bytecode with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/evm.md Demonstrates how to execute EVM smart contract bytecode using the Qiling Framework in Python. It shows how to initialize Qiling for EVM, prepare contract bytecode with optional parameters, create user and contract accounts, construct a transaction message, and run the execution. Dependencies include the 'qiling' library. ```python import sys from qiling import * if __name__ == '__main__': ql = Qiling(archtype="evm") contract = "0x60606040..." # Smart Contract Bytecode bal = ql.arch.evm.abi.convert(['uint256'], [20]) contract = contract + bal # add Bytecode init parameters(Optional) user1 = ql.arch.evm.create_account(balance=100*10**18) # Creating a user account with 100 ETH c1 = ql.arch.evm.create_account() # Creating a contract account call_data = '0x...' # Function Sign and parameters msg1 = ql.arch.evm.create_message(user1, c1, call_data) # Creating a transaction message result = ql.run(code=msg1) # Running this transaction ``` -------------------------------- ### GDB Remote Debugging with Qiling Source: https://context7.com/qilingframework/rtfd.io/llms.txt Enable GDB server for interactive debugging with GDB or IDA Pro. The example shows how to enable the GDB server and provides commands to connect to it. ```python from qiling import Qiling from qiling.const import QL_VERBOSE ql = Qiling([r'examples/rootfs/x8664_linux/bin/x8664_hello'], r'examples/rootfs/x8664_linux', verbose=QL_VERBOSE.OFF) # Enable GDB server (defaults to localhost:9999) ql.debugger = True # Custom address and port configurations # ql.debugger = ":9999" # listen on 0.0.0.0:9999 # ql.debugger = "127.0.0.1:9999" # listen on localhost:9999 # ql.debugger = "gdb:127.0.0.1:9999" # GDB server # ql.debugger = "idapro:127.0.0.1:9999" # IDA Pro server # Emulation will pause at entry point waiting for debugger connection ql.run() ``` ```bash # Start GDB $ gdb # Set architecture (gdb) set architecture i386:x86-64 # Connect to Qiling (gdb) target remote localhost:9999 ``` -------------------------------- ### Trace All Instructions with Capstone Disassembly Source: https://context7.com/qilingframework/rtfd.io/llms.txt Hooks every instruction executed during emulation and uses Capstone to disassemble and log each instruction. This is useful for detailed code tracing and analysis. ```python from capstone import Cs from qiling import Qiling from qiling.const import QL_VERBOSE def instruction_tracer(ql: Qiling, address: int, size: int, md: Cs) -> None: """Trace and disassemble each instruction""" buf = ql.mem.read(address, size) for insn in md.disasm(buf, address): ql.log.debug(f':: {insn.address:#010x} : {insn.mnemonic:24s} {insn.op_str}') # Initialize Qiling ql = Qiling([r'examples/rootfs/x8664_linux/bin/x8664_hello'], r'examples/rootfs/x8664_linux', verbose=QL_VERBOSE.DEBUG) # Hook all instructions with Capstone disassembler ql.hook_code(instruction_tracer, user_data=ql.arch.disassembler) ql.run() ``` -------------------------------- ### Emulate Windows Registry with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/demo.md This Python script demonstrates emulating the Windows registry using Qiling Framework. It initializes Qiling with debug verbosity to capture detailed information during the emulation of a registry-related executable. This is helpful for understanding or manipulating Windows registry behavior. ```python from qiling import Qiling from qiling.const import QL_VERBOSE # a simple emulatation sandbox def sandbox(path: str, rootfs: str) -> None: # initialize qiling and set it to debug verbosity ql = Qiling([path], rootfs, verbose=QL_VERBOSE.DEBUG) # do the magic! ql.run() if __name__ == '__main__': sandbox(r'rootfs/x86_windows/bin/RegDemo.exe', r'rootfs/x86_windows') ``` -------------------------------- ### Python Script to Load Qiling Profile Configuration Source: https://context7.com/qilingframework/rtfd.io/llms.txt This Python snippet shows how to load a Qiling profile configuration file within a script. It imports the necessary Qiling classes and uses them to initialize the emulator, presumably applying the settings defined in the profile file. ```python from qiling import Qiling from qiling.const import QL_VERBOSE ``` -------------------------------- ### Print Log Messages with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/print.md This snippet demonstrates how to print informational log messages using the Qiling instance's log attribute. It utilizes the standard Python logging levels. ```python ql.log.info('Hello from Qiling Framework!') ``` -------------------------------- ### Emulating Netgear R6220 with Qiling Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/demo.md This Python script demonstrates how to emulate a Netgear R6220 router using the Qiling Framework. It involves setting up a custom syscall handler for `write` and configuring Qiling with specific rootfs paths and profile settings. This is useful for analyzing or interacting with the device's firmware. ```python import sys sys.path.append("..") from qiling import * from qiling.os.posix import syscall from qiling.const import QL_VERBOSE def my_syscall_write(ql, write_fd, write_buf, write_count, *rest): if write_fd == 2 and ql.os.file_des[2].__class__.__name__ == 'ql_pipe': ql.os.definesyscall_return(-1) else: syscall.ql_syscall_write(ql, write_fd, write_buf, write_count, *rest) def my_netgear(path, rootfs): ql = Qiling( path, rootfs, verbose = QL_VERBOSE.DEBUG, profile = "netgear_6220.ql" ) ql.root = False ql.bindtolocalhost = True ql.multithread = False ql.add_fs_mapper('/proc', '/proc') ql.os.set_syscall(4004, my_syscall_write) ql.run() if __name__ == "__main__": my_netgear(["rootfs/netgear_r6220/bin/mini_httpd", "-d","/www", "-r","NETGEAR R6220", "-c","**.cgi", "-t","300"], "rootfs/netgear_r6220") ``` -------------------------------- ### Saving and Restoring Register State with EIP Modification Source: https://github.com/qilingframework/rtfd.io/blob/master/docs/snapshot.md Explains how to save all CPU registers, modify the instruction pointer (EIP), and then restore the registers. This allows for controlled manipulation of execution flow by setting a new starting point. ```python all_registers = ql.arch.regs.save() all_registers["eip"] = 0xaabbccdd ``` ```python ql.arch.regs.restore(all_registers) ```