Metadata-Version: 2.4
Name: winsec-timeline
Version: 1.0.2
Summary: Windows Security Analysis Engine — transforms structured Windows Event Logs into attack timelines, process trees, and human-readable forensic narratives.
Author: SecByShresth
License-Expression: MIT
Project-URL: Homepage, https://github.com/SecByShresth/winsec-timeline
Project-URL: Documentation, https://github.com/SecByShresth/winsec-timeline#readme
Project-URL: Issues, https://github.com/SecByShresth/winsec-timeline/issues
Project-URL: Source Code, https://github.com/SecByShresth/winsec-timeline
Project-URL: Changelog, https://github.com/SecByShresth/winsec-timeline/releases
Keywords: windows,security,siem,soc,event-log,timeline,incident-response,threat-detection,forensics,dfir,mitre-attack,blue-team,process-tree,evtx,sigma
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: System :: Logging
Classifier: Topic :: System :: Systems Administration
Classifier: Environment :: Console
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: rich>=13.0
Requires-Dist: PyYAML>=6.0
Provides-Extra: evtx
Requires-Dist: python-evtx>=0.7; extra == "evtx"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: python-evtx>=0.7; extra == "dev"
Dynamic: license-file

# 🛡️ WinSec Timeline

**Windows Security Analysis Engine** — Transforms structured Windows Event Logs into attack timelines, process trees, and human-readable forensic narratives. No SIEM required.

[![PyPI](https://img.shields.io/pypi/v/winsec-timeline)](https://pypi.org/project/winsec-timeline/)
[![Python](https://img.shields.io/pypi/pyversions/winsec-timeline)](https://pypi.org/project/winsec-timeline/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub](https://img.shields.io/badge/GitHub-SecByShresth%2Fwinsec--timeline-181717?logo=github)](https://github.com/SecByShresth/winsec-timeline)

---

## 🚀 Features

| Capability | Details |
|---|---|
| **5-Stage Analysis Pipeline** | Preprocess → Correlate → Detect → Score → Aggregate |
| **50+ Built-in Detection Rules** | Mapped to MITRE ATT&CK, covering the full attack lifecycle |
| **Attack Chain Reconstruction** | Stages from Initial Access to Impact, automatically sequenced |
| **Process Tree Visualization** | Parent-child execution chains with suspicious path highlighting |
| **Confidence Scoring** | 0–100% verdict score with deduplication to prevent inflation |
| **HTML Report Generation** | Dark-mode forensic report with process graph, MITRE heatmap, IOCs |
| **IOC Extraction** | Automatically surfaces IPs, domains, URLs, and file hashes |
| **Sigma Rule Support** | Load your own custom rules on top of the built-in ruleset |
| **Multiple Input Formats** | `.evtx`, XML, JSON, CSV — single file or directory |
| **Multiple Output Formats** | HTML · JSON · Plain Text |
| **CLI & Python API** | Use as a standalone tool or embed in your own pipeline |

---

## 📦 Installation

```bash
# Standard install
pip install winsec-timeline

# With native .evtx file support
pip install winsec-timeline[evtx]

# Development (includes pytest, ruff, evtx)
pip install winsec-timeline[dev]
```

**Requirements:** Python 3.9+ · Dependencies: `rich`, `PyYAML`

---

## ⚡ Quick Start

### CLI

```bash
# Analyze a log file, output HTML report (default)
winsec-timeline analyze logs.json

# Save HTML report to file
winsec-timeline analyze logs.json --output report.html

# Output as JSON
winsec-timeline analyze logs.json --format json

# Output plain text to terminal
winsec-timeline analyze logs.json --format cli

# Check version
winsec-timeline --version
```

### Python API

```python
from winsec_timeline import SecurityAnalyzer

analyzer = SecurityAnalyzer()
report = analyzer.analyze("logs.json")

print(report.verdict.value)   # "Likely Malicious"
print(report.confidence)      # 87

report_html = report.to_html()   # Full dark-mode HTML report
report_json = report.to_json()   # Machine-readable JSON
report_text = report.to_text()   # Plain text summary
```

---

## 🖥️ CLI Reference

```
winsec-timeline analyze <path> [options]
```

| Argument | Type | Default | Description |
|---|---|---|---|
| `path` | positional | — | Path to a log file or directory of log files |
| `--format` | `html` \| `json` \| `cli` | `html` | Output format |
| `-o` / `--output` | string | stdout | Write output to this file path |
| `--fast-mode` | flag | off | Cap ingestion at 100,000 events (vs. 500,000) for speed |
| `--full-timeline` | flag | off | Include every event in the full timeline section |
| `--ioc-only` | flag | off | Skip detections; extract IOCs only |
| `--sigma-rules` | string | — | Path to a Sigma rule file or directory |
| `--export-graph` | flag | off | Write the process graph as a `.graph.json` sidecar file |

### Examples

```bash
# Fast triage on a large log directory
winsec-timeline analyze ./incident_logs/ --fast-mode --format cli

# Full investigation — HTML report + sidecar graph JSON
winsec-timeline analyze ./logs/ --full-timeline --export-graph --output report.html

# IOC extraction only — no detection engine
winsec-timeline analyze logs.json --ioc-only --format json --output iocs.json

# Use custom Sigma rules on top of built-ins
winsec-timeline analyze logs.json --sigma-rules ./my_sigma_rules/ --output report.html

# Analyze a raw .evtx file (requires winsec-timeline[evtx])
winsec-timeline analyze Security.evtx --output report.html
```

---

## 🐍 Python API Reference

### `SecurityAnalyzer.analyze(data, **kwargs)`

```python
from winsec_timeline import SecurityAnalyzer
from winsec_timeline.analyzer import ThreatIntelProvider

analyzer = SecurityAnalyzer(threat_intel=ThreatIntelProvider())

report = analyzer.analyze(
    data,                        # dict | str (JSON) | Path — the event data
    include_full_timeline=False, # bool — include every raw event in output
    ioc_only=False,              # bool — skip detections, extract IOCs only
    export_graph=False,          # bool — include attack graph in report
    host_criticality={},         # dict[str, int] — boost score for critical hosts
    sigma_rules=[],              # list[dict] — custom Sigma rules to layer on top
)
```

#### `host_criticality` — Score Weighting by Host

Assign an importance score (0–10) to specific hosts. If a host appears in the logs
and has a criticality value set, its score contribution is boosted accordingly.

```python
report = analyzer.analyze(
    data,
    host_criticality={
        "DC-01":       10,   # Domain controller — maximum weight
        "FILESERVER":   8,
        "CORP-PC-01":   3,
    }
)
```

#### `sigma_rules` — Custom Detection Rules

Load and pass Sigma rules to extend the built-in ruleset:

```python
from winsec_timeline.analyzer import load_sigma_rules

sigma = load_sigma_rules("./my_sigma_rules/")  # file or directory

report = analyzer.analyze(data, sigma_rules=sigma)
```

`load_sigma_rules()` accepts `.yml`, `.yaml`, and `.json` files and walks directories recursively.

---

### `AnalysisReport` — Output Object

Every `analyze()` call returns an `AnalysisReport` with the following fields and methods:

```python
report.verdict           # Verdict.LIKELY_MALICIOUS | Verdict.SUSPICIOUS | Verdict.BENIGN
report.confidence        # int — 0 to 100
report.summary           # str — executive summary in plain English
report.top_findings      # list[Detection] — highest-severity detections
report.attack_chain      # list[AttackChainStage] — MITRE tactic stages
report.condensed_timeline# list[TimelineEntry] — behavioral timeline (grouped)
report.full_timeline     # list[TimelineEntry] — every raw event
report.mitre_summary     # dict[str, int] — technique ID → hit count
report.iocs              # dict — {"ips": [...], "domains": [...], "urls": [...], "hashes": [...]}
report.attack_graph      # GraphData — process nodes and edges
report.stats             # dict — events_total, detections_total, hosts_total, unique_processes
report.repaired_event_count  # int
report.dropped_event_count   # int

# Output methods
report.to_html()         # str — full dark-mode HTML report
report.to_json()         # str — JSON serialisation of the entire report
report.to_text()         # str — plain text summary for terminal output
report.to_dict()         # dict — Python dict (for custom serialisation)
```

---

## 📊 Analysis Pipeline

```
Input Logs (.evtx / XML / JSON / CSV)
         │
         ▼
┌─────────────────────────────────┐
│  Stage 1: PREPROCESSING         │
│  • Parse all input formats      │
│  • Normalise timestamps to UTC  │
│  • Repair/drop invalid events   │
│  • Filter to high-signal EIDs   │
└────────────────┬────────────────┘
                 │
                 ▼
┌─────────────────────────────────┐
│  Stage 2: CORRELATION           │
│  • Stitch events by host + PID  │
│  • Build parent→child tree      │
│  • Group into behavior chains   │
└────────────────┬────────────────┘
                 │
                 ▼
┌─────────────────────────────────┐
│  Stage 3: DETECTION             │
│  • Run 50+ built-in rules       │
│  • Apply custom Sigma rules     │
│  • Map hits to MITRE ATT&CK     │
└────────────────┬────────────────┘
                 │
                 ▼
┌─────────────────────────────────┐
│  Stage 4: SCORING               │
│  • Deduplicate by rule + tactic │
│  • Apply host criticality bonus │
│  • Produce 0–100 confidence     │
│  • Assign Verdict               │
└────────────────┬────────────────┘
                 │
                 ▼
┌─────────────────────────────────┐
│  Stage 5: AGGREGATION           │
│  • Build executive summary      │
│  • Construct attack chain       │
│  • Build behavioral timeline    │
│  • Extract IOCs                 │
│  • Generate process graph       │
└────────────────┬────────────────┘
                 │
                 ▼
     HTML Report / JSON / Text
```

---

## 🔍 Detection Rules

### Core Rules (WST-001 – WST-026)

| Rule ID | Title | Severity | Tactic | MITRE |
|---|---|---|---|---|
| WST-001 | Office spawned PowerShell | Critical | Execution | T1059.001 |
| WST-002 | Office spawned cmd | High | Execution | T1059.003 |
| WST-003 | Encoded command line | High | Defense Evasion | T1027 |
| WST-004 | PowerShell download cradle | High | Execution | T1059.001 |
| WST-005 | IEX / Invoke-Expression | High | Execution | T1059.001 |
| WST-006 | LOLBIN proxy execution | Medium | Defense Evasion | T1218 |
| WST-007 | Scheduled task creation | High | Persistence | T1053.005 |
| WST-008 | Service installation | High | Persistence | T1543.003 |
| WST-009 | Registry Run-key persistence | High | Persistence | T1547.001 |
| WST-010 | LSASS memory access (Sysmon) | Critical | Credential Access | T1003.001 |
| WST-011 | Credential dumping tooling | Critical | Credential Access | T1003 |
| WST-012 | SAM hive access | Critical | Credential Access | T1003.002 |
| WST-013 | NTDS / VSS access | Critical | Credential Access | T1003.003 |
| WST-014 | Pass-the-Hash indicators | High | Lateral Movement | T1550.002 |
| WST-015 | RDP lateral movement | Medium | Lateral Movement | T1021.001 |
| WST-016 | WinRM remote execution | High | Lateral Movement | T1021.006 |
| WST-017 | WMI remote execution | High | Lateral Movement | T1047 |
| WST-018 | SMB admin share access | Medium | Lateral Movement | T1021.002 |
| WST-019 | External network beacon | High | Command and Control | T1071.001 |
| WST-020 | DNS C2 pattern | Medium | Command and Control | T1071.004 |
| WST-021 | DNS tunnelling | High | Command and Control | T1572 |
| WST-022 | Archive staging | Medium | Collection | T1560.001 |
| WST-023 | Exfiltration over C2 | Critical | Exfiltration | T1041 |
| WST-024 | Exfiltration via DNS | Critical | Exfiltration | T1048.003 |
| WST-025 | Shadow copy deletion | Critical | Impact | T1490 |
| WST-026 | Ransomware encryption markers | Critical | Impact | T1486 |

### Secondary Discovery & Admin-Abuse Rules (WST-027+)

Medium severity, keyword-based rules covering: `net user`, `whoami`, `ipconfig`, `nltest`, `dsquery`, `systeminfo`, `tasklist`, `qwinsta`, `net view`, `arp -a`, `route print`, `reg save`, `cmdkey /list`, `wevtutil cl`, `sc stop`, `set-mppreference`, `bcdedit /set`, `rundll32`, `regsvr32`, `mshta`, `bitsadmin /transfer`, `curl`, `certutil -urlcache`, `wmic process call create`, `psexec.exe`, `invoke-mimikatz`, `secedit`, `fodhelper`

---

## 📄 HTML Report Sections

When using `--format html` or `report.to_html()`, the output includes:

| Section | Description |
|---|---|
| **Verdict Banner** | Verdict, confidence ring, executive summary |
| **Stats Row** | Events analyzed, detections fired, hosts, unique processes, graph nodes/edges |
| **Top Findings** | Up to 10 highest-severity detections with evidence |
| **Attack Chain** | MITRE tactic stages with technique tags and finding narratives |
| **MITRE ATT&CK Coverage** | Bar chart of technique hit counts |
| **Behavioral Timeline** | Grouped event cards, color-coded Malicious / Suspicious / Normal |
| **Indicators of Compromise** | IPs, domains, URLs, file hashes — expandable by type |
| **Process Graph** | All process nodes with risk level, spawn edge table, raw JSON |
| **Full Event Timeline** | Every raw event in a searchable table (up to 2,000 rows) |

---

## 📥 Input Format Reference

WinSec Timeline accepts events under either a `"timeline"` or `"events"` key:

```json
{
  "timeline": [
    {
      "timestamp":    "2024-03-15T09:15:23Z",
      "event_id":     4688,
      "process_name": "powershell.exe",
      "parent_process": "winword.exe",
      "command_line": "powershell -encodedcommand SGVsbG8=",
      "host":         "CORP-PC-01",
      "user":         "jsmith",
      "process_id":   4912,
      "parent_process_id": 3120,
      "ip":           "10.0.0.5",
      "domain":       "",
      "logon_type":   0,
      "file_hash":    ""
    }
  ]
}
```

**Alternate field names accepted:** `process` → `process_name`, `parent` → `parent_process`, `details` → `message`. String `event` values (`"Process Created"`, `"Logon"`, etc.) are automatically mapped to Event IDs.

---

## 📄 License

MIT License — see [LICENSE](LICENSE) for details.

---

## 🤝 Contributing

Issues and pull requests are welcome at [github.com/SecByShresth/winsec-timeline](https://github.com/SecByShresth/winsec-timeline).

Especially valuable: real-world `.evtx` test samples, new detection rules, and integrations with other DFIR tools.
