Kodax

اختبار الاختراق (Pen Testing) — الأمن المتقدم

اختبار الاختراق (Penetration Testing)

مراحل اختبار الاختراق

1. Reconnaissance (الاستطلاع)

- Passive: بدون تفاعل مباشر

- Active: تفاعل مع الهدف

2. Scanning (الفحص)

- Port scanning

- Vulnerability scanning

- Service enumeration

3. Exploitation (الاستغلال)

- استغلال الثغرات المكتشفة

- الحصول على access

4. Post-Exploitation

- Privilege escalation

- Lateral movement

- Data exfiltration

5. Reporting

- توثيق كل شيء

- تقديم التوصيات

أدوات شهيرة

- Nmap, Burp Suite

- Metasploit, SQLmap

- Wireshark, John the Ripper

import socket
import subprocess
import sys
import re

class PenTestTools:
    """
    أدوات اختبار اختراق بسيطة للتعليم
    ⚠️ للاستخدام على أنظمتك فقط بإذن!
    """
    
    @staticmethod
    def banner_grab(target: str, port: int) -> dict:
        """
        جمع معلومات الخدمة (Banner Grabbing)
        """
        result = {
            "target": target,
            "port": port,
            "banner": None,
            "error": None
        }
        
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            sock.connect((target, port))
            
            # إرسال طلب بسيط
            if port == 80:
                sock.send(b"HEAD / HTTP/1.1\r\nHost: " + target.encode() + b"\r\n\r\n")
            else:
                sock.send(b"\r\n")
            
            banner = sock.recv(1024).decode('utf-8', errors='ignore')
            result["banner"] = banner.strip()
            
        except Exception as e:
            result["error"] = str(e)
        finally:
            sock.close()
        
        return result
    
    @staticmethod
    def subdomain_enum(domain: str, wordlist: list = None) -> list:
        """
        اكتشاف النطاقات الفرعية
        """
        if wordlist is None:
            wordlist = [
                'www', 'mail', 'ftp', 'admin', 'blog',
                'api', 'dev', 'test', 'staging', 'app',
                'shop', 'store', 'secure', 'vpn', 'remote'
            ]
        
        found = []
        
        for sub in wordlist:
            subdomain = f"{sub}.{domain}"
            try:
                ip = socket.gethostbyname(subdomain)
                found.append({
                    "subdomain": subdomain,
                    "ip": ip
                })
            except socket.gaierror:
                pass
        
        return found
    
    @staticmethod
    def check_common_vulns(url: str) -> dict:
        """
        فحص ثغرات شائعة (محاكاة)
        """
        checks = {
            "sql_injection_params": False,
            "xss_reflection": False,
            "directory_listing": False,
            "sensitive_files": [],
            "security_headers": {}
        }
        
        # فحص ملفات حساسة شائعة
        sensitive_paths = [
            "/.env", "/config.php", "/wp-config.php",
            "/.git/config", "/backup.sql", "/admin",
            "/phpinfo.php", "/.htaccess", "/server-status"
        ]
        
        # محاكاة - في الواقع نرسل requests
        checks["notes"] = "هذا فحص محاكاة للتعليم"
        
        return checks
    
    @staticmethod
    def password_strength_audit(passwords: list) -> list:
        """
        تدقيق قوة كلمات المرور
        """
        common_passwords = [
            "password", "123456", "qwerty", "admin",
            "letmein", "welcome", "monkey", "dragon"
        ]
        
        results = []
        
        for pwd in passwords:
            audit = {
                "password": pwd[:3] + "*" * (len(pwd) - 3),
                "issues": []
            }
            
            if len(pwd) < 8:
                audit["issues"].append("قصيرة جداً (< 8)")
            
            if pwd.lower() in common_passwords:
                audit["issues"].append("كلمة مرور شائعة!")
            
            if not re.search(r'[A-Z]', pwd):
                audit["issues"].append("لا تحتوي حروف كبيرة")
            
            if not re.search(r'[0-9]', pwd):
                audit["issues"].append("لا تحتوي أرقام")
            
            if not re.search(r'[!@#$%^&*]', pwd):
                audit["issues"].append("لا تحتوي رموز")
            
            audit["risk"] = "🔴 عالي" if len(audit["issues"]) >= 3 else                            "🟡 متوسط" if len(audit["issues"]) >= 1 else "🟢 منخفض"
            
            results.append(audit)
        
        return results
    
    @staticmethod
    def generate_report(findings: dict) -> str:
        """
        توليد تقرير اختبار اختراق
        """
        report = """
╔══════════════════════════════════════════════╗
║         تقرير اختبار الاختراق               ║
╚══════════════════════════════════════════════╝

📅 التاريخ: {date}
🎯 الهدف: {target}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 ملخص النتائج:
  - ثغرات حرجة: {critical}
  - ثغرات عالية: {high}
  - ثغرات متوسطة: {medium}
  - ثغرات منخفضة: {low}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📝 التوصيات:
{recommendations}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
"""
        return report.format(**findings)

# ===== عرض توضيحي =====
tools = PenTestTools()

print("=== Banner Grabbing ===")
# result = tools.banner_grab("scanme.nmap.org", 80)
# print(result)
print("(يتطلب اتصال بالشبكة)\n")

print("=== Subdomain Enumeration ===")
# subdomains = tools.subdomain_enum("google.com")
# for sub in subdomains:
#     print(f"  {sub['subdomain']} -> {sub['ip']}")
print("(يتطلب اتصال بالشبكة)\n")

print("=== Password Audit ===")
test_passwords = ["admin", "MyP@ssw0rd!", "hello123", "Tr0ub4dor&3"]
audit_results = tools.password_strength_audit(test_passwords)

for result in audit_results:
    print(f"{result['risk']} {result['password']}")
    for issue in result['issues']:
        print(f"    ↳ {issue}")
اختبر فهمك