/ cnc_test_framework.py
cnc_test_framework.py
  1  #!/usr/bin/env python3
  2  """
  3  C&C SERVER TESTING FRAMEWORK
  4  Tests and evaluates generated C&C server code
  5  """
  6  import os
  7  import sys
  8  import subprocess
  9  import importlib.util
 10  import time
 11  import json
 12  from datetime import datetime
 13  import ast
 14  
 15  class CNCTester:
 16      def __init__(self):
 17          self.results = {}
 18          self.test_dir = "cnc_tests"
 19          os.makedirs(self.test_dir, exist_ok=True)
 20      
 21      def scan_for_cnc_files(self):
 22          """Find all potential C&C server files"""
 23          cnc_files = []
 24          
 25          for file in os.listdir("."):
 26              if file.endswith(".py"):
 27                  # Check if it looks like a C&C server
 28                  with open(file, 'r', errors='ignore') as f:
 29                      content = f.read().lower()
 30                      
 31                      # Keywords that indicate C&C functionality
 32                      keywords = [
 33                          'socket', 'server', 'client', 'command', 'execute',
 34                          'encrypt', 'aes', 'connect', 'bind', 'listen',
 35                          'thread', 'remote', 'shell', 'upload', 'download'
 36                      ]
 37                      
 38                      score = sum(1 for kw in keywords if kw in content)
 39                      if score >= 3:  # At least 3 keywords
 40                          cnc_files.append({
 41                              'file': file,
 42                              'score': score,
 43                              'size': os.path.getsize(file),
 44                              'lines': sum(1 for _ in open(file, 'r', errors='ignore'))
 45                          })
 46          
 47          # Sort by score
 48          cnc_files.sort(key=lambda x: x['score'], reverse=True)
 49          return cnc_files
 50      
 51      def analyze_file_structure(self, filename):
 52          """Analyze Python file structure"""
 53          try:
 54              with open(filename, 'r') as f:
 55                  content = f.read()
 56              
 57              # Parse AST
 58              tree = ast.parse(content)
 59              
 60              analysis = {
 61                  'imports': [],
 62                  'functions': [],
 63                  'classes': [],
 64                  'calls': []
 65              }
 66              
 67              for node in ast.walk(tree):
 68                  if isinstance(node, ast.Import):
 69                      for alias in node.names:
 70                          analysis['imports'].append(alias.name)
 71                  elif isinstance(node, ast.ImportFrom):
 72                      analysis['imports'].append(f"{node.module}")
 73                  elif isinstance(node, ast.FunctionDef):
 74                      analysis['functions'].append(node.name)
 75                  elif isinstance(node, ast.ClassDef):
 76                      analysis['classes'].append(node.name)
 77                  elif isinstance(node, ast.Call):
 78                      if hasattr(node.func, 'id'):
 79                          analysis['calls'].append(node.func.id)
 80              
 81              return analysis
 82          except:
 83              return {'error': 'Could not parse file'}
 84      
 85      def test_syntax(self, filename):
 86          """Test if Python file has valid syntax"""
 87          try:
 88              result = subprocess.run(
 89                  ["python3", "-m", "py_compile", filename],
 90                  capture_output=True,
 91                  text=True
 92              )
 93              return result.returncode == 0
 94          except:
 95              return False
 96      
 97      def test_execution(self, filename, timeout=10):
 98          """Test if file can be executed"""
 99          try:
100              # Create a test wrapper
101              test_code = f"""
102  import sys
103  import {filename.replace('.py', '')} as module
104  
105  print("โœ… Module loaded successfully")
106  print(f"Functions found: {{dir(module)}}")
107  
108  # Try to find main or server function
109  for attr in dir(module):
110      if 'main' in attr.lower() or 'server' in attr.lower() or 'start' in attr.lower():
111          print(f"Found potential entry point: {{attr}}")
112  """
113              
114              with open(f"{self.test_dir}/test_{filename}", 'w') as f:
115                  f.write(test_code)
116              
117              result = subprocess.run(
118                  ["python3", f"{self.test_dir}/test_{filename}"],
119                  capture_output=True,
120                  text=True,
121                  timeout=timeout
122              )
123              
124              return {
125                  'success': result.returncode == 0,
126                  'output': result.stdout,
127                  'error': result.stderr
128              }
129          except subprocess.TimeoutExpired:
130              return {'success': False, 'error': 'Timeout'}
131          except Exception as e:
132              return {'success': False, 'error': str(e)}
133      
134      def evaluate_security_features(self, filename):
135          """Evaluate security features in code"""
136          features = {
137              'encryption': False,
138              'authentication': False,
139              'logging': False,
140              'error_handling': False,
141              'input_validation': False
142          }
143          
144          try:
145              with open(filename, 'r') as f:
146                  content = f.read().lower()
147              
148              # Check for features
149              if any(word in content for word in ['aes', 'encrypt', 'crypto', 'cipher']):
150                  features['encryption'] = True
151              
152              if any(word in content for word in ['auth', 'login', 'password', 'credential']):
153                  features['authentication'] = True
154              
155              if any(word in content for word in ['log', 'logger', 'logging']):
156                  features['logging'] = True
157              
158              if any(word in content for word in ['try:', 'except', 'error', 'exception']):
159                  features['error_handling'] = True
160              
161              if any(word in content for word in ['validate', 'sanitize', 'check']):
162                  features['input_validation'] = True
163              
164              return features
165          except:
166              return features
167      
168      def generate_report(self, filename):
169          """Generate comprehensive report for a file"""
170          report = {
171              'filename': filename,
172              'timestamp': datetime.now().isoformat(),
173              'file_info': {},
174              'analysis': {},
175              'tests': {},
176              'security': {},
177              'rating': 0
178          }
179          
180          # File info
181          try:
182              report['file_info'] = {
183                  'size': os.path.getsize(filename),
184                  'lines': sum(1 for _ in open(filename, 'r', errors='ignore')),
185                  'modified': datetime.fromtimestamp(os.path.getmtime(filename)).isoformat()
186              }
187          except:
188              pass
189          
190          # Structure analysis
191          report['analysis'] = self.analyze_file_structure(filename)
192          
193          # Syntax test
194          report['tests']['syntax'] = self.test_syntax(filename)
195          
196          # Execution test
197          report['tests']['execution'] = self.test_execution(filename)
198          
199          # Security features
200          report['security'] = self.evaluate_security_features(filename)
201          
202          # Calculate rating
203          rating = 0
204          if report['tests']['syntax']:
205              rating += 2
206          if report['tests']['execution']['success']:
207              rating += 3
208          
209          security_points = sum(1 for v in report['security'].values() if v)
210          rating += security_points
211          
212          if len(report['analysis'].get('functions', [])) > 3:
213              rating += 1
214          if len(report['analysis'].get('classes', [])) > 0:
215              rating += 1
216          
217          report['rating'] = min(10, rating)
218          
219          return report
220      
221      def run_all_tests(self):
222          """Run tests on all C&C files"""
223          print("๐Ÿ” Scanning for C&C server files...")
224          cnc_files = self.scan_for_cnc_files()
225          
226          if not cnc_files:
227              print("โŒ No C&C server files found!")
228              return
229          
230          print(f"๐Ÿ“ Found {len(cnc_files)} potential C&C files:")
231          
232          reports = []
233          for file_info in cnc_files:
234              filename = file_info['file']
235              print(f"\n{'='*60}")
236              print(f"๐Ÿงช Testing: {filename}")
237              print(f"   Score: {file_info['score']}, Lines: {file_info['lines']}")
238              
239              report = self.generate_report(filename)
240              reports.append(report)
241              
242              # Print summary
243              print(f"   โœ… Syntax: {'PASS' if report['tests']['syntax'] else 'FAIL'}")
244              exec_test = report['tests']['execution']
245              print(f"   ๐Ÿš€ Execution: {'PASS' if exec_test['success'] else 'FAIL'}")
246              
247              if exec_test['success'] and exec_test['output']:
248                  print(f"   ๐Ÿ“ค Output: {exec_test['output'][:100]}...")
249              
250              sec_features = [k for k, v in report['security'].items() if v]
251              print(f"   ๐Ÿ”’ Security: {', '.join(sec_features) if sec_features else 'None'}")
252              
253              print(f"   โญ Rating: {report['rating']}/10")
254          
255          # Sort by rating
256          reports.sort(key=lambda x: x['rating'], reverse=True)
257          
258          # Save comprehensive report
259          report_file = f"{self.test_dir}/cnc_test_report_{int(time.time())}.json"
260          with open(report_file, 'w') as f:
261              json.dump({
262                  'timestamp': datetime.now().isoformat(),
263                  'total_tested': len(reports),
264                  'reports': reports,
265                  'top_files': [
266                      {
267                          'file': r['filename'],
268                          'rating': r['rating'],
269                          'security': [k for k, v in r['security'].items() if v]
270                      }
271                      for r in reports[:5]
272                  ]
273              }, f, indent=2)
274          
275          print(f"\n{'='*60}")
276          print("๐Ÿ“Š TESTING COMPLETE")
277          print("=" * 60)
278          
279          # Show top 3
280          print("\n๐Ÿ† TOP C&C SERVERS:")
281          for i, report in enumerate(reports[:3], 1):
282              print(f"{i}. {report['filename']} - Rating: {report['rating']}/10")
283              if report['security']:
284                  sec = [k for k, v in report['security'].items() if v]
285                  print(f"   Security features: {', '.join(sec)}")
286          
287          print(f"\n๐Ÿ’พ Full report saved to: {report_file}")
288          
289          return reports
290      
291      def create_combined_server(self, top_files=3):
292          """Create a combined server from the best files"""
293          reports = []
294          for file in os.listdir("."):
295              if file.endswith(".py") and "cnc" in file.lower():
296                  reports.append(self.generate_report(file))
297          
298          reports.sort(key=lambda x: x['rating'], reverse=True)
299          
300          if not reports:
301              print("โŒ No C&C files to combine!")
302              return
303          
304          print(f"\n๐Ÿ”— Combining top {min(top_files, len(reports))} servers...")
305          
306          combined = """#!/usr/bin/env python3
307  """
308  SUPER C&C SERVER - COMBINED FROM BEST GENERATED CODE
309  Generated: {datetime.now().isoformat()}
310  Sources: {', '.join(r['filename'] for r in reports[:top_files])}
311  ====================================================================
312  
313  """
314          
315          # Add imports from all files (deduplicated)
316          all_imports = set()
317          for report in reports[:top_files]:
318              analysis = report.get('analysis', {})
319              imports = analysis.get('imports', [])
320              for imp in imports:
321                  all_imports.add(imp)
322          
323          if all_imports:
324              combined += "# IMPORTS\n"
325              for imp in sorted(all_imports):
326                  combined += f"import {imp.split('.')[0]}\n"
327              combined += "\n"
328          
329          # Add code from each file
330          for i, report in enumerate(reports[:top_files], 1):
331              filename = report['filename']
332              combined += f"\n{'='*60}\n"
333              combined += f"# COMPONENT {i}: {filename}\n"
334              combined += f"# Rating: {report['rating']}/10\n"
335              combined += f"{'='*60}\n\n"
336              
337              with open(filename, 'r') as f:
338                  content = f.read()
339                  # Remove imports since we already added them
340                  lines = content.split('\n')
341                  lines = [line for line in lines if not line.startswith('import ') and not line.startswith('from ')]
342                  combined += '\n'.join(lines) + '\n'
343          
344          # Add main entry point
345          combined += f"""
346  {'='*60}
347  # MAIN ENTRY POINT
348  {'='*60}
349  
350  def main():
351      print("SUPER C&C SERVER - Combined Edition")
352      print("Sources: {', '.join(r['filename'] for r in reports[:top_files])}")
353      
354      # Initialize components
355      print("\\n๐Ÿ”ง Initializing components...")
356      
357      # Try to find and start server components
358      components_started = 0
359      
360      # Look for server start functions
361      import sys
362      for report in {reports[:top_files]}:
363          filename = report['filename'].replace('.py', '')
364          try:
365              module = __import__(filename)
366              for attr in dir(module):
367                  if 'start' in attr.lower() or 'main' in attr.lower():
368                      print(f"Starting component from {{filename}}...")
369                      getattr(module, attr)()
370                      components_started += 1
371          except:
372              pass
373      
374      print(f"โœ… {{components_started}} components started")
375      
376      if components_started == 0:
377          print("\\nโš ๏ธ No server components found to start")
378          print("   Try running individual files instead")
379  
380  if __name__ == "__main__":
381      main()
382  """
383          
384          combined_file = f"super_cnc_server_{int(time.time())}.py"
385          with open(combined_file, 'w') as f:
386              f.write(combined)
387          
388          print(f"โœ… Created: {combined_file}")
389          print(f"๐Ÿ“ Size: {len(combined.split('\\n'))} lines")
390          
391          return combined_file
392  
393  def main():
394      print("๐Ÿ›ก๏ธ C&C SERVER TESTING FRAMEWORK")
395      print("=" * 60)
396      
397      tester = CNCTester()
398      
399      print("\n๐ŸŽฏ Options:")
400      print("1. Test all C&C files")
401      print("2. Create combined super server")
402      print("3. Test specific file")
403      print("4. Exit")
404      
405      choice = input("\nSelect (1-4): ").strip()
406      
407      if choice == "1":
408          tester.run_all_tests()
409      elif choice == "2":
410          tester.create_combined_server()
411      elif choice == "3":
412          file = input("Enter filename: ").strip()
413          if os.path.exists(file):
414              report = tester.generate_report(file)
415              print(f"\n๐Ÿ“Š Report for {file}:")
416              print(f"Rating: {report['rating']}/10")
417              print(f"Security features: {[k for k, v in report['security'].items() if v]}")
418          else:
419              print("โŒ File not found!")
420      elif choice == "4":
421          print("๐Ÿ‘‹ Exiting...")
422      else:
423          print("โŒ Invalid choice!")
424  
425  if __name__ == "__main__":
426      main()