Last year I found great x64 shellcode for Windows on McDermott’s site. Not only is it dynamic (lookup API addresses), but it even handles forwarded functions.
But it’s written for MASM, and I prefer to use NASM. Hence I translated it, but also normalized it to adhere to the x64 calling convention and fixed a bug in the error handling.
And I modularized it so you can use it like my 32-bit shellcode.
Here’s the classic MessageBox example:
; x64 shellcode to display a “Hello from injected shell code!” MessageBox, then return to caller; Written for NASM assembler (http://www.nasm.us) by Didier Stevens; Source code put in public domain by Didier Stevens, no Copyright; https://DidierStevens.com; Use at your own risk;; History:; 2011/12/27: Refactored functions to include file sc-x64-api-functions.asm%include “sc-x64-macros.asm”INDEX_KERNEL32_LOADLIBRARYA equ 0 * POINTERSIZE + STACKSPACEINDEX_MESSAGEBOXA equ 1 * POINTERSIZE + STACKSPACEAPIFUNCTIONCOUNT equ 2segment .text; Setup environmentsub rsp, STACKSPACE + ROUND_EVEN(APIFUNCTIONCOUNT) * POINTERSIZE ;reserve stack space for called functions and for API addressesLOOKUP_API KERNEL32DLL, KERNEL32_LOADLIBRARYA, INDEX_KERNEL32_LOADLIBRARYAlea rcx, [rel USER32DLL]call [rsp + INDEX_KERNEL32_LOADLIBRARYA]LOOKUP_API USER32DLL, USER32_MESSAGEBOXA, INDEX_MESSAGEBOXA, INDEX_KERNEL32_LOADLIBRARYA; Display MessageBoxxor r9, r9lea r8, [rel TITLE]lea rdx, [rel HELLO]xor rcx, rcxcall [rsp + INDEX_MESSAGEBOXA]add rsp, STACKSPACE + ROUND_EVEN(APIFUNCTIONCOUNT) * POINTERSIZEret%include “sc-x64-api-functions.asm”KERNEL32DLL db “KERNEL32.DLL”, 0KERNEL32_LOADLIBRARYA db “LoadLibraryA”, 0USER32DLL db “USER32.DLL”, 0USER32_MESSAGEBOXA db “MessageBoxA”, 0HELLO db “Hello from injected shell code!”, 0TITLE db “Message”, 0
Here’s what I changed exactly from the original MASM code:
1) non-volatile registers are preserved (by storing them on the stack)
2) building the DLL name for forwarded functions is done with a variable on the stack frame of lookup_api, and not of the caller
3) the address of LoadLibraryA is passed via r9, and no longer r15
4) lookup_api not only returns the function address in rax, but also stores it in memory at an address provided in r8
5) fixed the error handling bug (stack restoration)
6) added some EQUs to make it easier to use this code as a “library” (include)
You can get the code from my shellcode page. Look for filenames starting with sc-x64 in the zip file.
Leave a reply