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 + STACKSPACE INDEX_MESSAGEBOXA equ 1 * POINTERSIZE + STACKSPACE APIFUNCTIONCOUNT equ 2 segment .text ; Setup environment sub rsp, STACKSPACE + ROUND_EVEN(APIFUNCTIONCOUNT) * POINTERSIZE ;reserve stack space for called functions and for API addresses LOOKUP_API KERNEL32DLL, KERNEL32_LOADLIBRARYA, INDEX_KERNEL32_LOADLIBRARYA lea rcx, [rel USER32DLL] call [rsp + INDEX_KERNEL32_LOADLIBRARYA] LOOKUP_API USER32DLL, USER32_MESSAGEBOXA, INDEX_MESSAGEBOXA, INDEX_KERNEL32_LOADLIBRARYA ; Display MessageBox xor r9, r9 lea r8, [rel TITLE] lea rdx, [rel HELLO] xor rcx, rcx call [rsp + INDEX_MESSAGEBOXA] add rsp, STACKSPACE + ROUND_EVEN(APIFUNCTIONCOUNT) * POINTERSIZE ret %include "sc-x64-api-functions.asm" KERNEL32DLL db "KERNEL32.DLL", 0 KERNEL32_LOADLIBRARYA db "LoadLibraryA", 0 USER32DLL db "USER32.DLL", 0 USER32_MESSAGEBOXA db "MessageBoxA", 0 HELLO db "Hello from injected shell code!", 0 TITLE 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.