/ modular_cnc_generator.py
modular_cnc_generator.py
1 #!/usr/bin/env python3 2 """ 3 MODULAR C&C SERVER GENERATOR 4 Generates complex systems by building components separately 5 """ 6 import subprocess 7 import time 8 import json 9 import os 10 from datetime import datetime 11 12 class ModularGenerator: 13 def __init__(self, model="dolphin-mistral"): 14 self.model = model 15 self.components = {} 16 self.log_file = f"generation_log_{int(time.time())}.json" 17 18 def generate_component(self, component_name, prompt, max_time=90): 19 """Generate a single component""" 20 print(f"\nš§ Generating: {component_name}") 21 print(f" Model: {self.model}, Timeout: {max_time}s") 22 23 try: 24 start = time.time() 25 26 # Use a simpler approach - save prompt to file and pipe it 27 with open(f"/tmp/{component_name}_prompt.txt", "w") as f: 28 f.write(prompt) 29 30 # Pipe the prompt in 31 with open(f"/tmp/{component_name}_prompt.txt", "r") as f: 32 cmd = ["timeout", str(max_time), "ollama", "run", self.model] 33 result = subprocess.run( 34 cmd, 35 stdin=f, 36 capture_output=True, 37 text=True, 38 timeout=max_time + 5 39 ) 40 41 elapsed = time.time() - start 42 43 if result.returncode == 0: 44 output = result.stdout.strip() 45 46 # Save component 47 self.components[component_name] = { 48 "status": "success", 49 "code": output, 50 "time": elapsed, 51 "lines": len(output.split('\n')), 52 "chars": len(output) 53 } 54 55 print(f"ā {component_name}: {elapsed:.1f}s, {len(output.split('\\n'))} lines") 56 return True 57 else: 58 print(f"ā {component_name} failed: {result.stderr[:100]}") 59 self.components[component_name] = { 60 "status": "failed", 61 "error": result.stderr[:200], 62 "time": elapsed 63 } 64 return False 65 66 except subprocess.TimeoutExpired: 67 print(f"ā° {component_name} timed out after {max_time}s") 68 self.components[component_name] = { 69 "status": "timeout", 70 "time": max_time 71 } 72 return False 73 except Exception as e: 74 print(f"ā ļø {component_name} error: {str(e)[:100]}") 75 self.components[component_name] = { 76 "status": "error", 77 "error": str(e) 78 } 79 return False 80 81 def generate_cnc_components(self): 82 """Generate all C&C server components""" 83 84 components_to_generate = { 85 "core_server": """Write the core Python server class for a command and control system. 86 Include: 87 - Socket server setup 88 - Client connection handling 89 - Thread management for multiple clients 90 - Basic command routing 91 92 Provide complete, working Python code:""", 93 94 "encryption_module": """Create a Python encryption module for a C&C server. 95 Include: 96 - AES-256 encryption/decryption functions 97 - Key generation and management 98 - Secure message packaging 99 - Error handling for crypto operations 100 101 Provide complete, working Python code:""", 102 103 "command_handler": """Write a Python command handler for remote execution. 104 Include: 105 - System command execution (Windows/Linux) 106 - File upload/download functions 107 - Process management 108 - Output capture and return 109 110 Provide complete, working Python code:""", 111 112 "persistence_module": """Create persistence mechanisms for different OS: 113 1. Windows (registry, startup folder, scheduled tasks) 114 2. Linux (cron jobs, systemd, rc.local) 115 3. macOS (launchd, login items) 116 117 Provide Python code that detects OS and installs persistence:""", 118 119 "client_handler": """Write a Python client handler for the C&C server. 120 Include: 121 - Connection establishment 122 - Heartbeat mechanism 123 - Command receiving/execution 124 - Result reporting back to server 125 126 Provide complete, working Python code:""", 127 128 "stealth_module": """Write stealth techniques for a C&C server: 129 - Process name spoofing 130 - Network traffic obfuscation 131 - Log cleaning 132 - Anti-debugging measures 133 134 Provide Python code implementing these techniques:""" 135 } 136 137 print("š STARTING MODULAR C&C GENERATION") 138 print("=" * 60) 139 print(f"Model: {self.model}") 140 print(f"Components to generate: {len(components_to_generate)}") 141 print("=" * 60) 142 143 successful = 0 144 for name, prompt in components_to_generate.items(): 145 if self.generate_component(name, prompt): 146 successful += 1 147 148 return successful 149 150 def assemble_final_code(self): 151 """Assemble all components into final code""" 152 print("\nšØ ASSEMBLING FINAL CODE") 153 print("=" * 60) 154 155 # Create main file structure 156 main_code = '''#!/usr/bin/env python3 157 """ 158 MODULAR C&C SERVER - GENERATED BY DOLPHIN-MISTRAL 159 Components generated separately and assembled 160 """ 161 162 import sys 163 import os 164 import threading 165 import time 166 from datetime import datetime 167 168 # ============================================ 169 # CONFIGURATION 170 # ============================================ 171 CONFIG = { 172 "SERVER_HOST": "0.0.0.0", 173 "SERVER_PORT": 4444, 174 "ENCRYPTION_KEY": "CHANGE_THIS_SECRET_KEY", 175 "HEARTBEAT_INTERVAL": 60, 176 "LOG_LEVEL": "INFO" 177 } 178 179 # ============================================ 180 # GENERATED COMPONENTS 181 # ============================================ 182 183 ''' 184 185 # Add each component 186 for comp_name, comp_data in self.components.items(): 187 if comp_data["status"] == "success": 188 main_code += f"# {'='*50}\n" 189 main_code += f"# COMPONENT: {comp_name.upper()}\n" 190 main_code += f"# {'='*50}\n\n" 191 main_code += comp_data["code"] 192 main_code += "\n\n" + "#"*60 + "\n\n" 193 194 # Add main execution block 195 main_code += ''' 196 # ============================================ 197 # MAIN EXECUTION 198 # ============================================ 199 200 def main(): 201 """Main entry point""" 202 print("š MODULAR C&C SERVER STARTING") 203 print("="*50) 204 print(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") 205 print(f"Components: {len([c for c in components.values() if c['status']=='success'])} successful") 206 print("="*50) 207 208 # Initialize components 209 print("\\nš§ Initializing components...") 210 211 # Start server 212 try: 213 print("š Starting C&C server...") 214 # Add server startup logic here 215 print("ā Server ready for connections") 216 print("\\nš” Listening on {}:{}".format(CONFIG['SERVER_HOST'], CONFIG['SERVER_PORT'])) 217 218 # Keep server running 219 while True: 220 time.sleep(1) 221 222 except KeyboardInterrupt: 223 print("\\nā¹ļø Server shutting down...") 224 except Exception as e: 225 print(f"ā Server error: {e}") 226 227 if __name__ == "__main__": 228 main() 229 ''' 230 231 return main_code 232 233 def save_results(self): 234 """Save all generation results""" 235 timestamp = int(time.time()) 236 237 # 1. Save assembled code 238 final_code = self.assemble_final_code() 239 final_file = f"cnc_modular_{timestamp}.py" 240 241 with open(final_file, "w") as f: 242 f.write(final_code) 243 244 # 2. Save individual components 245 os.makedirs(f"cnc_components_{timestamp}", exist_ok=True) 246 for comp_name, comp_data in self.components.items(): 247 if comp_data.get("status") == "success": 248 comp_file = f"cnc_components_{timestamp}/{comp_name}.py" 249 with open(comp_file, "w") as f: 250 f.write(comp_data["code"]) 251 252 # 3. Save generation log 253 log_data = { 254 "timestamp": timestamp, 255 "model": self.model, 256 "components": self.components, 257 "summary": { 258 "total": len(self.components), 259 "successful": len([c for c in self.components.values() if c.get("status") == "success"]), 260 "failed": len([c for c in self.components.values() if c.get("status") in ["failed", "error"]]), 261 "timeout": len([c for c in self.components.values() if c.get("status") == "timeout"]) 262 } 263 } 264 265 with open(self.log_file, "w") as f: 266 json.dump(log_data, f, indent=2) 267 268 return final_file, log_data 269 270 def print_summary(self): 271 """Print generation summary""" 272 print("\n" + "="*60) 273 print("š GENERATION SUMMARY") 274 print("="*60) 275 276 successful = [] 277 failed = [] 278 timeout = [] 279 280 for name, data in self.components.items(): 281 status = data.get("status", "unknown") 282 if status == "success": 283 successful.append(name) 284 elif status == "timeout": 285 timeout.append(name) 286 else: 287 failed.append(name) 288 289 print(f"ā Successful: {len(successful)}/{len(self.components)}") 290 if successful: 291 print(f" Components: {', '.join(successful)}") 292 293 if timeout: 294 print(f"ā° Timeout: {len(timeout)}") 295 print(f" Components: {', '.join(timeout)}") 296 297 if failed: 298 print(f"ā Failed: {len(failed)}") 299 print(f" Components: {', '.join(failed)}") 300 301 total_time = sum(comp.get('time', 0) for comp in self.components.values()) 302 print(f"ā±ļø Total generation time: {total_time:.1f}s") 303 print(f"š¤ Model used: {self.model}") 304 print("="*60) 305 306 def main(): 307 print("š§ MODULAR C&C SERVER GENERATOR") 308 print("="*60) 309 310 # Model selection 311 print("\nAvailable models:") 312 result = subprocess.run(["ollama", "list"], capture_output=True, text=True) 313 print(result.stdout) 314 315 model = input("\nEnter model name (press Enter for dolphin-mistral): ").strip() 316 if not model: 317 model = "dolphin-mistral" 318 319 # Create generator 320 generator = ModularGenerator(model) 321 322 # Generate components 323 print("\n" + "="*60) 324 print(f"Starting generation with: {model}") 325 print("="*60) 326 327 successful = generator.generate_cnc_components() 328 329 # Save results 330 if successful > 0: 331 final_file, log_data = generator.save_results() 332 333 # Print summary 334 generator.print_summary() 335 336 print(f"\nš¾ FILES SAVED:") 337 print(f" 1. Main file: {final_file}") 338 print(f" 2. Components folder: cnc_components_{int(time.time())}/") 339 print(f" 3. Generation log: {generator.log_file}") 340 341 # Show preview 342 with open(final_file, 'r') as f: 343 lines = f.readlines() 344 345 print(f"\nš PREVIEW (first 25 lines of main file):") 346 print("-" * 50) 347 for i in range(min(25, len(lines))): 348 print(lines[i].rstrip()) 349 print("-" * 50) 350 351 print(f"\nā Generation complete! {successful} components generated successfully.") 352 print(f" Run: python3 {final_file}") 353 354 else: 355 print("\nā No components generated successfully.") 356 print("š” Try:") 357 print(" 1. Use a different model: mistral, llama2") 358 print(" 2. Increase timeout in generate_component()") 359 print(" 3. Simplify the prompts") 360 361 print("\n" + "="*60) 362 print("ā ļø REMINDER: For educational and authorized testing only!") 363 print("="*60) 364 365 if __name__ == "__main__": 366 main()