threat-modeling

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Threat Modeling

威胁建模

Systematic approach to identifying, quantifying, and addressing security threats in software systems.
一种用于识别、量化和解决软件系统中安全威胁的系统性方法。

When to Use This Skill

何时使用该技能

Keywords: threat modeling, STRIDE, DREAD, attack trees, security design, risk assessment, threat analysis, data flow diagram, trust boundary, attack surface, threat enumeration
Use this skill when:
  • Designing new systems or features
  • Conducting security architecture reviews
  • Identifying potential attack vectors
  • Prioritizing security investments
  • Documenting security assumptions
  • Integrating security into SDLC
  • Creating threat models as code
关键词: 威胁建模、STRIDE、DREAD、攻击树、安全设计、风险评估、威胁分析、数据流图(DFD)、信任边界、攻击面、威胁枚举
在以下场景使用该技能:
  • 设计新系统或功能时
  • 开展安全架构评审时
  • 识别潜在攻击向量时
  • 优先分配安全投入时
  • 记录安全假设时
  • 将安全集成到SDLC中时
  • 创建即代码化威胁模型时

Quick Decision Tree

快速决策树

  1. Starting a threat model? → Begin with Threat Modeling Process
  2. Identifying threats? → Use STRIDE methodology
  3. Prioritizing threats? → Apply DREAD scoring or Attack Trees
  4. Automating threat models? → See references/threat-modeling-tools.md
  5. Specific architecture patterns? → See Architecture-Specific Threats
  1. 启动威胁建模? → 从威胁建模流程开始
  2. 识别威胁? → 使用STRIDE方法论
  3. 优先处理威胁? → 应用DRED评分攻击树
  4. 自动化威胁模型? → 查看references/threat-modeling-tools.md
  5. 特定架构模式? → 查看特定架构威胁

Threat Modeling Process

威胁建模流程

text
┌─────────────────────────────────────────────────────────────────┐
│                    THREAT MODELING WORKFLOW                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. DECOMPOSE        2. IDENTIFY         3. PRIORITIZE          │
│  ┌──────────┐       ┌──────────┐        ┌──────────┐           │
│  │ System   │──────▶│ Threats  │───────▶│ Risks    │           │
│  │ Model    │       │ (STRIDE) │        │ (DREAD)  │           │
│  └──────────┘       └──────────┘        └──────────┘           │
│       │                   │                   │                  │
│       ▼                   ▼                   ▼                  │
│  ┌──────────┐       ┌──────────┐        ┌──────────┐           │
│  │ DFD      │       │ Attack   │        │ Counter- │           │
│  │ Trust    │       │ Trees    │        │ measures │           │
│  │ Boundary │       │ Patterns │        │ Backlog  │           │
│  └──────────┘       └──────────┘        └──────────┘           │
│                                                                  │
│  4. DOCUMENT ──────▶ 5. VALIDATE ──────▶ 6. ITERATE            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
text
┌─────────────────────────────────────────────────────────────────┐
│                    THREAT MODELING WORKFLOW                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. DECOMPOSE        2. IDENTIFY         3. PRIORITIZE          │
│  ┌──────────┐       ┌──────────┐        ┌──────────┐           │
│  │ System   │──────▶│ Threats  │───────▶│ Risks    │           │
│  │ Model    │       │ (STRIDE) │        │ (DREAD)  │           │
│  └──────────┘       └──────────┘        └──────────┘           │
│       │                   │                   │                  │
│       ▼                   ▼                   ▼                  │
│  ┌──────────┐       ┌──────────┐        ┌──────────┐           │
│  │ DFD      │       │ Attack   │        │ Counter- │           │
│  │ Trust    │       │ Trees    │        │ measures │           │
│  │ Boundary │       │ Patterns │        │ Backlog  │           │
│  └──────────┘       └──────────┘        └──────────┘           │
│                                                                  │
│  4. DOCUMENT ──────▶ 5. VALIDATE ──────▶ 6. ITERATE            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Step 1: System Decomposition

步骤1:系统分解

Create a Data Flow Diagram (DFD) with these elements:
ElementSymbolDescription
External EntityRectangleUsers, external systems
ProcessCircleCode that transforms data
Data StoreParallel linesDatabases, files, caches
Data FlowArrowData movement
Trust BoundaryDashed lineSecurity perimeter
csharp
// Example: E-commerce system decomposition
public enum ElementType
{
    ExternalEntity, Process, DataStore, DataFlow
}

/// <summary>Defines a security perimeter</summary>
public sealed record TrustBoundary(
    string Id,
    string Name,
    string Description,
    IReadOnlyList<string> Elements);  // IDs of contained elements

/// <summary>Data Flow Diagram element</summary>
public sealed record DfdElement
{
    public required string Id { get; init; }
    public required string Name { get; init; }
    public required ElementType ElementType { get; init; }
    public string? TrustBoundary { get; init; }
    public string Description { get; init; } = "";
}

/// <summary>Connection between elements</summary>
public sealed record DataFlow
{
    public required string Id { get; init; }
    public required string Source { get; init; }
    public required string Destination { get; init; }
    public required string DataType { get; init; }
    public required string Protocol { get; init; }
    public bool Encrypted { get; init; }
    public bool Authenticated { get; init; }
}

/// <summary>Complete system model for threat analysis</summary>
public sealed class SystemModel(string name)
{
    public string Name => name;
    private readonly Dictionary<string, DfdElement> _elements = new();
    private readonly List<DataFlow> _flows = [];
    private readonly List<TrustBoundary> _trustBoundaries = [];

    public IReadOnlyDictionary<string, DfdElement> Elements => _elements;
    public IReadOnlyList<DataFlow> Flows => _flows;
    public IReadOnlyList<TrustBoundary> TrustBoundaries => _trustBoundaries;

    public void AddElement(DfdElement element) => _elements[element.Id] = element;
    public void AddFlow(DataFlow flow) => _flows.Add(flow);
    public void AddTrustBoundary(TrustBoundary boundary) => _trustBoundaries.Add(boundary);

    /// <summary>Identify flows that cross trust boundaries - high-risk areas</summary>
    public IReadOnlyList<DataFlow> GetCrossBoundaryFlows()
    {
        var crossBoundary = new List<DataFlow>();
        foreach (var flow in _flows)
        {
            var sourceBoundary = _elements[flow.Source].TrustBoundary;
            var destBoundary = _elements[flow.Destination].TrustBoundary;
            if (sourceBoundary != destBoundary)
                crossBoundary.Add(flow);
        }
        return crossBoundary;
    }
}

// Example usage
var model = new SystemModel("E-Commerce Platform");

// Define elements
model.AddElement(new DfdElement
{
    Id = "user",
    Name = "Customer",
    ElementType = ElementType.ExternalEntity,
    TrustBoundary = "internet",
    Description = "End user accessing via browser"
});

model.AddElement(new DfdElement
{
    Id = "web_app",
    Name = "Web Application",
    ElementType = ElementType.Process,
    TrustBoundary = "dmz",
    Description = "Frontend web server"
});

model.AddElement(new DfdElement
{
    Id = "api",
    Name = "API Gateway",
    ElementType = ElementType.Process,
    TrustBoundary = "internal",
    Description = "Backend API services"
});

model.AddElement(new DfdElement
{
    Id = "db",
    Name = "Database",
    ElementType = ElementType.DataStore,
    TrustBoundary = "internal",
    Description = "Customer and order data"
});

// Define flows
model.AddFlow(new DataFlow
{
    Id = "f1",
    Source = "user",
    Destination = "web_app",
    DataType = "HTTP Request",
    Protocol = "HTTPS",
    Encrypted = true,
    Authenticated = false
});

// Find high-risk flows
var riskyFlows = model.GetCrossBoundaryFlows();
创建包含以下元素的数据流图(DFD):
元素符号描述
外部实体矩形用户、外部系统
流程圆形转换数据的代码
数据存储平行线数据库、文件、缓存
数据流箭头数据移动
信任边界虚线安全边界
csharp
// Example: E-commerce system decomposition
public enum ElementType
{
    ExternalEntity, Process, DataStore, DataFlow
}

/// <summary>Defines a security perimeter</summary>
public sealed record TrustBoundary(
    string Id,
    string Name,
    string Description,
    IReadOnlyList<string> Elements);  // IDs of contained elements

/// <summary>Data Flow Diagram element</summary>
public sealed record DfdElement
{
    public required string Id { get; init; }
    public required string Name { get; init; }
    public required ElementType ElementType { get; init; }
    public string? TrustBoundary { get; init; }
    public string Description { get; init; } = "";
}

/// <summary>Connection between elements</summary>
public sealed record DataFlow
{
    public required string Id { get; init; }
    public required string Source { get; init; }
    public required string Destination { get; init; }
    public required string DataType { get; init; }
    public required string Protocol { get; init; }
    public bool Encrypted { get; init; }
    public bool Authenticated { get; init; }
}

/// <summary>Complete system model for threat analysis</summary>
public sealed class SystemModel(string name)
{
    public string Name => name;
    private readonly Dictionary<string, DfdElement> _elements = new();
    private readonly List<DataFlow> _flows = [];
    private readonly List<TrustBoundary> _trustBoundaries = [];

    public IReadOnlyDictionary<string, DfdElement> Elements => _elements;
    public IReadOnlyList<DataFlow> Flows => _flows;
    public IReadOnlyList<TrustBoundary> TrustBoundaries => _trustBoundaries;

    public void AddElement(DfdElement element) => _elements[element.Id] = element;
    public void AddFlow(DataFlow flow) => _flows.Add(flow);
    public void AddTrustBoundary(TrustBoundary boundary) => _trustBoundaries.Add(boundary);

    /// <summary>Identify flows that cross trust boundaries - high-risk areas</summary>
    public IReadOnlyList<DataFlow> GetCrossBoundaryFlows()
    {
        var crossBoundary = new List<DataFlow>();
        foreach (var flow in _flows)
        {
            var sourceBoundary = _elements[flow.Source].TrustBoundary;
            var destBoundary = _elements[flow.Destination].TrustBoundary;
            if (sourceBoundary != destBoundary)
                crossBoundary.Add(flow);
        }
        return crossBoundary;
    }
}

// Example usage
var model = new SystemModel("E-Commerce Platform");

// Define elements
model.AddElement(new DfdElement
{
    Id = "user",
    Name = "Customer",
    ElementType = ElementType.ExternalEntity,
    TrustBoundary = "internet",
    Description = "End user accessing via browser"
});

model.AddElement(new DfdElement
{
    Id = "web_app",
    Name = "Web Application",
    ElementType = ElementType.Process,
    TrustBoundary = "dmz",
    Description = "Frontend web server"
});

model.AddElement(new DfdElement
{
    Id = "api",
    Name = "API Gateway",
    ElementType = ElementType.Process,
    TrustBoundary = "internal",
    Description = "Backend API services"
});

model.AddElement(new DfdElement
{
    Id = "db",
    Name = "Database",
    ElementType = ElementType.DataStore,
    TrustBoundary = "internal",
    Description = "Customer and order data"
});

// Define flows
model.AddFlow(new DataFlow
{
    Id = "f1",
    Source = "user",
    Destination = "web_app",
    DataType = "HTTP Request",
    Protocol = "HTTPS",
    Encrypted = true,
    Authenticated = false
});

// Find high-risk flows
var riskyFlows = model.GetCrossBoundaryFlows();

STRIDE Methodology

STRIDE方法论

STRIDE is a threat classification framework for systematic threat identification:
CategoryThreatSecurity PropertyExample
SpoofingImpersonating someone/somethingAuthenticationStolen credentials, session hijacking
TamperingModifying data or codeIntegritySQL injection, file modification
RepudiationDenying actionsNon-repudiationMissing audit logs
Information DisclosureExposing informationConfidentialityData breach, verbose errors
Denial of ServiceDisrupting availabilityAvailabilityResource exhaustion, DDoS
Elevation of PrivilegeGaining unauthorized accessAuthorizationPrivilege escalation, IDOR
STRIDE是用于系统性威胁识别的威胁分类框架:
类别威胁安全属性示例
Spoofing(冒充)冒充他人/物身份认证凭证被盗、会话劫持
Tampering(篡改)修改数据或代码完整性SQL注入、文件篡改
Repudiation(抵赖)否认操作不可抵赖性缺失审计日志
Information Disclosure(信息泄露)泄露信息保密性数据泄露、详细错误信息暴露
Denial of Service(拒绝服务)破坏可用性可用性资源耗尽、DDoS攻击
Elevation of Privilege(权限提升)获取未授权访问权限授权权限提升、IDOR(不安全的直接对象引用)

STRIDE-per-Element Analysis

按元素应用STRIDE分析

Apply STRIDE to each DFD element:
csharp
using System.Collections.Frozen;

public enum StrideCategory
{
    Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege
}

/// <summary>Which STRIDE categories apply to which element types</summary>
public static class StrideApplicability
{
    public static readonly FrozenDictionary<ElementType, StrideCategory[]> Map =
        new Dictionary<ElementType, StrideCategory[]>
        {
            [ElementType.ExternalEntity] =
                [StrideCategory.Spoofing, StrideCategory.Repudiation],
            [ElementType.Process] =
                [StrideCategory.Spoofing, StrideCategory.Tampering, StrideCategory.Repudiation,
                 StrideCategory.InformationDisclosure, StrideCategory.DenialOfService,
                 StrideCategory.ElevationOfPrivilege],
            [ElementType.DataStore] =
                [StrideCategory.Tampering, StrideCategory.Repudiation,
                 StrideCategory.InformationDisclosure, StrideCategory.DenialOfService],
            [ElementType.DataFlow] =
                [StrideCategory.Tampering, StrideCategory.InformationDisclosure,
                 StrideCategory.DenialOfService]
        }.ToFrozenDictionary();
}

/// <summary>Identified threat</summary>
public sealed record Threat
{
    public required string Id { get; init; }
    public required StrideCategory Category { get; init; }
    public required string ElementId { get; init; }
    public required string Title { get; init; }
    public required string Description { get; init; }
    public required string AttackVector { get; init; }
    public string Impact { get; init; } = "";
    public string Likelihood { get; init; } = "Medium";
    public IReadOnlyList<string> Mitigations { get; init; } = [];
}

/// <summary>Threat template for generation</summary>
public sealed record ThreatTemplate(
    string TitleFormat, string DescriptionFormat, string AttackVector, string[] Mitigations);

/// <summary>Systematic STRIDE threat identification</summary>
public sealed class StrideAnalyzer(SystemModel model)
{
    private readonly List<Threat> _threats = [];
    private int _threatCounter;

    private static readonly Dictionary<(ElementType, StrideCategory), ThreatTemplate> Templates = new()
    {
        [(ElementType.Process, StrideCategory.Spoofing)] = new(
            "Spoofing of {0}",
            "Attacker impersonates {0} to gain unauthorized access",
            "Credential theft, session hijacking, certificate forgery",
            ["Strong authentication", "Certificate pinning", "Session management"]),
        [(ElementType.Process, StrideCategory.Tampering)] = new(
            "Tampering with {0}",
            "Attacker modifies data processed by {0}",
            "Input manipulation, code injection, memory corruption",
            ["Input validation", "Integrity checks", "Code signing"]),
        [(ElementType.DataStore, StrideCategory.InformationDisclosure)] = new(
            "Information disclosure from {0}",
            "Sensitive data exposed from {0}",
            "SQL injection, misconfiguration, backup exposure",
            ["Encryption at rest", "Access controls", "Data masking"])
    };

    /// <summary>Perform STRIDE analysis on all elements</summary>
    public IReadOnlyList<Threat> Analyze()
    {
        // Analyze elements
        foreach (var element in model.Elements.Values)
        {
            if (StrideApplicability.Map.TryGetValue(element.ElementType, out var categories))
            {
                foreach (var category in categories)
                    _threats.AddRange(IdentifyThreats(element, category));
            }
        }

        // Analyze data flows
        if (StrideApplicability.Map.TryGetValue(ElementType.DataFlow, out var flowCategories))
        {
            foreach (var flow in model.Flows)
            {
                foreach (var category in flowCategories)
                    _threats.AddRange(IdentifyFlowThreats(flow, category));
            }
        }

        return _threats;
    }

    private IEnumerable<Threat> IdentifyThreats(DfdElement element, StrideCategory category)
    {
        var key = (element.ElementType, category);
        if (!Templates.TryGetValue(key, out var template))
            yield break;

        _threatCounter++;
        yield return new Threat
        {
            Id = $"T{_threatCounter:D3}",
            Category = category,
            ElementId = element.Id,
            Title = string.Format(template.TitleFormat, element.Name),
            Description = string.Format(template.DescriptionFormat, element.Name),
            AttackVector = template.AttackVector,
            Mitigations = template.Mitigations
        };
    }

    private IEnumerable<Threat> IdentifyFlowThreats(DataFlow flow, StrideCategory category)
    {
        if (category == StrideCategory.InformationDisclosure && !flow.Encrypted)
        {
            _threatCounter++;
            yield return new Threat
            {
                Id = $"T{_threatCounter:D3}",
                Category = category,
                ElementId = flow.Id,
                Title = $"Unencrypted data flow: {flow.Source} -> {flow.Destination}",
                Description = $"Data ({flow.DataType}) transmitted without encryption",
                AttackVector = "Network sniffing, man-in-the-middle",
                Impact = "High - Data exposure",
                Mitigations = ["Enable TLS", "Use VPN", "Encrypt at application layer"]
            };
        }

        if (category == StrideCategory.Tampering && !flow.Authenticated)
        {
            _threatCounter++;
            yield return new Threat
            {
                Id = $"T{_threatCounter:D3}",
                Category = category,
                ElementId = flow.Id,
                Title = $"Unauthenticated data flow: {flow.Source} -> {flow.Destination}",
                Description = "Data flow lacks authentication - source cannot be verified",
                AttackVector = "Message injection, replay attacks",
                Impact = "Medium - Data integrity compromise",
                Mitigations = ["Mutual TLS", "Message signing", "API authentication"]
            };
        }
    }
}
For detailed STRIDE analysis with examples, see references/stride-methodology.md.
对每个DFD元素应用STRIDE:
csharp
using System.Collections.Frozen;

public enum StrideCategory
{
    Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege
}

/// <summary>Which STRIDE categories apply to which element types</summary>
public static class StrideApplicability
{
    public static readonly FrozenDictionary<ElementType, StrideCategory[]> Map =
        new Dictionary<ElementType, StrideCategory[]>
        {
            [ElementType.ExternalEntity] =
                [StrideCategory.Spoofing, StrideCategory.Repudiation],
            [ElementType.Process] =
                [StrideCategory.Spoofing, StrideCategory.Tampering, StrideCategory.Repudiation,
                 StrideCategory.InformationDisclosure, StrideCategory.DenialOfService,
                 StrideCategory.ElevationOfPrivilege],
            [ElementType.DataStore] =
                [StrideCategory.Tampering, StrideCategory.Repudiation,
                 StrideCategory.InformationDisclosure, StrideCategory.DenialOfService],
            [ElementType.DataFlow] =
                [StrideCategory.Tampering, StrideCategory.InformationDisclosure,
                 StrideCategory.DenialOfService]
        }.ToFrozenDictionary();
}

/// <summary>Identified threat</summary>
public sealed record Threat
{
    public required string Id { get; init; }
    public required StrideCategory Category { get; init; }
    public required string ElementId { get; init; }
    public required string Title { get; init; }
    public required string Description { get; init; }
    public required string AttackVector { get; init; }
    public string Impact { get; init; } = "";
    public string Likelihood { get; init; } = "Medium";
    public IReadOnlyList<string> Mitigations { get; init; } = [];
}

/// <summary>Threat template for generation</summary>
public sealed record ThreatTemplate(
    string TitleFormat, string DescriptionFormat, string AttackVector, string[] Mitigations);

/// <summary>Systematic STRIDE threat identification</summary>
public sealed class StrideAnalyzer(SystemModel model)
{
    private readonly List<Threat> _threats = [];
    private int _threatCounter;

    private static readonly Dictionary<(ElementType, StrideCategory), ThreatTemplate> Templates = new()
    {
        [(ElementType.Process, StrideCategory.Spoofing)] = new(
            "Spoofing of {0}",
            "Attacker impersonates {0} to gain unauthorized access",
            "Credential theft, session hijacking, certificate forgery",
            ["Strong authentication", "Certificate pinning", "Session management"]),
        [(ElementType.Process, StrideCategory.Tampering)] = new(
            "Tampering with {0}",
            "Attacker modifies data processed by {0}",
            "Input manipulation, code injection, memory corruption",
            ["Input validation", "Integrity checks", "Code signing"]),
        [(ElementType.DataStore, StrideCategory.InformationDisclosure)] = new(
            "Information disclosure from {0}",
            "Sensitive data exposed from {0}",
            "SQL injection, misconfiguration, backup exposure",
            ["Encryption at rest", "Access controls", "Data masking"])
    };

    /// <summary>Perform STRIDE analysis on all elements</summary>
    public IReadOnlyList<Threat> Analyze()
    {
        // Analyze elements
        foreach (var element in model.Elements.Values)
        {
            if (StrideApplicability.Map.TryGetValue(element.ElementType, out var categories))
            {
                foreach (var category in categories)
                    _threats.AddRange(IdentifyThreats(element, category));
            }
        }

        // Analyze data flows
        if (StrideApplicability.Map.TryGetValue(ElementType.DataFlow, out var flowCategories))
        {
            foreach (var flow in model.Flows)
            {
                foreach (var category in flowCategories)
                    _threats.AddRange(IdentifyFlowThreats(flow, category));
            }
        }

        return _threats;
    }

    private IEnumerable<Threat> IdentifyThreats(DfdElement element, StrideCategory category)
    {
        var key = (element.ElementType, category);
        if (!Templates.TryGetValue(key, out var template))
            yield break;

        _threatCounter++;
        yield return new Threat
        {
            Id = $"T{_threatCounter:D3}",
            Category = category,
            ElementId = element.Id,
            Title = string.Format(template.TitleFormat, element.Name),
            Description = string.Format(template.DescriptionFormat, element.Name),
            AttackVector = template.AttackVector,
            Mitigations = template.Mitigations
        };
    }

    private IEnumerable<Threat> IdentifyFlowThreats(DataFlow flow, StrideCategory category)
    {
        if (category == StrideCategory.InformationDisclosure && !flow.Encrypted)
        {
            _threatCounter++;
            yield return new Threat
            {
                Id = $"T{_threatCounter:D3}",
                Category = category,
                ElementId = flow.Id,
                Title = $"Unencrypted data flow: {flow.Source} -> {flow.Destination}",
                Description = $"Data ({flow.DataType}) transmitted without encryption",
                AttackVector = "Network sniffing, man-in-the-middle",
                Impact = "High - Data exposure",
                Mitigations = ["Enable TLS", "Use VPN", "Encrypt at application layer"]
            };
        }

        if (category == StrideCategory.Tampering && !flow.Authenticated)
        {
            _threatCounter++;
            yield return new Threat
            {
                Id = $"T{_threatCounter:D3}",
                Category = category,
                ElementId = flow.Id,
                Title = $"Unauthenticated data flow: {flow.Source} -> {flow.Destination}",
                Description = "Data flow lacks authentication - source cannot be verified",
                AttackVector = "Message injection, replay attacks",
                Impact = "Medium - Data integrity compromise",
                Mitigations = ["Mutual TLS", "Message signing", "API authentication"]
            };
        }
    }
}
有关带示例的详细STRIDE分析,请查看references/stride-methodology.md

DREAD Risk Scoring

DREAD风险评分

DREAD provides quantitative risk assessment for prioritization:
FactorDescriptionScale
DamageImpact if exploited1-10
ReproducibilityEase of reproducing attack1-10
ExploitabilityEffort required to exploit1-10
Affected UsersScope of impact1-10
DiscoverabilityLikelihood of finding vulnerability1-10
csharp
/// <summary>DREAD risk scoring</summary>
public readonly struct DreadScore
{
    public int Damage { get; }           // 1-10
    public int Reproducibility { get; }  // 1-10
    public int Exploitability { get; }   // 1-10
    public int AffectedUsers { get; }    // 1-10
    public int Discoverability { get; }  // 1-10

    public DreadScore(int damage, int reproducibility, int exploitability,
                      int affectedUsers, int discoverability)
    {
        ValidateRange(damage, nameof(damage));
        ValidateRange(reproducibility, nameof(reproducibility));
        ValidateRange(exploitability, nameof(exploitability));
        ValidateRange(affectedUsers, nameof(affectedUsers));
        ValidateRange(discoverability, nameof(discoverability));

        Damage = damage;
        Reproducibility = reproducibility;
        Exploitability = exploitability;
        AffectedUsers = affectedUsers;
        Discoverability = discoverability;
    }

    private static void ValidateRange(int value, string name)
    {
        if (value is < 1 or > 10)
            throw new ArgumentOutOfRangeException(name, $"{name} must be between 1-10");
    }

    /// <summary>Calculate average DREAD score</summary>
    public double Total => (Damage + Reproducibility + Exploitability +
                           AffectedUsers + Discoverability) / 5.0;

    /// <summary>Categorize risk level</summary>
    public string RiskLevel => Total switch
    {
        >= 8 => "Critical",
        >= 6 => "High",
        >= 4 => "Medium",
        _ => "Low"
    };
}

/// <summary>Prioritize threats using DREAD scoring</summary>
public sealed class ThreatPrioritizer
{
    private readonly List<(Threat Threat, DreadScore Score)> _scoredThreats = [];

    public void ScoreThreat(Threat threat, DreadScore score) =>
        _scoredThreats.Add((threat, score));

    /// <summary>Return threats sorted by risk (highest first)</summary>
    public IReadOnlyList<(Threat Threat, DreadScore Score)> GetPrioritizedList() =>
        _scoredThreats.OrderByDescending(x => x.Score.Total).ToList();

    /// <summary>Generate risk matrix summary</summary>
    public Dictionary<string, List<string>> GenerateRiskMatrix()
    {
        var matrix = new Dictionary<string, List<string>>
        {
            ["Critical"] = [], ["High"] = [], ["Medium"] = [], ["Low"] = []
        };
        foreach (var (threat, score) in _scoredThreats)
            matrix[score.RiskLevel].Add(threat.Id);
        return matrix;
    }
}

// Example scoring
var sqlInjectionScore = new DreadScore(
    damage: 9,           // Full database compromise
    reproducibility: 8,  // Easily reproducible with tools
    exploitability: 7,   // Well-known techniques
    affectedUsers: 10,   // All users potentially affected
    discoverability: 6   // Requires testing to find
);

Console.WriteLine($"Risk Score: {sqlInjectionScore.Total}");    // 8.0
Console.WriteLine($"Risk Level: {sqlInjectionScore.RiskLevel}"); // Critical
DREAD提供用于优先级排序的量化风险评估:
因素描述评分范围
Damage(损害)被利用后的影响1-10
Reproducibility(可复现性)重现攻击的难易程度1-10
Exploitability(可利用性)利用漏洞所需的工作量1-10
Affected Users(受影响用户)影响范围1-10
Discoverability(可发现性)发现漏洞的可能性1-10
csharp
/// <summary>DREAD risk scoring</summary>
public readonly struct DreadScore
{
    public int Damage { get; }           // 1-10
    public int Reproducibility { get; }  // 1-10
    public int Exploitability { get; }   // 1-10
    public int AffectedUsers { get; }    // 1-10
    public int Discoverability { get; }  // 1-10

    public DreadScore(int damage, int reproducibility, int exploitability,
                      int affectedUsers, int discoverability)
    {
        ValidateRange(damage, nameof(damage));
        ValidateRange(reproducibility, nameof(reproducibility));
        ValidateRange(exploitability, nameof(exploitability));
        ValidateRange(affectedUsers, nameof(affectedUsers));
        ValidateRange(discoverability, nameof(discoverability));

        Damage = damage;
        Reproducibility = reproducibility;
        Exploitability = exploitability;
        AffectedUsers = affectedUsers;
        Discoverability = discoverability;
    }

    private static void ValidateRange(int value, string name)
    {
        if (value is < 1 or > 10)
            throw new ArgumentOutOfRangeException(name, $"{name} must be between 1-10");
    }

    /// <summary>Calculate average DREAD score</summary>
    public double Total => (Damage + Reproducibility + Exploitability +
                           AffectedUsers + Discoverability) / 5.0;

    /// <summary>Categorize risk level</summary>
    public string RiskLevel => Total switch
    {
        >= 8 => "Critical",
        >= 6 => "High",
        >= 4 => "Medium",
        _ => "Low"
    };
}

/// <summary>Prioritize threats using DREAD scoring</summary>
public sealed class ThreatPrioritizer
{
    private readonly List<(Threat Threat, DreadScore Score)> _scoredThreats = [];

    public void ScoreThreat(Threat threat, DreadScore score) =>
        _scoredThreats.Add((threat, score));

    /// <summary>Return threats sorted by risk (highest first)</summary>
    public IReadOnlyList<(Threat Threat, DreadScore Score)> GetPrioritizedList() =>
        _scoredThreats.OrderByDescending(x => x.Score.Total).ToList();

    /// <summary>Generate risk matrix summary</summary>
    public Dictionary<string, List<string>> GenerateRiskMatrix()
    {
        var matrix = new Dictionary<string, List<string>>
        {
            ["Critical"] = [], ["High"] = [], ["Medium"] = [], ["Low"] = []
        };
        foreach (var (threat, score) in _scoredThreats)
            matrix[score.RiskLevel].Add(threat.Id);
        return matrix;
    }
}

// Example scoring
var sqlInjectionScore = new DreadScore(
    damage: 9,           // Full database compromise
    reproducibility: 8,  // Easily reproducible with tools
    exploitability: 7,   // Well-known techniques
    affectedUsers: 10,   // All users potentially affected
    discoverability: 6   // Requires testing to find
);

Console.WriteLine($"Risk Score: {sqlInjectionScore.Total}");    // 8.0
Console.WriteLine($"Risk Level: {sqlInjectionScore.RiskLevel}"); // Critical

Alternative: CVSS-Based Scoring

替代方案:基于CVSS的评分

For compatibility with industry standards, map to CVSS:
csharp
/// <summary>CVSS 3.1 Base Score components</summary>
public sealed record CvssVector
{
    public required string AttackVector { get; init; }       // N, A, L, P
    public required string AttackComplexity { get; init; }   // L, H
    public required string PrivilegesRequired { get; init; } // N, L, H
    public required string UserInteraction { get; init; }    // N, R
    public required string Scope { get; init; }              // U, C
    public required string Confidentiality { get; init; }    // N, L, H
    public required string Integrity { get; init; }          // N, L, H
    public required string Availability { get; init; }       // N, L, H

    public string ToVectorString() =>
        $"CVSS:3.1/AV:{AttackVector}/AC:{AttackComplexity}/" +
        $"PR:{PrivilegesRequired}/UI:{UserInteraction}/" +
        $"S:{Scope}/C:{Confidentiality}/I:{Integrity}/A:{Availability}";
}
为了兼容行业标准,可映射到CVSS:
csharp
/// <summary>CVSS 3.1 Base Score components</summary>
public sealed record CvssVector
{
    public required string AttackVector { get; init; }       // N, A, L, P
    public required string AttackComplexity { get; init; }   // L, H
    public required string PrivilegesRequired { get; init; } // N, L, H
    public required string UserInteraction { get; init; }    // N, R
    public required string Scope { get; init; }              // U, C
    public required string Confidentiality { get; init; }    // N, L, H
    public required string Integrity { get; init; }          // N, L, H
    public required string Availability { get; init; }       // N, L, H

    public string ToVectorString() =>
        $"CVSS:3.1/AV:{AttackVector}/AC:{AttackComplexity}/" +
        $"PR:{PrivilegesRequired}/UI:{UserInteraction}/" +
        $"S:{Scope}/C:{Confidentiality}/I:{Integrity}/A:{Availability}";
}

Attack Trees

攻击树

Attack trees visualize how an attacker might achieve a goal:
text
                    ┌─────────────────────┐
                    │ Steal Customer Data │ (Goal)
                    └─────────────────────┘
              ┌───────────────┼───────────────┐
              │               │               │
              ▼               ▼               ▼
      ┌───────────┐   ┌───────────┐   ┌───────────┐
      │ SQL       │   │ Phishing  │   │ Insider   │
      │ Injection │   │ Attack    │   │ Threat    │
      │ [OR]      │   │ [OR]      │   │ [OR]      │
      └───────────┘   └───────────┘   └───────────┘
            │               │               │
      ┌─────┴─────┐   ┌─────┴─────┐   ┌─────┴─────┐
      │           │   │           │   │           │
      ▼           ▼   ▼           ▼   ▼           ▼
  ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
  │Find   │ │Exploit│ │Send   │ │Harvest│ │Bribe  │ │Access │
  │Vuln   │ │Input  │ │Fake   │ │Creds  │ │Staff  │ │After  │
  │Endpoint│ │Field  │ │Emails │ │Site   │ │       │ │Hours  │
  │[AND]  │ │[AND]  │ │[AND]  │ │[AND]  │ │[OR]   │ │[OR]   │
  └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘
csharp
public enum NodeOperator
{
    And,  // All children must succeed
    Or    // Any child can succeed
}

/// <summary>Node in attack tree</summary>
public sealed class AttackNode
{
    public required string Id { get; init; }
    public required string Description { get; init; }
    public NodeOperator Operator { get; init; } = NodeOperator.Or;
    public double Cost { get; init; }           // Estimated attack cost
    public double Probability { get; init; } = 0.5;  // Success probability
    public string SkillRequired { get; init; } = "Medium";
    public List<AttackNode> Children { get; } = [];
    public List<string> Countermeasures { get; init; } = [];

    public void AddChild(AttackNode child) => Children.Add(child);

    /// <summary>Calculate probability based on operator and children</summary>
    public double CalculateProbability()
    {
        if (Children.Count == 0)
            return Probability;

        var childProbs = Children.Select(c => c.CalculateProbability()).ToList();

        if (Operator == NodeOperator.And)
        {
            // All must succeed - multiply probabilities
            return childProbs.Aggregate(1.0, (acc, p) => acc * p);
        }
        else // OR
        {
            // Any can succeed - 1 - (all fail)
            return 1.0 - childProbs.Aggregate(1.0, (acc, p) => acc * (1 - p));
        }
    }

    /// <summary>Calculate minimum attack cost</summary>
    public double CalculateMinCost()
    {
        if (Children.Count == 0)
            return Cost;

        var childCosts = Children.Select(c => c.CalculateMinCost()).ToList();

        if (Operator == NodeOperator.And)
        {
            // Must complete all - sum costs
            return childCosts.Sum();
        }
        else // OR
        {
            // Choose cheapest path
            return childCosts.Min();
        }
    }
}

/// <summary>Analyze attack trees for risk assessment</summary>
public sealed class AttackTreeAnalyzer(AttackNode root)
{
    /// <summary>Find the least expensive attack path</summary>
    public IReadOnlyList<AttackNode> FindCheapestPath() => FindPath(root, minimizeCost: true);

    /// <summary>Find the most probable attack path</summary>
    public IReadOnlyList<AttackNode> FindMostLikelyPath() => FindPath(root, minimizeCost: false);

    private static List<AttackNode> FindPath(AttackNode node, bool minimizeCost)
    {
        var path = new List<AttackNode> { node };

        if (node.Children.Count == 0)
            return path;

        if (node.Operator == NodeOperator.And)
        {
            // Must traverse all children
            foreach (var child in node.Children)
                path.AddRange(FindPath(child, minimizeCost));
        }
        else // OR
        {
            // Choose best child
            var bestChild = minimizeCost
                ? node.Children.MinBy(c => c.CalculateMinCost())!
                : node.Children.MaxBy(c => c.CalculateProbability())!;
            path.AddRange(FindPath(bestChild, minimizeCost));
        }

        return path;
    }

    /// <summary>Collect all countermeasures from tree</summary>
    public HashSet<string> GetAllCountermeasures() => CollectCountermeasures(root);

    private static HashSet<string> CollectCountermeasures(AttackNode node)
    {
        var measures = new HashSet<string>(node.Countermeasures);
        foreach (var child in node.Children)
            measures.UnionWith(CollectCountermeasures(child));
        return measures;
    }
}

// Example: Build attack tree
var rootNode = new AttackNode
{
    Id = "goal",
    Description = "Steal Customer Data",
    Operator = NodeOperator.Or
};

var sqlInjection = new AttackNode
{
    Id = "sqli",
    Description = "SQL Injection Attack",
    Operator = NodeOperator.And,
    Countermeasures = ["Parameterized queries", "WAF", "Input validation"]
};

sqlInjection.AddChild(new AttackNode
{
    Id = "find_vuln",
    Description = "Find vulnerable endpoint",
    Cost = 100,
    Probability = 0.7,
    SkillRequired = "Medium"
});

sqlInjection.AddChild(new AttackNode
{
    Id = "exploit",
    Description = "Exploit injection point",
    Cost = 200,
    Probability = 0.8,
    SkillRequired = "High"
});

rootNode.AddChild(sqlInjection);

// Analyze
var analyzer = new AttackTreeAnalyzer(rootNode);
Console.WriteLine($"Overall attack probability: {rootNode.CalculateProbability():P2}");
Console.WriteLine($"Minimum attack cost: ${rootNode.CalculateMinCost()}");
Console.WriteLine($"Countermeasures needed: {string.Join(", ", analyzer.GetAllCountermeasures())}");
攻击树可视化攻击者达成目标的可能路径:
text
                    ┌─────────────────────┐
                    │ Steal Customer Data │ (Goal)
                    └─────────────────────┘
              ┌───────────────┼───────────────┐
              │               │               │
              ▼               ▼               ▼
      ┌───────────┐   ┌───────────┐   ┌───────────┐
      │ SQL       │   │ Phishing  │   │ Insider   │
      │ Injection │   │ Attack    │   │ Threat    │
      │ [OR]      │   │ [OR]      │   │ [OR]      │
      └───────────┘   └───────────┘   └───────────┘
            │               │               │
      ┌─────┴─────┐   ┌─────┴─────┐   ┌─────┴─────┐
      │           │   │           │   │           │
      ▼           ▼   ▼           ▼   ▼           ▼
  ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
  │Find   │ │Exploit│ │Send   │ │Harvest│ │Bribe  │ │Access │
  │Vuln   │ │Input  │ │Fake   │ │Creds  │ │Staff  │ │After  │
  │Endpoint│ │Field  │ │Emails │ │Site   │ │       │ │Hours  │
  │[AND]  │ │[AND]  │ │[AND]  │ │[AND]  │ │[OR]   │ │[OR]   │
  └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘
csharp
public enum NodeOperator
{
    And,  // All children must succeed
    Or    // Any child can succeed
}

/// <summary>Node in attack tree</summary>
public sealed class AttackNode
{
    public required string Id { get; init; }
    public required string Description { get; init; }
    public NodeOperator Operator { get; init; } = NodeOperator.Or;
    public double Cost { get; init; }           // Estimated attack cost
    public double Probability { get; init; } = 0.5;  // Success probability
    public string SkillRequired { get; init; } = "Medium";
    public List<AttackNode> Children { get; } = [];
    public List<string> Countermeasures { get; init; } = [];

    public void AddChild(AttackNode child) => Children.Add(child);

    /// <summary>Calculate probability based on operator and children</summary>
    public double CalculateProbability()
    {
        if (Children.Count == 0)
            return Probability;

        var childProbs = Children.Select(c => c.CalculateProbability()).ToList();

        if (Operator == NodeOperator.And)
        {
            // All must succeed - multiply probabilities
            return childProbs.Aggregate(1.0, (acc, p) => acc * p);
        }
        else // OR
        {
            // Any can succeed - 1 - (all fail)
            return 1.0 - childProbs.Aggregate(1.0, (acc, p) => acc * (1 - p));
        }
    }

    /// <summary>Calculate minimum attack cost</summary>
    public double CalculateMinCost()
    {
        if (Children.Count == 0)
            return Cost;

        var childCosts = Children.Select(c => c.CalculateMinCost()).ToList();

        if (Operator == NodeOperator.And)
        {
            // Must complete all - sum costs
            return childCosts.Sum();
        }
        else // OR
        {
            // Choose cheapest path
            return childCosts.Min();
        }
    }
}

/// <summary>Analyze attack trees for risk assessment</summary>
public sealed class AttackTreeAnalyzer(AttackNode root)
{
    /// <summary>Find the least expensive attack path</summary>
    public IReadOnlyList<AttackNode> FindCheapestPath() => FindPath(root, minimizeCost: true);

    /// <summary>Find the most probable attack path</summary>
    public IReadOnlyList<AttackNode> FindMostLikelyPath() => FindPath(root, minimizeCost: false);

    private static List<AttackNode> FindPath(AttackNode node, bool minimizeCost)
    {
        var path = new List<AttackNode> { node };

        if (node.Children.Count == 0)
            return path;

        if (node.Operator == NodeOperator.And)
        {
            // Must traverse all children
            foreach (var child in node.Children)
                path.AddRange(FindPath(child, minimizeCost));
        }
        else // OR
        {
            // Choose best child
            var bestChild = minimizeCost
                ? node.Children.MinBy(c => c.CalculateMinCost())!
                : node.Children.MaxBy(c => c.CalculateProbability())!;
            path.AddRange(FindPath(bestChild, minimizeCost));
        }

        return path;
    }

    /// <summary>Collect all countermeasures from tree</summary>
    public HashSet<string> GetAllCountermeasures() => CollectCountermeasures(root);

    private static HashSet<string> CollectCountermeasures(AttackNode node)
    {
        var measures = new HashSet<string>(node.Countermeasures);
        foreach (var child in node.Children)
            measures.UnionWith(CollectCountermeasures(child));
        return measures;
    }
}

// Example: Build attack tree
var rootNode = new AttackNode
{
    Id = "goal",
    Description = "Steal Customer Data",
    Operator = NodeOperator.Or
};

var sqlInjection = new AttackNode
{
    Id = "sqli",
    Description = "SQL Injection Attack",
    Operator = NodeOperator.And,
    Countermeasures = ["Parameterized queries", "WAF", "Input validation"]
};

sqlInjection.AddChild(new AttackNode
{
    Id = "find_vuln",
    Description = "Find vulnerable endpoint",
    Cost = 100,
    Probability = 0.7,
    SkillRequired = "Medium"
});

sqlInjection.AddChild(new AttackNode
{
    Id = "exploit",
    Description = "Exploit injection point",
    Cost = 200,
    Probability = 0.8,
    SkillRequired = "High"
});

rootNode.AddChild(sqlInjection);

// Analyze
var analyzer = new AttackTreeAnalyzer(rootNode);
Console.WriteLine($"Overall attack probability: {rootNode.CalculateProbability():P2}");
Console.WriteLine($"Minimum attack cost: ${rootNode.CalculateMinCost()}");
Console.WriteLine($"Countermeasures needed: {string.Join(", ", analyzer.GetAllCountermeasures())}");

Architecture-Specific Threats

特定架构威胁

Microservices Architecture

微服务架构

ComponentKey ThreatsMitigations
API GatewayDDoS, injection, auth bypassRate limiting, WAF, OAuth
Service MeshmTLS bypass, sidecar compromiseCertificate rotation, network policies
Message QueueMessage tampering, replayMessage signing, idempotency
Service DiscoveryRegistry poisoningSecure registration, health checks
组件关键威胁缓解措施
API网关DDoS、注入、认证绕过速率限制、WAF、OAuth
服务网格mTLS绕过、Sidecar组件被攻陷证书轮换、网络策略
消息队列消息篡改、重放攻击消息签名、幂等性
服务发现注册表投毒安全注册、健康检查

Serverless Architecture

无服务器架构

ComponentKey ThreatsMitigations
FunctionsCold start attacks, injectionInput validation, minimal permissions
Event SourcesEvent injection, DoSSource validation, rate limiting
Shared TenancyNoisy neighbor, data leakageIsolation, encryption
组件关键威胁缓解措施
函数冷启动攻击、注入输入验证、最小权限
事件源事件注入、拒绝服务源验证、速率限制
共享租户资源抢占、数据泄露隔离、加密

Container/Kubernetes Architecture

容器/Kubernetes架构

ComponentKey ThreatsMitigations
Container RuntimeEscape, privilege escalationRootless, seccomp, AppArmor
OrchestratorAPI server compromiseRBAC, audit logging, network policies
RegistryImage tampering, supply chainImage signing, vulnerability scanning
组件关键威胁缓解措施
容器运行时逃逸、权限提升无根模式、seccomp、AppArmor
编排器API服务器被攻陷RBAC、审计日志、网络策略
镜像仓库镜像篡改、供应链攻击镜像签名、漏洞扫描

SDLC Integration

SDLC集成

When to Threat Model

何时进行威胁建模

PhaseActivityOutput
DesignInitial threat modelThreat register, DFD
DevelopmentUpdate for changesUpdated threats, security tests
Code ReviewVerify mitigationsSecurity checklist
TestingValidate mitigationsPenetration test plan
ReleaseFinal reviewRisk acceptance, residual risks
OperationsIncident analysisUpdated threat model
阶段活动输出
设计初始威胁建模威胁登记册、DFD
开发根据变更更新模型更新后的威胁、安全测试
代码评审验证缓解措施安全检查清单
测试验证缓解措施有效性渗透测试计划
发布最终评审风险接受文档、剩余风险
运维事件分析更新后的威胁模型

Lightweight Threat Modeling

轻量级威胁建模

For agile environments, use rapid threat modeling:
yaml
undefined
针对敏捷环境,可使用快速威胁建模:
yaml
undefined

threat-model.yaml - Minimal threat model per feature

threat-model.yaml - Minimal threat model per feature

feature: User Authentication date: 2024-01-15 author: security-team
assets:
  • name: User credentials classification: Confidential
  • name: Session tokens classification: Internal
threats:
  • id: AUTH-001 category: Spoofing description: Credential stuffing attack risk: High mitigation: Rate limiting, MFA, breach detection
  • id: AUTH-002 category: Information Disclosure description: Token exposure in logs risk: Medium mitigation: Token redaction, structured logging
mitigations_implemented:
  • Argon2id password hashing
  • JWT with short expiration
  • Refresh token rotation
open_risks:
  • Legacy systems using MD5 (migration planned Q2)
undefined
feature: User Authentication date: 2024-01-15 author: security-team
assets:
  • name: User credentials classification: Confidential
  • name: Session tokens classification: Internal
threats:
  • id: AUTH-001 category: Spoofing description: Credential stuffing attack risk: High mitigation: Rate limiting, MFA, breach detection
  • id: AUTH-002 category: Information Disclosure description: Token exposure in logs risk: Medium mitigation: Token redaction, structured logging
mitigations_implemented:
  • Argon2id password hashing
  • JWT with short expiration
  • Refresh token rotation
open_risks:
  • Legacy systems using MD5 (migration planned Q2)
undefined

Security Checklist

安全检查清单

Before finalizing threat model:
  • All trust boundaries identified
  • STRIDE applied to each element
  • Data flows across boundaries encrypted
  • Authentication at trust boundary crossings
  • Risks prioritized (DREAD/CVSS)
  • Mitigations mapped to threats
  • Residual risks documented
  • Model reviewed by stakeholders
  • Integration with issue tracking
完成威胁建模前需确认:
  • 已识别所有信任边界
  • 已对每个元素应用STRIDE分析
  • 跨边界的数据流已加密
  • 信任边界交叉点已实现认证
  • 已对风险进行优先级排序(DREAD/CVSS)
  • 已将缓解措施与威胁关联
  • 已记录剩余风险
  • 模型已通过相关方评审
  • 已与问题跟踪系统集成

References

参考资料

  • STRIDE Methodology Deep Dive - Detailed analysis with examples
  • Threat Modeling Tools - pytm, threagile, automation
  • STRIDE方法论深度解析 - 带示例的详细分析
  • 威胁建模工具 - pytm、threagile、自动化工具

User-Facing Interface

用户交互界面

When invoked directly by the user, this skill generates a structured threat model using STRIDE methodology.
当用户直接调用该技能时,将使用STRIDE方法论生成结构化威胁模型。

Execution Workflow

执行流程

  1. Parse Arguments - Extract the component or feature description from
    $ARGUMENTS
    . If no arguments provided, ask the user what to threat model.
  2. Understand the System - Identify assets, data flows, trust boundaries, and entry points.
  3. Create Data Flow Diagram - Generate a DFD in Mermaid notation showing components, data flows, and trust boundaries.
  4. Apply STRIDE Analysis - Analyze each component for Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege threats.
  5. Build Attack Trees - Create goal-oriented attack trees for high-value assets.
  6. Score Risks - Apply DREAD methodology (Damage, Reproducibility, Exploitability, Affected Users, Discoverability) to prioritize threats.
  7. Recommend Controls - Provide prioritized security control recommendations (Must Have / Should Have / Nice to Have).
  1. 解析参数 - 从
    $ARGUMENTS
    中提取组件或功能描述。若未提供参数,询问用户要对什么进行威胁建模。
  2. 理解系统 - 识别资产、数据流、信任边界和入口点。
  3. 创建数据流图 - 生成Mermaid格式的DFD,展示组件、数据流和信任边界。
  4. 应用STRIDE分析 - 分析每个组件的冒充、篡改、抵赖、信息泄露、拒绝服务和权限提升威胁。
  5. 构建攻击树 - 为高价值资产创建面向目标的攻击树。
  6. 风险评分 - 应用DREAD方法论(损害、可复现性、可利用性、受影响用户、可发现性)对威胁进行优先级排序。
  7. 推荐控制措施 - 提供分优先级的安全控制建议(必备/应备/可选)。

Version History

版本历史

  • v1.0.0 (2025-12-26): Initial release with STRIDE, DREAD, attack trees, architecture patterns

Last Updated: 2025-12-26
  • v1.0.0(2025-12-26):初始版本,包含STRIDE、DREAD、攻击树、架构模式

最后更新: 2025-12-26