Kodax

كتابة التقارير الأمنية — الجزء 1: المبادئ — الاختراق الأخلاقي

كتابة التقارير الأمنية

أهمية التقرير

- يُوثّق عملك

- يُقنع العميل بالمشاكل

- يُساعد المطورين على الإصلاح

- دليل قانوني على عملك المصرّح

أجزاء التقرير

1. الملخص التنفيذي (Executive Summary)

- لغير التقنيين

- النتائج الرئيسية

- التوصيات العامة

- 1-2 صفحة

2. نطاق الاختبار (Scope)

- ما تم اختباره

- ما لم يُختبر

- الفترة الزمنية

- القيود

3. المنهجية (Methodology)

- الأدوات المستخدمة

- الخطوات المتبعة

- معايير التقييم

4. النتائج (Findings)

لكل ثغرة:

- العنوان: وصف قصير

- الخطورة: Critical/High/Medium/Low

- الوصف: شرح المشكلة

- التأثير: ماذا يمكن أن يحدث

- الدليل: Screenshots, PoC

- التوصية: كيفية الإصلاح

5. الملاحق (Appendices)

- Logs كاملة

- أكواد الاستغلال

- تفاصيل تقنية

تصنيف الخطورة (CVSS)

| الخطورة | النطاق | الوصف |

|---------|--------|-------|

| Critical | 9.0-10.0 | استغلال فوري، تأثير كارثي |

| High | 7.0-8.9 | استغلال سهل، تأثير كبير |

| Medium | 4.0-6.9 | استغلال يحتاج شروط |

| Low | 0.1-3.9 | تأثير محدود |

| Info | 0 | معلومات فقط |

نصائح للكتابة

- كن واضحاً ومحدداً

- أضف صور وأدلة

- اقترح حلولاً عملية

- راجع قبل التسليم

# قالب تقرير اختبار اختراق
from datetime import datetime
import json

class PenTestReport:
    """
    قالب تقرير اختبار اختراق احترافي
    """
    
    def __init__(self, client_name, target, tester_name):
        self.report = {
            "metadata": {
                "title": f"تقرير اختبار اختراق - {client_name}",
                "client": client_name,
                "target": target,
                "tester": tester_name,
                "date": datetime.now().strftime("%Y-%m-%d"),
                "version": "1.0"
            },
            "executive_summary": "",
            "scope": {
                "in_scope": [],
                "out_of_scope": [],
                "testing_period": "",
                "limitations": []
            },
            "methodology": [],
            "findings": [],
            "recommendations": [],
            "appendices": []
        }
    
    def set_scope(self, in_scope, out_of_scope, period, limitations=None):
        """تحديد نطاق الاختبار"""
        self.report["scope"] = {
            "in_scope": in_scope,
            "out_of_scope": out_of_scope,
            "testing_period": period,
            "limitations": limitations or []
        }
    
    def add_methodology(self, phase, description, tools):
        """إضافة خطوة منهجية"""
        self.report["methodology"].append({
            "phase": phase,
            "description": description,
            "tools": tools
        })
    
    def add_finding(self, title, severity, description, impact, 
                    evidence, recommendation, cvss_score=None):
        """إضافة ثغرة مكتشفة"""
        
        finding_id = f"VULN-{len(self.report['findings']) + 1:03d}"
        
        finding = {
            "id": finding_id,
            "title": title,
            "severity": severity,
            "cvss_score": cvss_score,
            "description": description,
            "impact": impact,
            "evidence": evidence,
            "recommendation": recommendation,
            "status": "Open"
        }
        
        self.report["findings"].append(finding)
        return finding_id
    
    def generate_executive_summary(self):
        """توليد الملخص التنفيذي"""
        
        # إحصائيات
        severity_count = {"Critical": 0, "High": 0, "Medium": 0, "Low": 0, "Info": 0}
        for f in self.report["findings"]:
            severity_count[f["severity"]] += 1
        
        total = len(self.report["findings"])
        critical_high = severity_count["Critical"] + severity_count["High"]
        
        summary = f"""
الملخص التنفيذي
===============

تم إجراء اختبار اختراق لـ {self.report['metadata']['client']} 
في الفترة {self.report['scope']['testing_period']}.

النتائج الرئيسية:
-----------------
• إجمالي الثغرات المكتشفة: {total}
  - حرجة (Critical): {severity_count['Critical']}
  - عالية (High): {severity_count['High']}
  - متوسطة (Medium): {severity_count['Medium']}
  - منخفضة (Low): {severity_count['Low']}
  - معلوماتية (Info): {severity_count['Info']}

التقييم العام:
-------------
"""
        
        if critical_high > 0:
            summary += f"⚠️ الوضع الأمني يحتاج اهتمام فوري! ({critical_high} ثغرات حرجة/عالية)"
        elif severity_count["Medium"] > 0:
            summary += "⚠️ الوضع الأمني مقبول مع وجود مجال للتحسين"
        else:
            summary += "✅ الوضع الأمني جيد"
        
        summary += """

التوصيات العاجلة:
----------------
"""
        # أضف الثغرات الحرجة والعالية
        for f in self.report["findings"]:
            if f["severity"] in ["Critical", "High"]:
                summary += f"• [{f['severity']}] {f['title']}\n"
        
        self.report["executive_summary"] = summary
        return summary
    
    def generate_markdown(self):
        """توليد التقرير بصيغة Markdown"""
        
        md = f"""# {self.report['metadata']['title']}

**العميل:** {self.report['metadata']['client']}  
**الهدف:** {self.report['metadata']['target']}  
**المختبر:** {self.report['metadata']['tester']}  
**التاريخ:** {self.report['metadata']['date']}  
**الإصدار:** {self.report['metadata']['version']}

---

{self.report['executive_summary']}

---

## نطاق الاختبار

### ضمن النطاق:
"""
        for item in self.report['scope']['in_scope']:
            md += f"- {item}\n"
        
        md += """
### خارج النطاق:
"""
        for item in self.report['scope']['out_of_scope']:
            md += f"- {item}\n"
        
        md += f"""
**فترة الاختبار:** {self.report['scope']['testing_period']}

---

## المنهجية

"""
        for i, method in enumerate(self.report['methodology'], 1):
            md += f"""### {i}. {method['phase']}
{method['description']}

**الأدوات:** {', '.join(method['tools'])}

"""
        
        md += """---

## النتائج التفصيلية

"""
        for finding in self.report['findings']:
            severity_emoji = {
                "Critical": "🔴",
                "High": "🟠", 
                "Medium": "🟡",
                "Low": "🟢",
                "Info": "🔵"
            }
            
            md += f"""### {finding['id']}: {finding['title']}

{severity_emoji.get(finding['severity'], '')} **الخطورة:** {finding['severity']}
{f"**CVSS:** {finding['cvss_score']}" if finding['cvss_score'] else ""}

**الوصف:**  
{finding['description']}

**التأثير:**  
{finding['impact']}

**الدليل:**  
{finding['evidence']}

**التوصية:**  
{finding['recommendation']}

---

"""
        
        return md
    
    def save_report(self, filename):
        """حفظ التقرير"""
        # JSON
        with open(f"{filename}.json", 'w', encoding='utf-8') as f:
            json.dump(self.report, f, ensure_ascii=False, indent=2)
        
        # Markdown
        self.generate_executive_summary()
        md = self.generate_markdown()
        with open(f"{filename}.md", 'w', encoding='utf-8') as f:
            f.write(md)
        
        print(f"✅ تم حفظ التقرير: {filename}.json و {filename}.md")


# ===== مثال على إنشاء تقرير =====
report = PenTestReport(
    client_name="شركة Example",
    target="example.com",
    tester_name="أحمد - فريق الأمن"
)

# تحديد النطاق
report.set_scope(
    in_scope=["example.com", "api.example.com", "admin.example.com"],
    out_of_scope=["mail.example.com", "Third-party services"],
    period="1-15 يناير 2024",
    limitations=["لا اختبار DDoS", "ساعات العمل فقط"]
)

# المنهجية
report.add_methodology(
    "الاستطلاع",
    "جمع المعلومات عن الهدف",
    ["Nmap", "theHarvester", "Google Dorks"]
)
report.add_methodology(
    "الفحص",
    "فحص الثغرات والخدمات",
    ["Nmap", "Nikto", "Burp Suite"]
)
report.add_methodology(
    "الاستغلال",
    "محاولة استغلال الثغرات المكتشفة",
    ["Burp Suite", "SQLmap", "Manual Testing"]
)

# إضافة ثغرات
report.add_finding(
    title="SQL Injection في صفحة تسجيل الدخول",
    severity="Critical",
    description="حقل username يقبل أوامر SQL ضارة",
    impact="يمكن للمهاجم الوصول لقاعدة البيانات كاملة وسرقة بيانات المستخدمين",
    evidence="Payload: ' OR '1'='1' -- \nالنتيجة: تم تسجيل الدخول بدون كلمة مرور",
    recommendation="استخدام Prepared Statements وتنظيف المدخلات",
    cvss_score=9.8
)

report.add_finding(
    title="Missing Content-Security-Policy Header",
    severity="Medium",
    description="الموقع لا يرسل CSP header",
    impact="يزيد من خطر هجمات XSS",
    evidence="curl -I https://example.com | grep -i content-security",
    recommendation="إضافة CSP header مناسب",
    cvss_score=5.3
)

# توليد وحفظ
report.generate_executive_summary()
print(report.generate_markdown())
# report.save_report("pentest_report_example")
اختبر فهمك