---
name: security-vulnerability
description: >
  نظام إدارة واكتشاف ومعالجة الثغرات الأمنية.
  استخدم هذا الـ skill عند: فحص الثغرات، إدارة نقاط الضعف، اختبار الاختراق،
  تقييم المخاطر الأمنية، OWASP compliance، إدارة الأحداث الأمنية (SIEM)،
  استجابة الحوادث، تحديثات أمنية، مسح الشبكة، أو أي مهمة تتعلق بالأمن السيبراني.
  يتوافق مع إطار عمل الهيئة الوطنية للأمن السيبراني (NCA-ECC).
---

# Security Vulnerability Management
# إدارة الثغرات الأمنية

## Architecture

```
┌──────────────────────────────────────────────────────────┐
│                  Security Operations Center               │
│                                                          │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐ │
│  │ Vuln     │  │ SAST     │  │ DAST     │  │ Depend  │ │
│  │ Scanner  │  │ Code     │  │ Runtime  │  │ Check   │ │
│  │ (Infra)  │  │ Analysis │  │ Scan     │  │ (SCA)   │ │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬────┘ │
│       └──────────────┼──────────────┼─────────────┘      │
│                      ▼                                    │
│              ┌──────────────┐                             │
│              │  Aggregator  │                             │
│              │  & Dedup     │                             │
│              └──────┬───────┘                             │
│                     ▼                                     │
│              ┌──────────────┐      ┌──────────────┐      │
│              │ Risk Scoring │─────►│ Alert Engine │      │
│              │ & Prioritize │      │ & Workflow   │      │
│              └──────────────┘      └──────────────┘      │
└──────────────────────────────────────────────────────────┘
```

## Domain Model

```csharp
// === الثغرة الأمنية ===
public class Vulnerability : BaseAuditableEntity
{
    public int Id { get; set; }
    public string VulnId { get; set; } = string.Empty;          // VULN-2024-00001
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    
    // Classification
    public VulnerabilityType Type { get; set; }
    public VulnerabilityCategory Category { get; set; }
    public string? CveId { get; set; }                           // CVE-2024-XXXXX
    public string? CweId { get; set; }                           // CWE-79 (XSS)
    public string? OwaspCategory { get; set; }                   // A01:2021
    
    // Severity (CVSS v3.1)
    public decimal CvssScore { get; set; }                       // 0.0 - 10.0
    public CvssSeverity Severity { get; set; }
    public string? CvssVector { get; set; }                      // CVSS:3.1/AV:N/AC:L/...
    
    // Risk Assessment
    public ExploitabilityLevel Exploitability { get; set; }
    public bool IsExploitedInWild { get; set; }
    public bool HasPublicExploit { get; set; }
    public BusinessImpact BusinessImpact { get; set; }
    public int RiskScore { get; set; }                           // Custom: CVSS × Impact
    
    // Affected Asset
    public int AssetId { get; set; }
    public string AssetName { get; set; } = string.Empty;
    public AssetType AssetType { get; set; }
    public string? AffectedComponent { get; set; }
    public string? AffectedVersion { get; set; }
    
    // Discovery
    public DiscoverySource Source { get; set; }
    public DateTime DiscoveredAt { get; set; }
    public int? DiscoveredByUserId { get; set; }
    public string? ScanToolName { get; set; }
    
    // Remediation
    public VulnStatus Status { get; set; }
    public string? RemediationPlan { get; set; }
    public string? Workaround { get; set; }
    public int? AssignedToId { get; set; }
    public DateTime? RemediationDueDate { get; set; }
    public DateTime? RemediatedAt { get; set; }
    public DateTime? VerifiedAt { get; set; }
    public int? VerifiedByUserId { get; set; }
    
    // SLA tracking
    public int SlaHours { get; set; }                            // Based on severity
    public bool IsSlaBreached { get; set; }
    
    public List<VulnerabilityNote> Notes { get; set; } = new();
    public List<VulnerabilityAttachment> Attachments { get; set; } = new();
}

public enum CvssSeverity
{
    None,           // 0.0
    Low,            // 0.1-3.9
    Medium,         // 4.0-6.9
    High,           // 7.0-8.9
    Critical        // 9.0-10.0
}

public enum VulnerabilityType
{
    Infrastructure,     // بنية تحتية
    Application,        // تطبيقات
    Configuration,      // إعدادات
    CodeLevel,          // مستوى الكود
    Dependency,         // مكتبات خارجية
    Network,            // شبكة
    CloudMisconfig,     // إعدادات سحابية
    Authentication,     // مصادقة
    Encryption          // تشفير
}

public enum VulnerabilityCategory
{
    // OWASP Top 10 (2021)
    BrokenAccessControl,        // A01 - كسر التحكم بالوصول
    CryptographicFailures,      // A02 - فشل التشفير
    Injection,                  // A03 - حقن
    InsecureDesign,             // A04 - تصميم غير آمن
    SecurityMisconfiguration,   // A05 - إعدادات أمنية خاطئة
    VulnerableComponents,       // A06 - مكونات ضعيفة
    AuthenticationFailures,     // A07 - فشل المصادقة
    IntegrityFailures,          // A08 - فشل سلامة البيانات
    LoggingFailures,            // A09 - فشل التسجيل والمراقبة
    SSRF,                       // A10 - تزوير الطلبات
    Other
}

public enum DiscoverySource
{
    AutomatedScan,          // فحص تلقائي
    PenetrationTest,        // اختبار اختراق
    BugBounty,              // مكافآت الثغرات
    CodeReview,             // مراجعة الكود
    IncidentResponse,       // استجابة لحادث
    VendorAdvisory,         // تنبيه من المورد
    ThreatIntelligence,     // استخبارات تهديد
    InternalAudit,          // تدقيق داخلي
    UserReport              // بلاغ مستخدم
}

// === الحادث الأمني ===
public class SecurityIncident : BaseAuditableEntity
{
    public int Id { get; set; }
    public string IncidentNumber { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public IncidentSeverity Severity { get; set; }
    public IncidentType Type { get; set; }
    public IncidentStatus Status { get; set; }
    
    // Impact
    public string? AffectedSystems { get; set; }
    public int? AffectedUsersCount { get; set; }
    public bool DataBreached { get; set; }
    public string? DataBreachDetails { get; set; }
    
    // Timeline
    public DateTime DetectedAt { get; set; }
    public DateTime? ContainedAt { get; set; }
    public DateTime? EradicatedAt { get; set; }
    public DateTime? RecoveredAt { get; set; }
    public DateTime? LessonsLearnedAt { get; set; }
    
    // Assignment
    public int? IncidentCommanderId { get; set; }
    public List<int> ResponseTeamIds { get; set; } = new();
    
    public List<IncidentTimeline> Timeline { get; set; } = new();
    public List<int> RelatedVulnerabilityIds { get; set; } = new();
}

public enum IncidentType
{
    Malware,                // برمجيات خبيثة
    Phishing,               // تصيد احتيالي
    Ransomware,             // فدية
    DataBreach,             // تسريب بيانات
    DDoS,                   // حجب خدمة
    UnauthorizedAccess,     // وصول غير مصرح
    InsiderThreat,          // تهديد داخلي
    AccountCompromise,      // اختراق حساب
    WebDefacement,          // تشويه موقع
    DataLoss                // فقدان بيانات
}

// === أصل أمني ===
public class SecurityAsset
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public SecurityAssetType Type { get; set; }
    public string? IpAddress { get; set; }
    public string? Hostname { get; set; }
    public string? OperatingSystem { get; set; }
    public string? Version { get; set; }
    public CriticalityLevel Criticality { get; set; }
    public int DepartmentId { get; set; }
    public DateTime? LastScanDate { get; set; }
    public int OpenVulnerabilities { get; set; }
}
```

## Vulnerability Scanner Integration

```csharp
public interface IVulnerabilityScanner
{
    Task<ScanResult> ScanAsync(ScanRequest request);
    Task<List<Vulnerability>> ParseResultsAsync(ScanResult result);
}

// === SAST - Static Application Security Testing ===
public class SastScanner
{
    public async Task<List<CodeVulnerability>> ScanCodeAsync(string repositoryPath)
    {
        var vulnerabilities = new List<CodeVulnerability>();
        
        // Pattern-based detection
        var patterns = new Dictionary<string, SecurityPattern>
        {
            ["SQL_INJECTION"] = new()
            {
                Regex = @"(string\.Format|[""'].*\+.*[""']).*(@"".*SELECT|INSERT|UPDATE|DELETE)",
                CweId = "CWE-89",
                Severity = CvssSeverity.Critical,
                Description = "SQL Injection المحتمل - استخدم parameterized queries"
            },
            ["XSS"] = new()
            {
                Regex = @"@Html\.Raw\(|innerHTML\s*=|dangerouslySetInnerHTML",
                CweId = "CWE-79",
                Severity = CvssSeverity.High,
                Description = "XSS المحتمل - استخدم HTML encoding"
            },
            ["HARDCODED_SECRET"] = new()
            {
                Regex = @"(password|secret|apikey|api_key|token)\s*=\s*[""'][^""']+[""']",
                CweId = "CWE-798",
                Severity = CvssSeverity.High,
                Description = "بيانات سرية مكتوبة في الكود - استخدم Key Vault"
            },
            ["INSECURE_CRYPTO"] = new()
            {
                Regex = @"(MD5|SHA1|DES)\.",
                CweId = "CWE-327",
                Severity = CvssSeverity.Medium,
                Description = "خوارزمية تشفير ضعيفة - استخدم SHA256+ أو AES"
            },
            ["PATH_TRAVERSAL"] = new()
            {
                Regex = @"Path\.Combine\(.*Request\.|\.\.\/|\.\.\\",
                CweId = "CWE-22",
                Severity = CvssSeverity.High,
                Description = "Path Traversal المحتمل - تحقق من المسارات"
            }
        };
        
        // Scan all code files
        var codeFiles = Directory.GetFiles(repositoryPath, "*.*", SearchOption.AllDirectories)
            .Where(f => f.EndsWith(".cs") || f.EndsWith(".tsx") || f.EndsWith(".ts"));
        
        foreach (var file in codeFiles)
        {
            var content = await File.ReadAllTextAsync(file);
            var lines = content.Split('\n');
            
            foreach (var (patternName, pattern) in patterns)
            {
                var matches = Regex.Matches(content, pattern.Regex, RegexOptions.IgnoreCase);
                foreach (Match match in matches)
                {
                    var lineNumber = content[..match.Index].Count(c => c == '\n') + 1;
                    vulnerabilities.Add(new CodeVulnerability
                    {
                        FilePath = file,
                        LineNumber = lineNumber,
                        CodeSnippet = lines[lineNumber - 1].Trim(),
                        PatternName = patternName,
                        CweId = pattern.CweId,
                        Severity = pattern.Severity,
                        Description = pattern.Description
                    });
                }
            }
        }
        
        return vulnerabilities;
    }
}

// === Dependency Check (SCA) ===
public class DependencyChecker
{
    public async Task<List<DependencyVulnerability>> CheckAsync(string projectPath)
    {
        // .NET: Check NuGet packages
        var csprojFiles = Directory.GetFiles(projectPath, "*.csproj", SearchOption.AllDirectories);
        var vulnerabilities = new List<DependencyVulnerability>();
        
        foreach (var csproj in csprojFiles)
        {
            var doc = XDocument.Load(csproj);
            var packages = doc.Descendants("PackageReference")
                .Select(p => new { 
                    Name = p.Attribute("Include")?.Value,
                    Version = p.Attribute("Version")?.Value 
                });
            
            foreach (var pkg in packages)
            {
                // Check against NVD / OSV database
                var cves = await _nvdClient.SearchAsync(pkg.Name!, pkg.Version!);
                vulnerabilities.AddRange(cves.Select(cve => new DependencyVulnerability
                {
                    PackageName = pkg.Name!,
                    CurrentVersion = pkg.Version!,
                    CveId = cve.Id,
                    CvssScore = cve.CvssScore,
                    FixedVersion = cve.FixedVersion,
                    Description = cve.Description
                }));
            }
        }
        
        return vulnerabilities;
    }
}
```

## SLA by Severity

```csharp
public static class VulnerabilitySla
{
    // NCA-ECC aligned SLAs
    public static readonly Dictionary<CvssSeverity, TimeSpan> RemediationSla = new()
    {
        { CvssSeverity.Critical, TimeSpan.FromHours(24) },     // 24 ساعة
        { CvssSeverity.High, TimeSpan.FromDays(7) },           // 7 أيام
        { CvssSeverity.Medium, TimeSpan.FromDays(30) },        // 30 يوم
        { CvssSeverity.Low, TimeSpan.FromDays(90) },           // 90 يوم
        { CvssSeverity.None, TimeSpan.FromDays(180) }          // 180 يوم
    };
}
```

## SQL Schema

```sql
CREATE SCHEMA [Security];

CREATE TABLE [Security].[Vulnerabilities] (
    [Id] INT IDENTITY(1,1) PRIMARY KEY,
    [VulnId] NVARCHAR(50) NOT NULL UNIQUE,
    [Title] NVARCHAR(500) NOT NULL,
    [Description] NVARCHAR(MAX) NOT NULL,
    [Type] NVARCHAR(30) NOT NULL,
    [Category] NVARCHAR(50) NOT NULL,
    [CveId] NVARCHAR(20) NULL,
    [CweId] NVARCHAR(20) NULL,
    [CvssScore] DECIMAL(3,1) NOT NULL,
    [Severity] NVARCHAR(10) NOT NULL,
    [IsExploitedInWild] BIT NOT NULL DEFAULT 0,
    [HasPublicExploit] BIT NOT NULL DEFAULT 0,
    [AssetId] INT NOT NULL,
    [Source] NVARCHAR(30) NOT NULL,
    [DiscoveredAt] DATETIME2 NOT NULL,
    [Status] NVARCHAR(20) NOT NULL DEFAULT 'New',
    [AssignedToId] INT NULL,
    [RemediationDueDate] DATETIME2 NULL,
    [RemediatedAt] DATETIME2 NULL,
    [IsSlaBreached] BIT NOT NULL DEFAULT 0,
    [CreatedAt] DATETIME2 NOT NULL DEFAULT GETUTCDATE(),
    INDEX IX_Severity_Status ([Severity], [Status]),
    INDEX IX_Asset ([AssetId])
);

CREATE TABLE [Security].[Incidents] (
    [Id] INT IDENTITY(1,1) PRIMARY KEY,
    [IncidentNumber] NVARCHAR(50) NOT NULL UNIQUE,
    [Title] NVARCHAR(500) NOT NULL,
    [Severity] NVARCHAR(10) NOT NULL,
    [Type] NVARCHAR(30) NOT NULL,
    [Status] NVARCHAR(20) NOT NULL DEFAULT 'Detected',
    [DataBreached] BIT NOT NULL DEFAULT 0,
    [DetectedAt] DATETIME2 NOT NULL,
    [ContainedAt] DATETIME2 NULL,
    [RecoveredAt] DATETIME2 NULL,
    [IncidentCommanderId] INT NULL,
    [CreatedAt] DATETIME2 NOT NULL DEFAULT GETUTCDATE()
);

CREATE TABLE [Security].[Assets] (
    [Id] INT IDENTITY(1,1) PRIMARY KEY,
    [Name] NVARCHAR(200) NOT NULL,
    [Type] NVARCHAR(30) NOT NULL,
    [IpAddress] NVARCHAR(45) NULL,
    [Hostname] NVARCHAR(200) NULL,
    [Criticality] NVARCHAR(10) NOT NULL DEFAULT 'Medium',
    [DepartmentId] INT NOT NULL,
    [LastScanDate] DATETIME2 NULL,
    [OpenVulnerabilities] INT NOT NULL DEFAULT 0
);

-- Dashboard Views
CREATE VIEW [Security].[vw_VulnDashboard] AS
SELECT 
    Severity,
    Status,
    COUNT(*) AS VulnCount,
    SUM(CASE WHEN IsSlaBreached = 1 THEN 1 ELSE 0 END) AS SlaBreachedCount,
    AVG(CvssScore) AS AvgCvssScore
FROM [Security].[Vulnerabilities]
GROUP BY Severity, Status;

CREATE VIEW [Security].[vw_CriticalOpenVulns] AS
SELECT v.*, a.Name AS AssetName, a.Criticality AS AssetCriticality
FROM [Security].[Vulnerabilities] v
JOIN [Security].[Assets] a ON a.Id = v.AssetId
WHERE v.Status NOT IN ('Remediated','Verified','Closed')
    AND (v.Severity IN ('Critical','High') OR v.IsExploitedInWild = 1)
ORDER BY v.CvssScore DESC, v.DiscoveredAt;
```

## NCA-ECC Controls Mapping

| ضابط NCA-ECC | الوصف | التنفيذ في المنصة |
|--------------|--------|------------------|
| 2-3-1 | إدارة الثغرات | فحص دوري + معالجة حسب SLA |
| 2-3-2 | اختبار الاختراق | تقارير Pentest + متابعة |
| 2-5-1 | إدارة الحوادث | سير عمل Incident Response |
| 2-7-1 | أمن التطبيقات | SAST + DAST + SCA |
| 2-9-1 | أمن الشبكات | Network scanning |
| 2-11-1 | التشفير | فحص Cryptographic practices |
