# rasta-mouse/threatcheck architecture

> Architecture diagram of the GitHub repository rasta-mouse/threatcheck, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rasta-mouse/threatcheck
- Repository: https://github.com/rasta-mouse/threatcheck

## Overview

##### What this project is (type + purpose)
**ThreatCheck** is a **Windows/.NET Framework console application** (Visual Studio `.sln` / `.csproj`) used to **identify the exact byte ranges in an input file/script that trigger detection** by a chosen “engine”:
- **Microsoft Defender** (on-disk/binary scanning)
- **AMSI** (script/content scanning via the Windows AMSI interface)

Architecturally it’s a **single-process CLI tool** with a small internal “plugin-like” scanner abstraction (`Scanner`) and two concrete implementations (`DefenderScanner`, `AmsiScanner`). It also optionally downloads input from a URL.

- **C4 Context** (tool + external dependencies),
- **C4 Container** (single executable + OS services),

##### Read the file tree as architecture signals
Top-level:
- `ThreatCheck.sln` / `ThreatCheck/ThreatCheck.csproj` → single Visual Studio solution + one main project.
- `Program.cs` → CLI entry point; argument parsing; orchestration.
- `Scanners/` folder:
- `Scanner.cs` → base class / interface for scanning engines (core extensibility seam)
- `AmsiScanner.cs` → AMSI integration
- `DefenderScanner.cs` → Defender integration
- `NativeMethods.cs` → **P/Invoke boundary** (calls into Windows APIs; likely AMSI functions and other native calls)
- `Helpers.cs` → shared utilities (byte slicing, formatting, maybe splitting algorithm helpers, IO)
- `App.config` → runtime config (often .NET Framework settings)
- `Properties/AssemblyInfo.cs` → assembly metadata (not important for runtime architecture)

- **Orchestrator (Program)**
- **Input acquisition** (file vs URL)
- **Analysis loop** (splitting / pinpointing bad bytes)
- **Scanning abstraction + implementations**
- **Native boundary** (AMSI + Windows/Defender)
- **Presentation** (console output)

From README behavior:
- Accepts input from **disk** or **URL**
- Scans using **Defender** or **AMSI**
- Splits input repeatedly until it finds the smallest/precise flagged range
- Outputs offsets + hex dump to console

- **User / Operator** (invokes tool)
- **Filesystem** (reads local target file)
- **Network / Remote HTTP server** (if `--url` is used)
- **Windows Defender scanning capability** (engine external to the process)
- **Windows AMSI subsystem** (external to the process; invoked through native APIs)
- Optionally: **Windows OS** boundary (because AMSI + Defender are OS-integrated services)

##### CLI/Orchestrator
- `Program.cs`
- Responsibilities:
- Parse args (`--engine`, `--file`, `--url`, `--type`)
- Choose scanner implementation
- Kick off analysis loop
- Handle success/failure exit codes

##### Input Acquisition
- (Likely in `Helpers.cs` and/or `Program.cs`)
- Two subcomponents:
- **FileReader**: reads bytes from disk
- **UrlDownloader**: downloads bytes over HTTP

##### Analysis Engine (Byte Range Minimizer)
- (Often implemented across `Program.cs` + `Helpers.cs`)
- Responsibilities:
- Split content (binary/script) into segments
- Iteratively test segments against the chosen scanner
- Converge on “bad bytes end offset” (and potentially start offset)
- Produce result: offsets + offending byte sequence

##### Scanning Interface
- `Scanners/Scanner.cs`
- Responsibilities:
- Defines contract like `Scan(byte[] buffer, FileType type)` returning “clean/flagged” + message

##### Concrete Scanners
- `Scanners/DefenderScanner.cs`
- Calls into Defender scanning mechanism (external)
- `Scanners/AmsiScanner.cs`
- Calls into AMSI via native methods (external)

##### Native Interop Layer
- `NativeMethods.cs`
- Responsibilities:
- P/Invoke declarations
- Marshaling buffers/strings
- Strict boundary: “managed ↔ native Windows APIs”

##### Utilities
- `Helpers.cs`
- Responsibilities:
- Byte slicing, encoding conversions (especially for Script mode, likely UTF-16LE as shown)
- Hex dump helper
- Common constants

- `Program` → `Input Acquisition`: “get target bytes”
- `Program` → `Analysis Engine`: “analyze(bytes, type, scanner)”
- `Analysis Engine` → `Scanner` (interface): “scan(candidateBuffer)”
- `Scanner` → (`DefenderScanner` or `AmsiScanner`): “engine-specific scan”
- `AmsiScanner` → `NativeMethods` → **AMSI (external)**: “AmsiScanBuffer”
- `DefenderScanner` → **Defender (external)**: “submit/scan content”
- `Analysis Engine` → `CustomConsole`: “print offsets + hexdump”

##### Architectural patterns/design principles to highlight (specific to ThreatCheck)
- **Strategy pattern** for scanning engines:
- `Scanner` = strategy interface
- `DefenderScanner` / `AmsiScanner` = concrete strategies
- **Explicit boundary around native/system calls**:
- `NativeMethods.cs` isolates platform coupling
- **Pipeline-like processing**:
- Acquire input → Normalize/encode (esp. Script) → Split/minimize → Scan → Report
- **Single responsibility separation** (even in a small tool):
- Orchestration vs scanning vs interop vs output formatting

Of the following (explicitly) in the drawing:

##### Labels
- **Component name**
- **File/class** (e.g., “AmsiScanner (Scanners/AmsiScanner.cs)”)
- **Responsibility** (short phrase)

- Data type: “byte[]”, “string/script text”, “scan verdict”
- Mode: “Bin vs Script”
- Protocol where relevant: “HTTP GET”, “Win32 API (P/Invoke)”

##### Container: single-process ThreatCheck.exe (.NET) + OS services + IO boundaries
3. **Component (most important)**: map every file above into components and show the scanning/minimization loop

- Candidate slice → scan → if flagged then shrink slice → repeat → result

That loop is the essence of ThreatCheck’s behavior and is what differentiates it from a trivial “scan a file” tool—so it must be visually central.

- Defender and AMSI are shown as **external** systems.
- `Scanner` abstraction is shown, with two implementations.
- Both input modes (file + URL) appear.
- Script vs Bin type is represented (either as a decision node or an annotation on the analysis pipeline).
- Output includes offset + hexdump (Presentation component).

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% System Context (C4)
    %% =========================
    subgraph "System Context"
        OP["Operator\n(Invokes CLI)"]:::external

        TC_SYS["ThreatCheck.exe\nSystem: Windows/.NET Framework CLI tool\nPurpose: pinpoint detection-triggering byte ranges"]:::system

        FS[("Local Filesystem\nInput file bytes")]:::datastore
        URLC["Remote URL Host\n(HTTP server)"]:::network

        DEF["Windows Defender\n(On-disk/binary scanning engine)"]:::os
        AMSI["AMSI\n(Windows Antimalware Scan Interface)"]:::os
    end

    OP -->|"CLI_args(engine,input_source,type)"| TC_SYS
    TC_SYS -->|"Read_bytes(byte[])"| FS
    TC_SYS -->|"HTTP_GET(download_bytes)"| URLC
    TC_SYS -->|"Submit_content_for_scan(verdict)"| DEF
    TC_SYS -->|"AmsiScanBuffer(verdict)"| AMSI
    TC_SYS -->|"Results(offsets,hexdump,verdict)"| OP

    %% =========================
    %% Container (C4)
    %% =========================
    subgraph "Container View"
        subgraph "ThreatCheck.exe (Single Process)\nConsole App (.NET Framework)"
            ENTRY["CLI Host\nProgram main()"]:::internal
            PIPE["Processing Pipeline\nAcquire → Normalize(type) → Minimize → Scan → Report"]:::internal
        end

        subgraph "External I/O + OS"
            IO_FS[("Filesystem")]:::datastore
            IO_NET["Network\n(HTTP)"]:::network
            OS_DEF["Windows Defender"]:::os
            OS_AMSI["AMSI Subsystem"]:::os
        end
    end

    ENTRY -->|"orchestrates"| PIPE
    PIPE -->|"file_mode"| IO_FS
    PIPE -->|"url_mode"| IO_NET
    PIPE -->|"scan_via"| OS_DEF
    PIPE -->|"scan_via"| OS_AMSI

    %% =========================
    %% Component Diagram (Most Important)
    %% =========================
    subgraph "Component View (Inside ThreatCheck.exe)"
        direction TB

        subgraph "Build & Runtime Metadata"
            SLN["Solution\nThreatCheck.sln"]:::meta
            CSPROJ["Project\nThreatCheck.csproj"]:::meta
            CFG["Runtime Configuration\nApp.config"]:::meta
            ASM["Assembly Metadata\nAssemblyInfo.cs"]:::meta
        end

        subgraph "CLI & Orchestration"
            PROG["Program\n(Arg parse, scanner selection, main flow)\nChooses: Defender vs AMSI; Input: File vs URL; Type: Bin vs Script"]:::internal
        end

        subgraph "Input Acquisition"
            INP["Input Acquisition\nFileReader + UrlDownloader\nReturns: byte[]"]:::internal
        end

        subgraph "Analysis Engine"
            MIN["Byte Range Minimizer\nIterative splitting loop\nGoal: smallest flagged byte range\nOutputs: start/end offsets + offending bytes"]:::internal
            TYPEDEC{"Type?\nBin vs Script"}:::decision
        end

        subgraph "Scanning (Strategy Pattern)"
            SCAN_IF["Scanner (Strategy Abstraction)\nContract: Scan(byte[],type) → verdict/message"]:::internal
            SCAN_DEF["DefenderScanner\nConcrete strategy\nDelegates to Defender engine"]:::internal
            SCAN_AMSI["AmsiScanner\nConcrete strategy\nDelegates to AMSI via P/Invoke"]:::internal
        end

        subgraph "Native Boundary (Interop)"
            NATIVE["NativeMethods\nP/Invoke declarations + marshaling\nManaged ↔ Win32 boundary"]:::native
        end

        subgraph "Utilities & Presentation"
            HELP["Helpers\nByte slicing, encoding/normalization,\ncommon helpers for split/format"]:::internal
            OUT["CustomConsole\nConsole formatting + colored output\nHexdump + offset display"]:::internal
        end
    end

    %% --- Internal data flow / dependencies (vertical, annotated) ---
    PROG -->|"get_target_bytes"| INP
    PROG -->|"analyze(bytes,type,scanner)"| MIN
    MIN -->|"normalize/encode(esp_script)"| TYPEDEC
    TYPEDEC -->|"Bin_mode(byte[])"| MIN
    TYPEDEC -->|"Script_mode(string→byte[])"| HELP

    %% Minimization loop (essence of tool)
    MIN -->|"candidate_slice(byte[])"| SCAN_IF
    SCAN_IF -->|"strategy_dispatch"| SCAN_DEF
    SCAN_IF -->|"strategy_dispatch"| SCAN_AMSI
    SCAN_DEF -->|"submit_scan(verdict)"| DEF
    SCAN_AMSI -->|"Win32_API(P/Invoke)"| NATIVE
    NATIVE -->|"AmsiScanBuffer(verdict)"| AMSI
    SCAN_DEF -->|"verdict/message"| MIN
    SCAN_AMSI -->|"verdict/message"| MIN
    MIN -->|"if_flagged→shrink_and_repeat"| MIN

    MIN -->|"result(offsets,offending_bytes)"| OUT
    PROG -->|"status/summary"| OUT

    %% Shared helpers
    PROG -->|"uses"| HELP
    INP -->|"uses"| HELP
    MIN -->|"uses"| HELP
    OUT -->|"uses"| HELP

    %% --- Build/config relationships ---
    SLN -->|"contains"| CSPROJ
    CSPROJ -->|"includes"| PROG
    CSPROJ -->|"includes"| SCAN_IF
    CSPROJ -->|"includes"| SCAN_DEF
    CSPROJ -->|"includes"| SCAN_AMSI
    CSPROJ -->|"includes"| NATIVE
    CSPROJ -->|"includes"| HELP
    CSPROJ -->|"includes"| OUT
    CSPROJ -->|"uses_settings"| CFG
    CSPROJ -->|"assembly_info"| ASM

    %% =========================
    %% Click Events (from component_mapping)
    %% =========================
    click PROG "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Program.cs"
    click INP "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Program.cs"
    click MIN "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Program.cs"
    click SCAN_IF "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Scanners/Scanner.cs"
    click SCAN_DEF "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Scanners/DefenderScanner.cs"
    click SCAN_AMSI "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Scanners/AmsiScanner.cs"
    click NATIVE "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/NativeMethods.cs"
    click OUT "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/CustomConsole.cs"
    click HELP "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Helpers.cs"
    click CFG "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/App.config"
    click SLN "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck.sln"
    click CSPROJ "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/ThreatCheck.csproj"
    click ASM "https://github.com/rasta-mouse/threatcheck/blob/master/ThreatCheck/Properties/AssemblyInfo.cs"

    %% =========================
    %% Styles (Color)
    %% =========================
    classDef system fill:#1f77b4,stroke:#0b3d91,stroke-width:2px,color:#ffffff
    classDef internal fill:#4ea3ff,stroke:#1b5fa7,stroke-width:1.5px,color:#0b1a2b
    classDef external fill:#ffffff,stroke:#555555,stroke-width:1.5px,color:#111111
    classDef os fill:#ffb74d,stroke:#e07b00,stroke-width:2px,color:#3a2200
    classDef datastore fill:#e0e0e0,stroke:#616161,stroke-width:1.5px,color:#111111
    classDef network fill:#eeeeee,stroke:#757575,stroke-width:1.5px,color:#111111
    classDef native fill:#b39ddb,stroke:#4527a0,stroke-width:2px,stroke-dasharray: 6 4,color:#1a1033
    classDef decision fill:#fff59d,stroke:#b59b00,stroke-width:2px,color:#3a3200
    classDef meta fill:#cfd8dc,stroke:#546e7a,stroke-width:1.5px,color:#0b1a2b

    class OP external
    class TC_SYS system
    class FS,IO_FS datastore
    class URLC,IO_NET network
    class DEF,OS_DEF os
    class AMSI,OS_AMSI os
```
