EngineeringSolution ArchitectSecurity and Observability

Session 02 - Threat Modeling

Tại Sao Cần Threat Modeling?

Threat modeling là quá trình có hệ thống để xác định, đánh giá và xử lý security threats trước khi code. Chi phí fix security bug tăng 30-100x nếu phát hiện ở production so với design phase.

Khi nào thực hiện?

TimingTrigger
New systemArchitecture design phase
Major featureThay đổi data flow, thêm integration mới
Post-incidentSau security breach hoặc near-miss
Periodic reviewHàng quý cho critical systems

STRIDE Methodology

Microsoft STRIDE phân loại threats thành 6 categories:

ThreatMô tảVí dụ .NETMitigation
SpoofingGiả mạo identityFake JWT tokenAuthentication, token validation
TamperingSửa đổi dataMan-in-the-middleIntegrity checks, TLS, signing
RepudiationPhủ nhận hành độngUser phủ nhận đã xóa dataAudit logging, digital signatures
Info DisclosureLộ thông tinStack trace ở productionError handling, encryption
Denial of ServiceLàm service không hoạt độngDDoS, resource exhaustionRate limiting, autoscaling
Elevation of PrivilegeLeo thang quyềnUser thường access admin APIAuthorization, least privilege

Data Flow Diagram cho .NET App

Level 0 - Context Diagram

Level 1 - Trust Boundaries

TB = Trust Boundary: Mỗi khi data cross boundary, cần validation và authentication.

Threat Modeling Workshop Process

Step-by-Step (90 phút workshop)

StepThời gianActivity
1. Scope10 phútDefine system scope, what's in/out
2. Diagram20 phútVẽ DFD, xác định trust boundaries
3. Identify30 phútDùng STRIDE cho mỗi component
4. Assess15 phútĐánh giá risk (Impact x Likelihood)
5. Mitigate15 phútChọn mitigation strategy cho high risks

Risk Assessment Matrix

Low ImpactMedium ImpactHigh Impact
High LikelihoodMediumHighCritical
Medium LikelihoodLowMediumHigh
Low LikelihoodLowLowMedium

Participants

  • Required: Tech Lead, Senior Developer, Security Champion
  • Optional: Product Owner, DevOps, QA
  • Facilitator: Người hiểu threat modeling methodology

Example: Threat Model cho .NET Web API

System: Order Management API

Components: ASP.NET API → SQL Server → Azure Service Bus → Worker

STRIDE Analysis

ComponentThreatCategoryRiskMitigation
API EndpointFake JWT tokensSpoofingHighValidate issuer, audience, signature; short expiry
API → DBSQL injectionTamperingCriticalEF Core parameterized queries, input validation
Audit LogUser denies actionRepudiationMediumImmutable audit log, append-only table
Error ResponseStack trace leaksInfo DisclosureHighCustom error handler, no details in production
API EndpointRequest floodingDoSHighRate limiting, Azure Front Door DDoS protection
Admin EndpointRegular user accessElevationCriticalRole-based + policy-based authorization

Mitigation Implementation

csharp
// Threat: Info Disclosure - Stack trace in production
// Mitigation: Custom exception handler
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/json";

        var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
        var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();

        // Log full exception internally
        logger.LogError(errorFeature?.Error,
            "Unhandled exception for {Path}", context.Request.Path);

        // Return sanitized response to client
        await context.Response.WriteAsJsonAsync(new
        {
            error = "An internal error occurred",
            traceId = Activity.Current?.TraceId.ToString()
        });
    });
});

// Threat: Elevation of Privilege - Admin endpoint access
// Mitigation: Policy-based authorization
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin")
              .RequireClaim("department", "engineering"))
    .AddPolicy("OrderWrite", policy =>
        policy.RequireAuthenticatedUser()
              .AddRequirements(new OrderOwnerRequirement()));

Microsoft Threat Modeling Tool

Khi nào dùng tool vs manual?

ApproachPhù hợp choProsCons
MS TMTLarge systems, compliance cần documentationAuto-generate threats, structured outputLearning curve, heavyweight
Manual (whiteboard)Agile teams, design reviewsFast, collaborative, flexibleLess structured, may miss threats
OWASP Threat DragonOpen-source alternativeFree, web-basedÍt features hơn MS TMT

Output Format

Threat model document nên chứa:

  1. System description và scope
  2. DFD diagrams với trust boundaries
  3. Threat list với STRIDE classification
  4. Risk ratings (Impact x Likelihood)
  5. Mitigations với implementation status
  6. Assumptions và out-of-scope items
  7. Review date cho periodic reassessment

Trade-offs

Quyết địnhProCon
Threat model mọi featureComprehensive securitySlow delivery, team fatigue
Chỉ threat model major changesBalanced approachCó thể miss incremental risks
Formal tool (MS TMT)Structured, auditableOverhead, adoption resistance
Informal (whiteboard)Fast, engagingÍt traceability
Security champion in teamContinuous awarenessSingle point of knowledge
External security reviewExpert perspectiveExpensive, scheduling delays