This technique is very similar to the Shellcode Runner technique. The only difference is that the shellcode will be injected in a remote process rather than the current process.
The Windows APIs required to perfrom this technique are the following:
dwProcessId: Will be the ID of the process to get a handle on
Luckily the OpenProcess API is part of the windows package
pid :=uint32(12240) PROCESS_ALL_ACCESS := windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE |0xFFFF fmt.Printf("[+] Getting a handle on process with pid: %d\n", pid) pHandle, err := windows.OpenProcess(uint32(PROCESS_ALL_ACCESS), false, pid)if err !=nil { log.Fatalf("[FATAL] Unable to get a handle on process with id: %d : %v ", pid, err) } fmt.Printf("[+] Obtained a handle 0x%x on process with ID: %d\n", pHandle, pid)
Allocating memory on remote process
VirtuallAllocEx will be used for allocating memory for our shellcode in the remote memory.
hProcess: Process Handle returned by the OpenProcess API
lpAddress: We will let the API decide where to allocate the memory, therefore this value will be set to 0
dwSize: Will be the size of our shellcode
flAllocationType: We need to reserve and commit memory
flProtect: This can be done in a number of ways. To write and execute shellcode we will need rwx permissions. It is however unusual for legitimate programs to allocate memory with rwx permissions and it is usually flagged my AV engines. Another option is to assign rx or rw and then change permissions as needed for writing and executing with VirtualProtectEx.
NOTE: WriteProcessMemory that is used later on will temporarily assign WRITE permissions if they are missing from the memory page using VirtualAllocEx. It might be a good idea to manually manage permissions to avoid additional calls to VirtualAllocEx.
hProcess: Process Handle returned by the OpenProcess API
lpBaseAddress: Value returned from VirtualAllocEx
lpBuffer: A pointer to the beginning of our shellcode byte array
nSize: Size of our shellcode
lpNumberOfBytesWritten: Ouputs the number of bytes written to the destination address
var numberOfBytesWritten uintptr err = windows.WriteProcessMemory(pHandle, addr,&sc[0], uintptr(len(sc)), &numberOfBytesWritten)if err !=nil { log.Fatalf("[FATAL] Unable to write shellcode to the the allocated address") } fmt.Printf("[+] Wrote %d bytes to destination address\n", numberOfBytesWritten)
Change Memory Permissions
Since the memory permissions were set to PAGE_READWRITE we now need to set them to PAGE_EXECUTE_READ. This can be achieved with VirtualProtectEx.