Metadata-Version: 2.4
Name: winsecaudit
Version: 1.1.5
Summary: CLI-first Windows security misconfiguration auditor with weighted scoring, threat-intel enrichment, and multi-format reporting.
Author-email: Kavya Jain <jainkavyakj123@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/KavyaJain321/winsecaudit-v2
Project-URL: Repository, https://github.com/KavyaJain321/winsecaudit-v2
Project-URL: Issues, https://github.com/KavyaJain321/winsecaudit-v2/issues
Keywords: windows,security,audit,cve,hardening,cis,compliance
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: System Administrators
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: Microsoft :: Windows :: Windows 10
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer>=0.9
Requires-Dist: rich>=13
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: pyyaml>=6
Requires-Dist: requests>=2.31
Requires-Dist: fastapi>=0.110
Requires-Dist: uvicorn[standard]>=0.27
Requires-Dist: pydantic>=2
Requires-Dist: reportlab>=4
Requires-Dist: python-docx>=1.1
Dynamic: license-file

<div align="center">

# 🛡️ WinSecAudit v2

### *A CLI-first Windows Security Misconfiguration Auditor*

**Weighted scoring · Threat intelligence enrichment · Multi-format reporting · Drift detection**

[![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![Platform](https://img.shields.io/badge/Platform-Windows%2010%2F11-0078D6?logo=windows&logoColor=white)](https://www.microsoft.com/windows)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Checks](https://img.shields.io/badge/Security%20Checks-39-red)](#-security-checks)
[![Tests](https://img.shields.io/badge/Smoke%20Tests-10%2F10%20passing-brightgreen)](tests/smoke_test.py)

</div>

---

## ✨ Overview

**WinSecAudit v2** audits Windows 10/11 machines for common security misconfigurations, assigns a weighted risk score, enriches every finding with live CVE threat intelligence, and produces boardroom-ready reports in four formats. It's built as a plugin system — every check is a self-contained class auto-discovered at runtime, so extending the suite requires zero wiring.

```
┌──────────────┐     ┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  39 CHECKS   │ ──▶ │   SCORING    │ ──▶ │  THREAT INTEL│ ──▶ │   REPORTS    │
│ (PowerShell) │     │  (weighted)  │     │ NVD+EPSS+KEV │     │ PDF/DOCX/CSV │
└──────────────┘     └──────────────┘     └──────────────┘     └──────────────┘
```

---

## 📚 Table of Contents

- [🚀 Quick Start](#-quick-start)
- [⚙️ Installation](#️-installation)
- [🧰 Commands](#-commands)
- [🔍 Security Checks](#-security-checks)
- [🎛️ Profiles](#️-profiles)
- [📊 Scoring & Grading](#-scoring--grading)
- [🌐 Threat Intelligence](#-threat-intelligence)
- [📄 Output Formats](#-output-formats)
- [🧪 Testing](#-testing)
- [⚠️ Known Limitations](#️-known-limitations)
- [📂 Project Structure](#-project-structure)
- [🤝 Contributing](#-contributing)

---

## 🚀 Quick Start

```bash
# 1. Clone & install
git clone https://github.com/KavyaJain321/winsecaudit-v2.git
cd winsecaudit-v2
pip install -r requirements.txt

# 2. Run your first audit (open an elevated PowerShell first)
python winsecaudit.py scan

# 3. Export a beautiful PDF report
python winsecaudit.py report --format pdf
```

> 💡 **Tip:** The SQLite database and all caches are created automatically on first run inside `data/`. No setup scripts, no migrations.

---

## ⚙️ Installation

### Requirements

| Requirement | Version |
|---|---|
| **Python** | 3.11 or newer |
| **OS** | Windows 10 / 11 (elevated shell for most checks) |
| **Dependencies** | See [`requirements.txt`](requirements.txt) |

### Setup

```bash
git clone https://github.com/KavyaJain321/winsecaudit-v2.git
cd winsecaudit-v2
pip install -r requirements.txt
```

### Optional

```bash
# Set your NVD API key to bump rate limit from 5 → 50 req/s
$env:NVD_API_KEY = "your-key-here"     # PowerShell
export NVD_API_KEY="your-key-here"     # Bash
```

---

## 🧰 Commands

WinSecAudit ships with **6 Typer-powered commands**. Run `python winsecaudit.py --help` to see them all.

### `scan` — Run the full audit

```bash
python winsecaudit.py scan [OPTIONS]
```

| Option | Default | Description |
|---|---|---|
| `--profile` | `basic` | Profile name (`basic` or `hardened`) |
| `--output` | `terminal` | Output mode: `terminal` or `json` |
| `--no-threat-intel` | off | Skip NVD / EPSS / CISA KEV enrichment |

### `report` — Generate a formatted report

```bash
python winsecaudit.py report [OPTIONS]
```

| Option | Default | Description |
|---|---|---|
| `--scan-id` | latest | Specific scan ID to report on |
| `--format` | `terminal` | `terminal`, `pdf`, `docx`, or `csv` |

### `list` — List saved scans

```bash
python winsecaudit.py list [--machine HOSTNAME] [--limit N]
```

### `drift` — Compare two scans

```bash
python winsecaudit.py drift [--scan-a ID] [--scan-b ID]
```

Defaults to comparing the **two most recent scans**. Under the hood, drift emulates a `FULL OUTER JOIN` with two `LEFT JOIN`s + `UNION ALL` (SQLite doesn't support full outer joins natively).

### `fix` — List or apply remediations

```bash
python winsecaudit.py fix --list                      # show all remediable checks
python winsecaudit.py fix --check "Check Name"        # apply the fix
```

### `dashboard` — Launch the FastAPI read-only dashboard

```bash
python winsecaudit.py dashboard
# Opens http://localhost:8080
```

---

## 🔍 Security Checks

**39 checks across 8 categories**, all auto-discovered via `CheckRegistry.discover()`:

| Category | # | Sample Checks |
|---|---|---|
| 🔐 **Authentication** | 6 | Password complexity, min length, account lockout, guest account, admin rename |
| 🚪 **Access Control** | 5 | UAC level, admin shares, AutoRun, WSH, PowerShell execution policy |
| 🌐 **Network** | 6 | SMBv1 disabled, LLMNR, NetBIOS, WPAD, RDP NLA, NTLMv1 |
| ⚙️ **Services** | 5 | Print Spooler, Telnet, SNMP, FTP, WinRM |
| 🧬 **Kernel** | 4 | Secure Boot, DEP, ASLR, Kernel DMA Protection, VBS/HVCI |
| 🖥️ **System** | 5 | BitLocker, Defender, Firewall, Windows Update, Secure Boot |
| 📝 **Logging** | 4 | Audit policy, PowerShell module logging, script-block logging, Sysmon |
| 🔑 **Credentials** | 4 | Credential Guard, LAPS, WDigest disabled, cached logons |

Each check emits an **immutable `CheckResult`** with CVE IDs, MITRE ATT&CK technique, CIS benchmark ID, severity, weight, and a ready-to-run remediation command.

---

## 🎛️ Profiles

Profiles live in [`profiles/*.yaml`](profiles/) and control three levers:

| Key | Effect |
|---|---|
| `relaxed_checks` | Named checks whose `FAIL` is flipped to `PASS` (with a note). Use for controls intentionally disabled on a machine class. |
| `weight_overrides` | Override the default weight of any check by name. |
| `required_checks` | *(Reserved)* Checks that must pass for the scan to succeed. |

### Bundled Profiles

| Profile | Target | Relaxations |
|---|---|---|
| **`basic`** | Workstations, developer machines | BitLocker, Secure Boot, NTLMv1, PS exec policy, Kernel DMA |
| **`hardened`** | Servers, high-security workstations | None — all checks enforced with higher weights on crypto/creds |

---

## 📊 Scoring & Grading

```
score = (earned_weight / max_possible_weight) × 100
```

| Status | Contribution |
|---|---|
| ✅ **PASS** | earns full check weight |
| ❌ **FAIL** / **ERROR** | earns 0 |
| ⏭️ **SKIPPED** | excluded from numerator *and* denominator |

> **Edge case:** if every check is skipped → `score = 100.0`

### Grade Bands

| Grade | Score Range | Meaning |
|:---:|:---:|---|
| 🟢 **A** | ≥ 90 | Excellent — hardened baseline met |
| 🟢 **B** | ≥ 75 | Good — minor gaps |
| 🟡 **C** | ≥ 60 | Acceptable — remediation recommended |
| 🟠 **D** | ≥ 40 | Poor — significant exposure |
| 🔴 **F** | < 40 | Critical — immediate action required |

---

## 🌐 Threat Intelligence

Every CVE associated with a failed check is enriched from three sources:

| Source | Data | Rate Limit | Cache TTL |
|---|---|---|---|
| **NIST NVD** | CVSS score, severity, description | 5/s anon · 50/s with key | 7 days |
| **FIRST EPSS** | Exploitation probability (0.0–1.0) | None documented | 7 days |
| **CISA KEV** | Known-exploited flag + ransomware use | Bulk download | 24 hours |

Caches live in `data/cve_map.json` and `data/cisa_kev_cache.json`. Enrichment degrades gracefully — a 429 from NVD does not crash the scan; affected CVEs simply ship without TI metadata.

---

## 📄 Output Formats

| Format | File | Highlights |
|:---:|---|---|
| 🖥️ **Terminal** | *(stdout)* | Rich-rendered tables · ANSI colour · live progress |
| 📕 **PDF** | `output/<scan_id>.pdf` | Cover page · executive summary · category breakdown · failure deep-dive · "Page N of M" footer |
| 📘 **DOCX** | `output/<scan_id>.docx` | Word-native styles · FAIL rows bold + italic |
| 📗 **CSV** | `output/<scan_id>.csv` | UTF-8 BOM · scan metadata denormalised per row (SIEM-friendly) |

---

## 🧪 Testing

```bash
python tests/smoke_test.py
```

**10 standalone tests** cover: imports, check discovery, profile loading, scoring math, grade thresholds, DB round-trip, profile relaxation, TI offline cache, CLI entry point, and the full pipeline. No pytest required — exits `0` on success.

```
WinSecAudit v2 — Smoke Tests
========================================
  PASS  01 Import health
  PASS  02 Check discovery
  PASS  03 Profile loading
  PASS  04 Scoring correctness
  PASS  05 Grade thresholds
  PASS  06 DB round-trip
  PASS  07 Profile relaxation
  PASS  08 TI cache offline-safe
  PASS  09 CLI entry point
  PASS  10 Full pipeline
========================================
Results: 10/10 passed
```

---

## ⚠️ Known Limitations

- 🔒 **Elevation required** — Most PowerShell checks call `secedit`, `auditpol`, or protected registry paths. Run from an elevated terminal.
- 🪟 **Windows-only checks** — All checks are PowerShell/Windows-specific. The DB, scoring engine, and exporters are cross-platform.
- 📉 **NVD rate limit** — Without an API key, NVD allows 5 req/s. Set `NVD_API_KEY` to raise this to 50 req/s.
- 📥 **CISA KEV download** — First scan of the day downloads ~5 MB from `cisa.gov`. Subsequent scans within 24 h use the cache.

---

## 📂 Project Structure

```
winsecaudit-v2/
├── winsecaudit.py          # Entry point — forces UTF-8 stdout/stderr on Windows
├── requirements.txt
│
├── checks/                 # 🔍 Security check plugins (auto-discovered)
│   ├── base.py             #    BaseCheck, CheckResult, CheckRegistry
│   ├── auth/               #    Authentication (6)
│   ├── access/             #    Access control (5)
│   ├── network/            #    Network (6)
│   ├── services/           #    Services (5)
│   ├── kernel/             #    Kernel/hardware (4)
│   ├── system/             #    System config (5)
│   ├── logging/            #    Audit & logging (4)
│   └── credentials/        #    Credential protection (4)
│
├── engine/                 # ⚙️ Core orchestration
│   ├── runner.py           #    Parallel check execution
│   ├── scorer.py           #    Weighted scoring
│   ├── comparator.py       #    Profile loading & adjustment
│   ├── risk.py             #    Grade assignment & priority
│   └── threat_intel.py     #    NVD / EPSS / CISA KEV pipeline
│
├── db/                     # 💾 Persistence
│   ├── database.py         #    SQLAlchemy Core layer
│   └── schema.sql          #    Reference DDL
│
├── cli/                    # 🧰 CLI surface
│   ├── main.py             #    Typer commands
│   └── output.py           #    Rich rendering
│
├── dashboard/              # 🌐 FastAPI read-only dashboard
│   ├── app.py
│   ├── models.py
│   └── static/index.html
│
├── exporters/              # 📄 Report generators
│   ├── pdf.py              #    reportlab Platypus
│   ├── docx_export.py      #    python-docx
│   └── csv_export.py       #    csv module
│
├── profiles/               # 🎛️ YAML profiles
│   ├── basic.yaml
│   └── hardened.yaml
│
├── data/                   # 🗃️ Runtime data (gitignored)
└── tests/
    └── smoke_test.py       # ✅ 10 standalone smoke tests
```

---

## 🤝 Contributing

Adding a new check is a three-step affair:

1. **Create** a file under the appropriate `checks/<category>/` directory.
2. **Subclass** `BaseCheck` and set the class attributes (`name`, `category`, `weight`, `severity`, `cve_ids`, `mitre_technique`, `cis_id`, `remediation_cmd`, `remediation_supported`).
3. **Implement** `run() -> CheckResult`. That's it — `CheckRegistry.discover()` picks it up on the next scan.

```python
from checks.base import BaseCheck, CheckResult, CheckStatus, Severity, run_powershell

class MyNewCheck(BaseCheck):
    name = "My New Check"
    category = "System"
    weight = 5
    severity = Severity.HIGH
    remediation_cmd = "Set-ItemProperty ..."
    remediation_supported = True

    def run(self) -> CheckResult:
        value = run_powershell("Get-Something")
        return CheckResult(
            check_name=self.name,
            category=self.category,
            status=CheckStatus.PASS if value == "expected" else CheckStatus.FAIL,
            system_value=value,
            expected_value="expected",
            severity=self.severity,
            weight=self.weight,
            cve_ids=(),
            mitre_technique="",
            cis_id="",
            remediation_cmd=self.remediation_cmd,
            remediation_supported=self.remediation_supported,
        )
```

---

<div align="center">

**Built with ❤️ for defenders.**

[Report Bug](https://github.com/KavyaJain321/winsecaudit-v2/issues) · [Request Feature](https://github.com/KavyaJain321/winsecaudit-v2/issues) · [View Changelog](CHANGELOG.md)

</div>
