-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathc-to-shellcode.py
73 lines (55 loc) · 1.75 KB
/
c-to-shellcode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python3
#
# Name : c-to-shellcode.py
# Author: Print3M
# GitHub: https://github.com/Print3M
import subprocess
def args(arr: list[str]):
return " ".join(arr)
def run_cmd(cmd: str):
subprocess.run(cmd, text=True, check=True, shell=True)
print(f"[+] {cmd}")
LOADER_PAYLOAD_STR = ":PAYLOAD:"
CC = "x86_64-w64-mingw32-gcc-win32"
EXE_PAYLOAD_CFLAGS = args(["-fPIC", "-mconsole", "-Os", "-e start", "-nostartfiles"])
BIN_PAYLOAD_CFLAGS = args(
[
"-Os",
"-fPIC",
"-nostdlib",
"-nostartfiles",
"-ffreestanding",
"-fno-asynchronous-unwind-tables",
"-fno-ident",
"-e start",
"-s",
]
)
if __name__ == "__main__":
# Compile payload C code to object file
run_cmd(f"{CC} -c payload.c -o bin/payload.o {BIN_PAYLOAD_CFLAGS}")
# Produce flat binary with payload
run_cmd(
f"ld -T assets/linker.ld bin/payload.o -o bin/payload.bin"
)
# Produce PE .exe with payload (WinAPI included)
run_cmd(f"{CC} bin/payload.o -o bin/payload.exe {EXE_PAYLOAD_CFLAGS}")
# Convert flat binary into C array of bytes
with open("bin/payload.bin", "rb") as f:
bytes = bytearray(f.read())
size = len(bytes)
print(f"[+] Binary payload size: {size} bytes")
payload = ""
for byte in bytes:
payload += "\\" + hex(byte).lstrip("0")
# Inject payload into loader source code
with open("assets/loader.c", "r") as f:
loader = f.read()
loader = loader.replace(LOADER_PAYLOAD_STR, payload)
with open("bin/loader.c", "w") as f:
f.write(loader)
# Compile loader
run_cmd(f"{CC} bin/loader.c -o bin/loader.exe")
print("")
print("[+] bin/payload.exe is ready!")
print("[+] bin/loader.exe is ready!")