### GUID Usage Examples Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/types.md Demonstrates how to define well-known GUIDs and how to create a GUID from a string using RtlStringFromGUID. ```c // Well-known GUIDs GUID UEFI_GLOBAL_VARIABLE_GUID = { 0x8be4df61, 0x93ca, 0x11d2, {0xaa, 0x0d, 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c} }; // Create GUID from string GUID MyGuid; RtlStringFromGUID(&MyGuid, &GuidString); ``` -------------------------------- ### User-Mode Application Example (C++) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md A C++ example demonstrating how to open a file using Veil's Native API functions like NtOpenFile and NtClose. Ensure Veil headers and ntdll.lib are correctly configured. ```cpp #include "Veil.h" #include int main() { HANDLE ProcessHandle; OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING ProcessName = RTL_CONSTANT_STRING(L"\\??\\C:\\Windows\\notepad.exe"); InitializeObjectAttributes(&ObjectAttributes, &ProcessName, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS Status = NtOpenFile(&ProcessHandle, FILE_GENERIC_READ, &ObjectAttributes, NULL, FILE_SHARE_READ, 0); if (NT_SUCCESS(Status)) { printf("Successfully opened file\n"); NtClose(ProcessHandle); } return 0; } ``` -------------------------------- ### Object Attributes Initialization Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/types.md Provides an example of how to initialize an OBJECT_ATTRIBUTES structure using the InitializeObjectAttributes function. ```c OBJECT_ATTRIBUTES ObjectAttrs; InitializeObjectAttributes(&ObjectAttrs, &ObjectName, OBJ_CASE_INSENSITIVE, RootDirectory, SecurityDescriptor); ``` -------------------------------- ### Kernel-Mode Driver Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md A C example for a kernel-mode driver using Veil. It includes the main Veil header and wdm.h. Kernel-mode specific functions like KdPrint and ExAllocatePoolWithTag can be used. ```c #include "Veil.h" #include // Kernel-mode code here // Use with KdPrint, ExAllocatePoolWithTag, etc. ``` -------------------------------- ### Usage Example for KeGetCurrentIrql Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Demonstrates how to use KeGetCurrentIrql to check the current IRQL and perform operations safely based on the level. ```c KIRQL CurrentIrql = KeGetCurrentIrql(); if (CurrentIrql < DISPATCH_LEVEL) { // Safe to perform certain operations } ``` -------------------------------- ### APC Queuing Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Demonstrates how to initialize and queue an Asynchronous Procedure Call (APC) for execution in a target thread. ```APIDOC ## Pattern 1: Creating and Queuing an APC ### Description This pattern shows the process of initializing a kernel APC structure and then queuing it for execution on a specified thread. It involves setting up the APC with necessary routines and context, and then using `KeInsertQueueApc` to schedule its execution. ### Usage ```c // Initialize APC KAPC Apc; KeInitializeApc(&Apc, TargetThread, CurrentApcEnvironment, KernelRoutine, NULL, NormalRoutine, UserMode, NormalContext); // Queue for execution if (KeInsertQueueApc(&Apc, Arg1, Arg2, 0)) { // APC queued successfully } ``` ### Parameters - `Apc`: A pointer to a `KAPC` structure to be initialized. - `TargetThread`: A pointer to the thread on which the APC will be queued. - `CurrentApcEnvironment`: The APC environment (Kernel or User). - `KernelRoutine`: A pointer to the kernel-mode APC routine. - `NormalRoutine`: A pointer to the user-mode APC routine. - `NormalContext`: A pointer to the context to be passed to the normal routine. - `Arg1`, `Arg2`: Arguments to be passed to the APC routines. ### Return Value `KeInsertQueueApc` returns `TRUE` if the APC was successfully queued, and `FALSE` otherwise. ``` -------------------------------- ### Object Access Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/object-manager.md Demonstrates how to set desired access rights for an object and check granted access. This is typically used when opening or creating kernel objects. ```c // Open object with read and synchronize access ULONG DesiredAccess = GENERIC_READ | SYNCHRONIZE; // Check if specific access is available if (GrantedAccess & READ_CONTROL) { // Can read object security information } ``` -------------------------------- ### Create and Queue APC Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Demonstrates the initialization and queuing of an Asynchronous Procedure Call (APC) to a target thread. Ensure the APC environment and routines are correctly set. ```c // Initialize APC KAPC Apc; KeInitializeApc(&Apc, TargetThread, CurrentApcEnvironment, KernelRoutine, NULL, NormalRoutine, UserMode, NormalContext); // Queue for execution if (KeInsertQueueApc(&Apc, Arg1, Arg2, 0)) { // APC queued successfully } ``` -------------------------------- ### Install Musa.Veil via NuGet Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Installs the Musa.Veil package using the NuGet Package Manager. This is the recommended integration method. ```powershell Install-Package Musa.Veil ``` -------------------------------- ### NtCallbackReturn Usage Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Demonstrates how to use NtCallbackReturn to return control to user-mode with a success status. Ensure proper buffer allocation and size management. ```c PVOID OutputBuffer = malloc(256); ULONG OutputLength = 256; NTSTATUS Status = NtCallbackReturn(OutputBuffer, OutputLength, STATUS_SUCCESS); if (NT_SUCCESS(Status)) { // Callback return succeeded } ``` -------------------------------- ### UEFI Variable Attributes Usage Patterns Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/executive-functions.md Demonstrates how to combine UEFI variable attribute flags for different storage and access requirements. Includes an example of checking for specific attributes. ```c // Variable accessible at runtime but stored in volatile memory ULONG Attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS; // Persistent UEFI variable with authentication ULONG Attributes = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS; // Check specific attributes if (Attributes & EFI_VARIABLE_NON_VOLATILE) { // Variable is persistent } ``` -------------------------------- ### Set Memory Protection Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Example of setting memory protection flags using NtProtectVirtualMemory. Demonstrates setting pages to be executable and readable but not writable. ```c // Make memory executable and readable but not writable DWORD Protect = PAGE_EXECUTE_READ; NtProtectVirtualMemory(ProcessHandle, &BaseAddress, &Size, Protect, &OldProtect); ``` -------------------------------- ### Integrate Musa.Veil with CMake FetchContent Source: https://github.com/mirokaku/musa.veil/blob/main/README.md Fetch and integrate Musa.Veil into your project using CMake's FetchContent module. This example shows how to declare, make available, and link the library. ```cmake include(FetchContent) FetchContent_Declare( Musa.Veil GIT_REPOSITORY https://github.com/MiroKaku/Musa.Veil.git GIT_TAG main GIT_SHALLOW TRUE ) FetchContent_MakeAvailable(Musa.Veil) add_library(Musa.Veil INTERFACE) target_include_directories(Musa.Veil INTERFACE "${musa.veil_SOURCE_DIR}") # Link to your target target_link_libraries(YourTarget PRIVATE Musa.Veil) ``` -------------------------------- ### Query and Set Debug Filter State Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Shows how to query the current debug filter state and subsequently set it using NtQueryDebugFilterState and NtSetDebugFilterState. Requires appropriate privileges. ```c NTSTATUS Status = NtQueryDebugFilterState(DPFLTR_SYSTEM_ID, DPFLTR_ERROR_LEVEL); if (NT_SUCCESS(Status)) { // Check current debug filter state } // Change debug filter Status = NtSetDebugFilterState(DPFLTR_SYSTEM_ID, DPFLTR_ERROR_LEVEL, TRUE); ``` -------------------------------- ### Include Musa.Veil Header Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Includes the main header file for Musa.Veil after installation. This makes library definitions available. ```c #include "Veil.h" ``` -------------------------------- ### NtYieldExecution Usage Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Shows how to call NtYieldExecution to yield the current thread's execution time. The function returns STATUS_SUCCESS on successful yielding. ```c NTSTATUS Status = NtYieldExecution(); if (NT_SUCCESS(Status)) { // Thread has yielded execution } ``` -------------------------------- ### Debug Filter State Management Example Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Illustrates how to query and set the debug filter state using NtQueryDebugFilterState and NtSetDebugFilterState. ```APIDOC ## Pattern 2: Handling Debug Filter State ### Description This pattern shows how to interact with the system's debug filter state. It includes querying the current state of a specific debug filter and setting a new state (enable/disable). ### Usage ```c // Query current debug filter state NTSTATUS Status = NtQueryDebugFilterState(DPFLTR_SYSTEM_ID, DPFLTR_ERROR_LEVEL); if (NT_SUCCESS(Status)) { // Check current debug filter state } // Change debug filter state Status = NtSetDebugFilterState(DPFLTR_SYSTEM_ID, DPFLTR_ERROR_LEVEL, TRUE); ``` ### Functions - `NtQueryDebugFilterState`: Retrieves the current state of a debug filter. - `NtSetDebugFilterState`: Sets the state (enabled/disabled) of a debug filter. ### Parameters for `NtQueryDebugFilterState` and `NtSetDebugFilterState` - `DPFLTR_SYSTEM_ID`: Identifier for the debug filter component. - `DPFLTR_ERROR_LEVEL`: The specific debug filter level to query or set. - `TRUE`/`FALSE` (for `NtSetDebugFilterState`): Boolean value indicating whether to enable (`TRUE`) or disable (`FALSE`) the filter. ### Return Value Both functions return an `NTSTATUS` code. `NT_SUCCESS(Status)` can be used to check if the operation was successful. ``` -------------------------------- ### Compilation Command for User-Mode Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Example command for compiling a C program in user-mode using cl.exe. It specifies warning levels, error checking, include paths, and links against 'ntdll.lib'. ```batch cl /W4 /WX /I "path\to\veil" myprogram.c ntdll.lib ``` -------------------------------- ### Allocate Memory with Guard Page Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Example of allocating memory with the PAGE_GUARD flag using NtAllocateVirtualMemory. This is useful for detecting stack overflows. ```c // Guard page for stack overflow detection DWORD GuardProtect = PAGE_READWRITE | PAGE_GUARD; NtAllocateVirtualMemory(ProcessHandle, &BaseAddress, 0, &Size, MEM_COMMIT, GuardProtect, NULL); ``` -------------------------------- ### Query UEFI System Environment Variable Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Queries a UEFI system environment variable by name and vendor GUID. Checks for non-volatile attributes. ```c // Query UEFI variable UNICODE_STRING VarName; RtlInitUnicodeString(&VarName, L"BootOrder"); GUID VendorGuid = UEFI_GLOBAL_VARIABLE_GUID; UCHAR Buffer[256]; ULONG BufferSize = sizeof(Buffer); ULONG Attributes = 0; NTSTATUS Status = NtQuerySystemEnvironmentValueEx( &VarName, &VendorGuid, Buffer, &BufferSize, &Attributes); if (NT_SUCCESS(Status)) { // Check variable attributes if (Attributes & EFI_VARIABLE_NON_VOLATILE) { // Variable persists across reboots } } ``` -------------------------------- ### Essential Includes and Macros Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Includes the main Veil header and provides macros for checking NT status, getting containing structures, initializing object attributes, initializing wide strings, and alignment checks. ```c #include "Veil.h" // Include all definitions // Check for success if (NT_SUCCESS(Status)) { /* ... */ } // Get containing structure from member PLDR_DATA_TABLE_ENTRY Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); // Initialize object attributes OBJECT_ATTRIBUTES ObjectAttrs; InitializeObjectAttributes(&ObjectAttrs, &ObjectName, OBJ_CASE_INSENSITIVE, NULL, NULL); // Initialize wide-string UNICODE_STRING String = RTL_CONSTANT_STRING(L"\Device\Harddisk0"); // Alignment macros if (IS_ALIGNED(Pointer, 4096)) { /* ... */ } ULONG AlignedSize = ROUND_TO_SIZE(Size, 4096); ``` -------------------------------- ### PS_POST_PROCESS_INIT_ROUTINE Function Pointer Type Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/process-management.md Defines a function pointer type for callbacks executed after process initialization. Use this to register custom setup routines. ```c typedef _Function_class_(PS_POST_PROCESS_INIT_ROUTINE) VOID NTAPI PS_POST_PROCESS_INIT_ROUTINE(VOID); typedef PS_POST_PROCESS_INIT_ROUTINE* PPS_POST_PROCESS_INIT_ROUTINE; ``` -------------------------------- ### Combining Memory Protection Flags Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Illustrates how to combine standard Windows memory protection flags to define specific access rights and behaviors for memory regions. For example, combining read, execute, and guard page attributes. ```c // Read and execute, with guard page DWORD Protection = PAGE_EXECUTE_READ | PAGE_GUARD; // Copy-on-write execution DWORD Protection = PAGE_EXECUTE_WRITECOPY; ``` -------------------------------- ### GUID Structure Definition Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/types.md Defines the Globally Unique Identifier (GUID) structure. Also includes a type alias for a constant GUID pointer. ```c typedef struct _GUID { ULONG Data1; USHORT Data2; USHORT Data3; UCHAR Data4[8]; } GUID, * PGUID; typedef const GUID* LPCGUID; ``` -------------------------------- ### Get Thread Information Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Retrieves basic information about a thread using NtQueryInformationThread with ThreadBasicInformation class. ```c THREAD_BASIC_INFORMATION ThreadInfo; ULONG ReturnLength; NTSTATUS Status = NtQueryInformationThread( ThreadHandle, ThreadBasicInformation, &ThreadInfo, sizeof(ThreadInfo), &ReturnLength ); ``` -------------------------------- ### Change Memory Protection (C) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Demonstrates how to make memory executable and then restore its original protection using NtProtectVirtualMemory. Ensure BaseAddress and Size are correctly defined before use. ```c // Make memory executable DWORD OldProtect; NtProtectVirtualMemory(NtCurrentProcess(), &BaseAddress, &Size, PAGE_EXECUTE_READWRITE, &OldProtect); // Restore original protection NtProtectVirtualMemory(NtCurrentProcess(), &BaseAddress, &Size, OldProtect, NULL); ``` -------------------------------- ### Get System Time Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Retrieves the current system time in UTC using NtQuerySystemTime. Can be converted to a readable format. ```c LARGE_INTEGER SystemTime; NtQuerySystemTime(&SystemTime); // Convert to readable format SYSTEMTIME ReadableTime; RtlTimeToSecondsSince1970(&SystemTime, NULL); ``` -------------------------------- ### Verify Include Path for Veil.h Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Troubleshoot 'Cannot open include file: 'Veil.h'' errors by verifying the include path. Use the 'dir' command to check if the file exists at the specified location. ```batch # Check file exists dir C:\Path\To\Veil\Veil.h ``` -------------------------------- ### Generate x64 Import Library using lib Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md Command to generate the x64 import library (.lib) using the lib utility and a .def file. Specify the machine type as x64. ```bash lib /def:CI.def /machine:x64 /out:ci.lib ``` -------------------------------- ### Querying Basic Memory Information Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Demonstrates how to use NtQueryVirtualMemory to retrieve basic memory information for a given address. Ensure the necessary structures and constants are included. ```c // Query basic memory information MEMORY_BASIC_INFORMATION MemInfo = {0}; SIZE_T ReturnLength = 0; NTSTATUS Status = NtQueryVirtualMemory( NtCurrentProcess(), BaseAddress, MemoryBasicInformation, &MemInfo, sizeof(MEMORY_BASIC_INFORMATION), &ReturnLength ); if (NT_SUCCESS(Status)) { // MemInfo.BaseAddress, MemInfo.RegionSize, MemInfo.Protect, MemInfo.Type } ``` -------------------------------- ### Release Virtual Memory Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Frees a region of virtual memory. Set RegionSize to 0 to release the entire region starting from BaseAddress. ```c SIZE_T RegionSize = 0; // Entire region NTSTATUS Status = NtFreeVirtualMemory( ProcessHandle, &BaseAddress, &RegionSize, MEM_RELEASE ); ``` -------------------------------- ### Allocate and Commit Memory Pattern Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md Demonstrates a common pattern for memory management: first reserving a range of virtual address space, then committing physical pages as needed. This allows for efficient memory usage. ```c // Reserve address space SIZE_T Size = 1024 * 1024; // 1MB PVOID BaseAddress = NULL; NtAllocateVirtualMemory(NtCurrentProcess(), &BaseAddress, 0, &Size, MEM_RESERVE, PAGE_NOACCESS, NULL); // Commit pages as needed SIZE_T CommitSize = 4096; PVOID CommitAddr = BaseAddress; NtAllocateVirtualMemory(NtCurrentProcess(), &CommitAddr, 0, &CommitSize, MEM_COMMIT, PAGE_READWRITE, NULL); ``` -------------------------------- ### Generate AMD64 Import Library using lib Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md Command to generate the AMD64 import library (.lib) using the lib utility and a .def file. Specify the machine type as AMD64. ```bash lib /def:CI.def /machine:AMD64 /out:ci.lib ``` -------------------------------- ### Add Musa.Veil NuGet Package to .vcxproj (Mile.Project.Windows) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Use this XML snippet to add the Musa.Veil NuGet package to a .vcxproj file when using the Mile.Project.Windows template. ```xml 1.0.0 ``` -------------------------------- ### Include Veil.h for User-Mode APIs (Default) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Include Veil.h directly to access user-mode APIs. This is the default behavior. ```c #include "Veil.h" // User-mode APIs available ``` -------------------------------- ### Get Current IRQL Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/kernel-core-functions.md Retrieves the current interrupt request level (IRQL). This function is only defined for AMD64 architecture and uses the CR8 register on x64 systems. ```c _IRQL_requires_max_(HIGH_LEVEL) _IRQL_saves_ inline KIRQL _VEIL_IMPL_KeGetCurrentIrql(VOID); ``` -------------------------------- ### Open a File Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Opens a file for reading using NtOpenFile. Ensure proper initialization of OBJECT_ATTRIBUTES and IO_STATUS_BLOCK. ```c HANDLE FileHandle; OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatusBlock; UNICODE_STRING FileName = RTL_CONSTANT_STRING(L"\??\C:\Windows\notepad.exe"); InitializeObjectAttributes(&ObjectAttributes, &FileName, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS Status = NtOpenFile( &FileHandle, FILE_GENERIC_READ, // Desired access &ObjectAttributes, &IoStatusBlock, FILE_SHARE_READ, // Share access FILE_SEQUENTIAL_ONLY // Open options ); ``` -------------------------------- ### Handle Specific NTSTATUS Codes Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Handles specific NTSTATUS error codes to provide differentiated error handling. Examples include access denied and object not found. ```c else if (Status == STATUS_ACCESS_DENIED) { // Insufficient privileges } else if (Status == STATUS_OBJECT_NAME_NOT_FOUND) { // Object not found } ``` -------------------------------- ### Loader and Modules API Reference Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/MANIFEST.txt Documentation on module loading, PE headers, relocation, and enumeration patterns in Musa.Veil. ```APIDOC ## api-reference/loader-and-modules.md ### Description Details module loading, Portable Executable (PE) headers, relocation, and enumeration patterns. ### Topics Covered - Module Loading - PE Headers - Relocation - Enumeration Patterns ``` -------------------------------- ### Generate 32-bit Import Library using lib Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md Command to generate the 32-bit import library (.lib) using the lib utility, a .def file, and the compiled OBJ file. Specify the machine type as x86. ```bat > lib /def:CI.def /machine:x86 /out:ci.lib CI.Stub.obj ``` -------------------------------- ### Compile User Application with Visual Studio Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Compile a C++ user-mode application using cl.exe from the Visual Studio Developer Command Prompt. Includes Veil's include path and links against ntdll.lib. ```batch cl.exe /W4 /I "C:\Path\To\Veil" project.cpp ntdll.lib ``` -------------------------------- ### Import by Name Lookup Logic Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md Explains the logic for importing functions by name, highlighting the role of the hint for faster lookup and the format in the Import Address Table (IAT). ```c // When importing by name, the hint provides the export ordinal for faster lookup // Windows checks the ordinal hint first; if it matches, no name lookup needed // Format in IAT: // Bit 63/31 (high bit) = 0: Import by name (pointer to IMAGE_IMPORT_BY_NAME) // Bit 63/31 (high bit) = 1: Import by ordinal (lower 16 bits = ordinal) ``` -------------------------------- ### CI.dll Export Definitions (.def file) Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md A sample .def file listing the exported functions from ci.dll. This file is used by the lib utility to create the import library. ```plaintext LIBRARY ci.dll EXPORTS CiValidateFileAsImageType @1 NONAME CiRegisterSigningInformation @2 NONAME CiUnregisterSigningInformation @3 NONAME CiCheckSignedFile CiFindPageHashesInCatalog CiFindPageHashesInSignedFile CiFreePolicyInfo CiGetCertPublisherName CiGetPEInformation CiInitialize CiSetTrustedOriginClaimId CiValidateFileObject CiVerifyHashInCatalog ``` -------------------------------- ### Include Veil.h for C++ and C Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/types.md Shows how to include the main Veil header file for both C++ and C development, including an optional macro for C++ namespace usage. ```c // C++ - automatic extern "C" handling #define VEIL_USE_SEPARATE_NAMESPACE // Optional: put in Veil namespace #include "Veil.h" // C - requires explicit extern "C" #include "Veil.h" ``` -------------------------------- ### Check Module Characteristics (C) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md Use bitwise operations with IMAGE_FILE constants to determine module properties like being a DLL or 32-bit. ```c // Check if module is a DLL IMAGE_OPTIONAL_HEADER OptHeader = /* ... */; if (OptHeader.Characteristics & IMAGE_FILE_DLL) { // Module is a DLL } // Check if module is 32-bit if (OptHeader.Characteristics & IMAGE_FILE_32BIT_MACHINE) { // 32-bit image } ``` -------------------------------- ### Compile with Musa.Veil using cl.exe Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Compile your C/C++ program using cl.exe, specifying the additional include directory for Musa.Veil. ```batch cl.exe /I "C:\Path\To\Musa.Veil" /W4 /WX MyProgram.c ``` -------------------------------- ### Compile User-Mode Application Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Compiles a user-mode application using cl.exe, specifying warning levels, include paths, and linking ntdll.lib. ```bash # User-mode application cl.exe /W4 /WX /I "C:\Path\To\Veil" MyProgram.c ntdll.lib ``` -------------------------------- ### Initialize Unicode String Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Manually initializes a UNICODE_STRING structure by setting its buffer, length, and maximum length. ```c UNICODE_STRING String; wchar_t Buffer[] = L"Hello, World!"; String.Buffer = Buffer; String.Length = (wcslen(Buffer)) * sizeof(wchar_t); String.MaximumLength = sizeof(Buffer); ``` -------------------------------- ### Exported Functions from DLL using dumpbin Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md Use the dumpbin utility to list exported functions from a DLL. This is the first step in generating an import library. ```bash dumpbin /EXPORTS c:\windows\system32\ci.dll ``` -------------------------------- ### Reserve and Commit Memory with NtAllocateVirtualMemory Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/memory-management.md This C code snippet demonstrates reserving a large memory region with top-down allocation and then committing physical pages as needed. Ensure proper error handling for NtAllocateVirtualMemory calls. ```c // Reserve large memory region with top-down allocation PVOID BaseAddress = NULL; SIZE_T Size = 1024 * 1024 * 10; // 10MB NTSTATUS Status = NtAllocateVirtualMemory( NtCurrentProcess(), &BaseAddress, 0, &Size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS, NULL ); // Later, commit physical pages as needed Size = 4096; // 1 page BaseAddress = (PVOID)((ULONG_PTR)BaseAddress + 0x2000); Status = NtAllocateVirtualMemory( NtCurrentProcess(), &BaseAddress, 0, &Size, MEM_COMMIT, PAGE_READWRITE, NULL ); ``` -------------------------------- ### Compile User Application with Veil Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Compile a user-mode application using cl.exe, specifying warning levels, include paths for Veil, and linking ntdll.lib. ```batch cl.exe /W4 /WX /I "C:\Path\To\Veil" MyProgram.c ntdll.lib ``` -------------------------------- ### Finding a Module by Name Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md Illustrates how to search for a specific module within the process's loaded modules list by its name, using the PEB's loader data. ```c PPEB Peb = GetProcessPEB(); PPEB_LDR_DATA LdrData = Peb->Ldr; UNICODE_STRING TargetName; RtlInitUnicodeString(&TargetName, L"ntdll.dll"); PLDR_DATA_TABLE_ENTRY FoundModule = NULL; LIST_ENTRY* Entry = LdrData->InLoadOrderModuleList.Flink; while (Entry != &LdrData->InLoadOrderModuleList) { PLDR_DATA_TABLE_ENTRY Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); if (RtlEqualUnicodeString(&Module->BaseDllName, &TargetName, TRUE)) { FoundModule = Module; break; } Entry = Entry->Flink; } ``` -------------------------------- ### Create Symbolic Link Object Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/object-manager.md Shows how to create a symbolic link object, which redirects to another object in the namespace. This function is used to establish object redirections. ```c HANDLE SymbolicLinkHandle; OBJECT_ATTRIBUTES ObjectAttrs; UNICODE_STRING TargetName = RTL_CONSTANT_STRING(L"\\Device\\HarddiskVolume1"); InitializeObjectAttributes(&ObjectAttrs, &SymbolicLinkName, OBJ_CASE_INSENSITIVE, ParentDirectory, NULL); NTSTATUS Status = NtCreateSymbolicLinkObject( &SymbolicLinkHandle, SYMBOLIC_LINK_ALL_ACCESS, &ObjectAttrs, &TargetName ); ``` -------------------------------- ### Enumerating Modules by Load Order Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md Provides a pattern for iterating through all loaded modules in a process, ordered by their load sequence, using the PEB's loader data structures. ```c // Get PEB from process PPEB Peb = GetProcessPEB(); // Get loader data PPEB_LDR_DATA LdrData = Peb->Ldr; // Walk modules in load order LIST_ENTRY* ModuleList = &LdrData->InLoadOrderModuleList; LIST_ENTRY* ModuleEntry = ModuleList->Flink; while (ModuleEntry != ModuleList) { // Get module entry (use CONTAINING_RECORD) PLDR_DATA_TABLE_ENTRY Module = CONTAINING_RECORD(ModuleEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); // Print module information wprintf(L"Module: %wZ at %p (size: 0x%x)\n", &Module->BaseDllName, Module->DllBase, Module->SizeOfImage); ModuleEntry = ModuleEntry->Flink; } ``` -------------------------------- ### Define Macro with Documentation Source: https://github.com/mirokaku/musa.veil/blob/main/AGENTS.md Defines a macro with brief and detailed documentation comments. Use this for creating custom macros with clear explanations. ```cpp // rev (for reverse-engineered) /** * \def MACRO_NAME * \brief Brief description. * * Detailed description of the macro's purpose and usage. */ #define MACRO_NAME value ``` -------------------------------- ### Add Musa.Veil Include Path Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Configures the project to include the Musa.Veil source directory. This is necessary when integrating via Git clone. ```text C:\Path\To\Musa.Veil ``` -------------------------------- ### Open Process Handle Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Opens a handle to a target process with specified access rights. Ensure to close the handle using NtClose when done. ```c HANDLE ProcessHandle; OBJECT_ATTRIBUTES ObjectAttributes; CLIENT_ID ClientId = {ProcessId, 0}; InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL); NTSTATUS Status = NtOpenProcess( &ProcessHandle, PROCESS_VM_READ | PROCESS_VM_WRITE, // Desired access &ObjectAttributes, &ClientId ); if (NT_SUCCESS(Status)) { // Use ProcessHandle NtClose(ProcessHandle); } ``` -------------------------------- ### Create Object with Attributes Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/object-manager.md Use this snippet to create an object with specified attributes like inheritance and case-insensitive matching. Ensure proper initialization of OBJECT_ATTRIBUTES and call NtCreateEvent with appropriate access rights. ```c // Create object with inheritance and case-insensitive matching ULONG Attributes = OBJ_INHERIT | OBJ_CASE_INSENSITIVE; OBJECT_ATTRIBUTES ObjectAttrs; InitializeObjectAttributes(&ObjectAttrs, &ObjectName, Attributes, ParentDirectory, SecurityDescriptor); NTSTATUS Status = NtCreateEvent(&EventHandle, EVENT_ALL_ACCESS, &ObjectAttrs, SynchronizationEvent, FALSE); ``` -------------------------------- ### Compile User Application with CMake Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Configure a CMake project to build a user-mode application. This involves setting the minimum CMake version, project name, adding the executable, specifying Veil's include directories, and linking against ntdll. ```cmake cmake_minimum_required(VERSION 3.15) project(MyProject) add_executable(MyApp project.cpp) # Add Veil include path target_include_directories(MyApp PRIVATE "C:/Path/To/Veil") # Link with ntdll target_link_libraries(MyApp PRIVATE ntdll) ``` -------------------------------- ### Checking Module Flags Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md Demonstrates how to check specific flags within the LDR_DATA_TABLE_ENTRY structure to determine module properties like being a DLL or if its entry point has been called. ```c // Check if module is a DLL PLDR_DATA_TABLE_ENTRY Entry = /* ... */; if (Entry->Flags & LDRP_IMAGE_DLL) { // Module is a DLL } // Check if image is at preferred base if ((Entry->Flags & LDRP_IMAGE_NOT_AT_BASE) == 0) { // Image loaded at preferred base address } // Check if entry point has been called if (Entry->Flags & LDRP_PROCESS_ATTACH_CALLED) { // DLL_PROCESS_ATTACH has been executed } ``` -------------------------------- ### Compile C++ Stub to OBJ file for 32-bit Source: https://github.com/mirokaku/musa.veil/blob/main/Library/README.CI.md Command to compile a C++ stub file into an object (.obj) file using the cl compiler. Ensure correct include paths and preprocessor definitions for a 32-bit kernel mode build. ```bat > SET KM_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\km" > SET CRT_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\km\crt" > SET KIT_SHARED_IncludePath="C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\shared" > > cl CI.Stub.cpp /c /kernel /Zc:wchar_t /I%KM_IncludePath% /I%CRT_IncludePath% /I%KIT_SHARED_IncludePath% /D _X86_=1 /D i386=1 /DSTD_CALL /D_MINCRYPT_LIB ``` -------------------------------- ### Include Order for Veil.h in C Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Ensures correct compilation by including 'Veil.h' first, followed by standard Windows headers like 'windows.h' and 'stdio.h'. This order is crucial for Veil library integration. ```c #include "Veil.h" // FIRST #include // SECOND #include // THIRD ``` -------------------------------- ### Add Musa.Veil NuGet Package to .vcxproj Source: https://github.com/mirokaku/musa.veil/blob/main/README.md Include the Musa.Veil NuGet package by adding this to your .vcxproj file. Ensure you specify the desired version. ```XML 1.0.0 ``` -------------------------------- ### Link ntdll.lib for User-Mode Native APIs Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Link with ntdll.lib when using user-mode Native APIs such as NtCreateProcess or NtQueryInformationProcess. ```batch link.exe ... ntdll.lib ... ``` -------------------------------- ### Enumerate Process Modules Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/process-management.md Retrieves PEB loader data and iterates through the module list to process module information. Ensure `Veil.h` is included and appropriate Windows SDK headers are available. ```c // Get PEB loader data PPEB_LDR_DATA LdrData = GetLdrData(ProcessHandle); // Walk the module list LIST_ENTRY* ModuleList = &LdrData->InLoadOrderModuleList; for (LIST_ENTRY* Entry = ModuleList->Flink; Entry != ModuleList; Entry = Entry->Flink) { PLDR_DATA_TABLE_ENTRY Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); // Process module information } ``` -------------------------------- ### Executive Functions API Reference Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/MANIFEST.txt Documentation for thread execution, firmware variables, and UEFI management within the Musa.Veil library. ```APIDOC ## api-reference/executive-functions.md ### Description Covers thread execution, firmware variables, and Unified Extensible Firmware Interface (UEFI) management. ### Topics Covered - Thread Execution - Firmware Variables - UEFI Management ``` -------------------------------- ### Open Process for Reading Memory Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/process-management.md Opens a process handle with the necessary rights to read its virtual memory. Ensure the process ID is valid and you have sufficient privileges. ```c HANDLE ProcessHandle = NtOpenProcess(&ProcessId, PROCESS_VM_READ, &ObjectAttributes); if (NT_SUCCESS(ProcessHandle)) { // Can now read process memory } ``` -------------------------------- ### Enumerate Loaded Modules in a Process Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Walks through the PEB's module list to enumerate loaded modules. Accesses module name, base address, and size. ```c // Get PEB and module list PPEB Peb = /* get from process */; PPEB_LDR_DATA LdrData = Peb->Ldr; // Walk module list LIST_ENTRY* Entry = LdrData->InLoadOrderModuleList.Flink; while (Entry != &LdrData->InLoadOrderModuleList) { PLDR_DATA_TABLE_ENTRY Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); // Use Module->BaseDllName, Module->DllBase, Module->SizeOfImage Entry = Entry->Flink; } ``` -------------------------------- ### Use Veil Definitions in Global Namespace (Default) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Include Veil.h without any special defines to use its definitions directly in the global namespace. ```c #include "Veil.h" // Use definitions directly HANDLE ProcessHandle; NTSTATUS Status = NtCreateEvent(/* ... */); ``` -------------------------------- ### Create a Thread Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Creates a new thread within a process using NtCreateThreadEx. Requires a thread entry point and optionally arguments. ```c HANDLE ThreadHandle; NTSTATUS Status = NtCreateThreadEx( &ThreadHandle, THREAD_ALL_ACCESS, NULL, // ObjectAttributes ProcessHandle, (PUSER_THREAD_START_ROUTINE)ThreadEntry, NULL, // Argument 0, // CreateFlags 0, 0, 0, NULL ); ``` -------------------------------- ### Enumerate Objects in Root Directory Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/object-manager.md This C code snippet demonstrates how to open and query the root directory object to enumerate its contents. Ensure you include Veil.h and link with ntdll.lib. ```c // Enumerate objects in the root directory HANDLE DirectoryHandle; OBJECT_ATTRIBUTES ObjectAttrs; UNICODE_STRING DirectoryName = RTL_CONSTANT_STRING(L"\"); InitializeObjectAttributes(&ObjectAttrs, &DirectoryName, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS Status = NtOpenDirectoryObject(&DirectoryHandle, DIRECTORY_QUERY, &ObjectAttrs); if (NT_SUCCESS(Status)) { OBJECT_DIRECTORY_INFORMATION Entries[10]; ULONG Context = 0; ULONG ReturnLength = 0; while (TRUE) { Status = NtQueryDirectoryObject(DirectoryHandle, Entries, sizeof(Entries), FALSE, FALSE, &Context, &ReturnLength); if (!NT_SUCCESS(Status)) break; for (ULONG i = 0; i < ReturnLength; i++) { // Process each entry } } NtClose(DirectoryHandle); } ``` -------------------------------- ### Include Specific Musa.Veil Modules Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Includes only specific modules from Musa.Veil to reduce compile times and binary size. Useful for targeted functionality. ```c // Include specific modules #include "Veil/Veil.System.Process.h" #include "Veil/Veil.System.Memory.h" ``` -------------------------------- ### Set Legacy System Environment Variable Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/executive-functions.md Sets a legacy firmware environment variable value. Requires SE_SYSTEM_ENVIRONMENT_NAME privilege. Setting the value to NULL deletes the variable. ```c __kernel_entry NTSYSCALLAPI NTSTATUS NTAPI NtSetSystemEnvironmentValue( _In_ PCUNICODE_STRING VariableName, _In_ PCUNICODE_STRING VariableValue ); _IRQL_requires_max_(PASSIVE_LEVEL) NTSYSAPI NTSTATUS NTAPI ZwSetSystemEnvironmentValue( _In_ PCUNICODE_STRING VariableName, _In_ PCUNICODE_STRING VariableValue ); ``` -------------------------------- ### Open Registry Key Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/quick-reference.md Opens a registry key for querying values and enumerating subkeys using NtOpenKey. Requires proper OBJECT_ATTRIBUTES. ```c HANDLE KeyHandle; OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING KeyName = RTL_CONSTANT_STRING(L"\Registry\Machine\Software"); InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS Status = NtOpenKey( &KeyHandle, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &ObjectAttributes ); ``` -------------------------------- ### Correct Include Order for Veil.h and Windows Headers Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Prevent type redefinition errors by including 'Veil.h' before other Windows headers. This ensures proper initialization and avoids conflicts. ```c #include "Veil.h" // FIRST #include // SECOND ``` -------------------------------- ### File Basic Information Structure Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/types.md Defines the FILE_BASIC_INFORMATION structure, used to retrieve or set basic file attributes such as creation time and file attributes. ```c typedef struct _FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; ULONG FileAttributes; } FILE_BASIC_INFORMATION, * PFILE_BASIC_INFORMATION; ``` -------------------------------- ### Open Process for Virtual Memory Operations Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/README.md Opens a handle to a process for reading and writing its virtual memory. Requires the target process ID. ```c #include "Veil.h" // Open process for virtual memory operations HANDLE ProcessHandle; OBJECT_ATTRIBUTES ObjectAttributes; CLIENT_ID ClientId = {ProcessId, 0}; InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL); NtOpenProcess(&ProcessHandle, PROCESS_VM_READ | PROCESS_VM_WRITE, &ObjectAttributes, &ClientId); ``` -------------------------------- ### Process Management API Reference Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/MANIFEST.txt Documentation related to process and thread access rights, PEB structures, and compatibility flags in Musa.Veil. ```APIDOC ## api-reference/process-management.md ### Description Details process and thread access rights, Process Environment Block (PEB) structures, and compatibility flags. ### Topics Covered - Process/Thread Access Rights - PEB Structures - Compatibility Flags ``` -------------------------------- ### Delay Load Descriptor Structure (C) Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/loader-and-modules.md The ImgDelayDescr structure defines attributes and pointers for delayed module loading, including module name and import tables. ```c typedef struct ImgDelayDescr { DWORD grAttrs; // Attributes LPCSTR szName; // Module name PIMAGE_THUNK_DATA phmod; // Module handle location PIMAGE_THUNK_DATA pIAT; // Import Address Table PIMAGE_THUNK_DATA pINT; // Import Name Table PIMAGE_THUNK_DATA pBoundIAT; // Bound IAT PIMAGE_THUNK_DATA pUnloadIAT; // Unload IAT DWORD dwTimeStamp; // Timestamp } ImgDelayDescr, * PImgDelayDescr; ``` -------------------------------- ### Include Specific Veil System Modules Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/configuration.md Include only the necessary Veil system modules by specifying their header files. This is useful for reducing compile times and binary size. ```c #include "Veil/Veil.System.Define.h" #include "Veil/Veil.System.Process.h" #include "Veil/Veil.System.Executive.h" ``` -------------------------------- ### Global and Session-Local Event Naming Source: https://github.com/mirokaku/musa.veil/blob/main/_autodocs/api-reference/object-manager.md Illustrates how to define names for events to control their visibility. Global events are system-wide, while session-local events are restricted to the current user session. ```c // Global named event (visible to all sessions) UNICODE_STRING EventName = RTL_CONSTANT_STRING(L"Global\MyEvent"); // Session-local event (visible only in current session) UNICODE_STRING EventName = RTL_CONSTANT_STRING(L"Local\MyEvent"); ```