Local, Privacy-First Static Application Security Testing (SAST) Platform with Web Dashboard & CLI
SecureCodeAudit (scaudit) is a local, privacy-first static security code review platform for Windows 10/11. Developers and security reviewers give it a single code file, folder, .zip / .tar.gz archive, or local Git repository; it runs 5 parallel static analyzers, deduplicates findings with cross-tool consensus confidence, enriches them with OWASP Top 10:2025, CWE Top 25, CVSS v3.1 / v4.0, and insecure-vs-secure code examples, computes a transparent A–F security grade, and presents actionable remediation guidance through either an offline-capable Web Dashboard (scaudit dashboard) or a Rich Typer CLI (scaudit scan) backed by one shared SQLite WAL database.
- Overview & Core Features
- Installation & Setup (Windows 10/11)
- How to Use SecureCodeAudit (Dual Mode Guide)
- Supported Languages & Export Formats
- Security of the Tool & Threat Mitigations
- Architecture & Project Layout
- Scoring Model & Consensus Deduplication
- Real Audit Results (Vulpy, TrafficScope & SentinelIDS)
- Running Automated Tests & Rule Verification
- Limitations & False Positives
- Technology Stack
- Legal & Ethical Use
- License & Acknowledgments
Important
Static Analysis Only — Zero Target Execution: SecureCodeAudit never imports, compiles/runs, or executes uploaded code, build scripts (setup.py / PEP 517 hooks), or test suites. Dependency vulnerabilities are scanned by parsing manifests statically in pure Python, and analyzer configs inside untrusted repos (.bandit, .semgrepignore) are isolated and ignored.
- Dual-Mode Operation on One Engine:
- Web Dashboard (
scaudit dashboard --open): Localhost (127.0.0.1:8080) FastAPI web UI with drag-and-drop upload, browser file/folder pickers, local path scan, live SSE tool progress, interactive Chart.js analytics, file risk heatmap, Pygments syntax-highlighted code viewer, triage controls, drift comparison, and zero external CDN calls at runtime. - Standalone CLI (
scaudit): Typer CLI with Rich terminal summary tables, JSON/SARIF/Markdown/HTML/Coding Guide export, triage, scan comparison, dry-run/apply patch generation, custom rule testing, and CI--fail-onexit codes. Scans run in CLI are immediately viewable in the dashboard.
- Web Dashboard (
- 5 Parallel Static Analyzers: Combines Bandit (Python security linter), Semgrep (local YAML rules in
rules/), Secrets (detect-secrets+ custom regex/Shannon entropy checks with automatic masking), Dependencies (zero-exec static manifest parser + Google OSV Batch API with 24h SQLite TTL cache &--offlineskip), and Python AST (custom AST detectors + intra-procedural source-to-sink taint traces). - Consensus Deduplication & Enrichment: Clusters overlapping hits within
±3lines on the same file, boosts confidence when 2+ analyzers agree, and maps every finding to OWASP Top 10:2025 (with 2021 alias), 2025 CWE Top 25, CVSS v3.1 / v4.0 score + justification, Why This Is Dangerous, remediation steps, and insecure-vs-secure examples. - Deterministic Auto-Fix Patching (
scaudit fix): Generates clean unified-diff patches (.patchdry-run by default) for deterministic fixes such asyaml.load->yaml.safe_load,verify=False->verify=True,debug=False/ loopback binding,tempfile.mktemp->NamedTemporaryFile, weak hashes, and vulnerablerequirements.txtpins.
Tip
No Admin Privileges Required: Unlike live packet sniffers, SecureCodeAudit runs entirely in a normal (non-Admin) PowerShell terminal for both the CLI and the Web Dashboard.
- Python 3.11+ (tested on Python
3.13.13, 64-bit Windows 10/11). Ensure "Add Python to PATH" is checked during setup. - Git (optional, for cloning the repository).
git clone https://github.com/Jaindu-Net/CodeAlpha_SecureCodeAudit.git
cd CodeAlpha_SecureCodeAudit
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"Note
If PowerShell blocks .\.venv\Scripts\Activate.ps1 with an execution policy error, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once and retry.
scaudit doctorConfirm that Python Runtime, SQLite Storage, bandit, semgrep, secrets, deps, ast_python, and Windows UTF-8 Mode report OK / READY.
- If
OSV API NetworkshowsOFFLINE, all code analyzers still work offline—simply use--offline(CLI) or tick Offline mode (Web UI). - (Windows Note:) If Windows Smart App Control blocks
semgrep-core.exe, installopengrep.exeonPATH(scauditautomatically checksopengrepas a fallback or skips Semgrep gracefully with a warning without crashing).
Choose whichever mode fits your workflow—both run scaudit.core.pipeline.run_scan_pipeline() and persist into the exact same SQLite database (%LOCALAPPDATA%\SecureCodeAudit\scaudit.db).
Start the web dashboard locally (bound strictly to 127.0.0.1:8080 by default):
# Launch Web Dashboard and open http://127.0.0.1:8080 in your browser
scaudit dashboard --open
# Custom port without auto-opening browser
scaudit dashboard --port 8090Note
Keep the PowerShell window open while using the web dashboard; press Ctrl + C to stop the server cleanly.
- Upload or Select a Target (
New Scan):- Drag and drop code files, a folder, or a
.zip/.tar.gzarchive onto the upload zone, OR click Select File(s) / Archive / Select Folder. - Alternatively, enter a local folder/file/archive path in "Or scan a local path..." and click Scan Local Path.
- Toggle individual analyzers (Bandit, Semgrep, Secrets, Dependencies (OSV), Python AST) or tick Offline mode (skip OSV lookup).
- Drag and drop code files, a folder, or a
- Watch Live SSE Progress:
- Monitor per-analyzer execution status (
pending,success,skipped,timeout,error), finding counts, and timings via Server-Sent Events (/api/jobs/{job_id}/events).
- Monitor per-analyzer execution status (
- Inspect
Overview& Analytics:- View the A–F Security Grade and score (
/ 100), grade caps applied, severity breakdown, and skipped-file inventory. - Explore the Severity Distribution doughnut, OWASP Top 10:2025 bars, Language Breakdown, Tool Agreement & Consensus, and Top 10 Riskiest Files.
- Click any block in the File Risk Heatmap to open filtered findings for that exact file.
- View the A–F Security Grade and score (
- Investigate & Triage Findings (
Findings-> Finding Detail):- Search and filter by Severity, CWE, OWASP category, Analyzer tool, or Triage status; sort by Severity, CVSS, Consensus, File, or CWE; group flat or by File / OWASP / CWE; apply Bulk Triage.
- Click any finding title to open the Finding Detail view:
- Syntax-highlighted Pygments source viewer with the vulnerable line highlighted and secrets masked
- CWE, OWASP Top 10:2025, CVSS v3.1 / v4.0 vector + justification, and Python Source-to-Sink Trace (for injection sinks)
- Why This Is Dangerous, How to Fix, Insecure vs. Secure Pattern, and Suggested Auto-Fix Patch (Dry-Run Preview)
- Triage Decision (
Open,True Positive,False Positive,Accepted Risk) with analyst comment—savingFalse PositiveorAccepted Riskimmediately recalculates the scan's active security score
- Compare Drift, View History & Export Reports:
- Use Compare to diff Baseline (
A) vs Current (B) scans (New, Fixed, Unchanged, and Score Delta). - Use History to track security score trends over time across CLI and Web scans.
- Open Reports to download HTML, Markdown, JSON, SARIF 2.1.0, or the auto-generated Secure Coding Guide (
MD/HTML). Toggle Dark / Light Mode anytime in the navbar.
- Use Compare to diff Baseline (
# 1. Scan a folder, file, archive, or git repo with Rich terminal tables
scaudit scan D:\path\to\project
# 2. Offline scan (skip OSV dependency API calls) showing Low+ severity only
scaudit scan D:\path\to\project --offline --min-severity low
# 3. Export directly to HTML, Markdown, JSON, SARIF 2.1.0, or Secure Coding Guide
scaudit scan D:\path\to\project --format html -o audit-report.html
scaudit scan D:\path\to\project --offline --format sarif -o audit.sarif
# 4. List past scans and inspect a single finding in detail
scaudit history
scaudit show <finding_id>
# 5. Triage a finding from CLI (recomputes active score in SQLite)
scaudit triage <finding_id> --status fp --comment "Static allowlisted identifier"
# 6. Preview deterministic auto-fix patches (dry-run by default) or write a .patch file
scaudit fix <scan_id> --dry-run
scaudit fix <scan_id> --dry-run -o remediation.patch
# 7. Apply safe single-line patches locally (requires interactive confirmation or --yes)
scaudit fix <scan_id> --apply
# 8. Compare before-fix vs after-fix scans
scaudit compare <scan_id_A> <scan_id_B>
# 9. Verify custom Semgrep YAML rule positive/negative test cases
scaudit rules test
# 10. CI quality gate (exit code 1 if active High/Critical findings exist)
scaudit scan D:\path\to\project --offline --fail-on high --format sarif -o audit.sarifCLI Exit Codes: 0 = clean / under --fail-on threshold, 1 = active findings at or above --fail-on (or rule test failure), 2 = usage, ingest validation, or execution error.
| Command | Arguments / Purpose |
|---|---|
scaudit scan <target> |
Statically analyze a file, folder, .zip/.tar.gz archive, or repo and save to SQLite |
scaudit dashboard |
Start the local FastAPI web dashboard (default 127.0.0.1:8080) |
scaudit report <scan_id> |
Export an existing scan to html, md, json, sarif, or guide (--format, -o) |
scaudit history |
Display recent scans from SQLite (--limit, --db) |
scaudit show <finding_id> |
Print masked snippet, CWE/OWASP/CVSS metadata, and remediation for one finding |
scaudit compare <scan_a> <scan_b> |
Show Score Delta plus New, Fixed, and Unchanged findings between two scans |
scaudit triage <finding_id> |
Set triage (open, tp, fp, accepted) with --comment and refresh active score |
scaudit fix <scan_id> |
Preview unified diff patches (--dry-run default, -o), or --apply (-y) locally |
scaudit rules test |
Run positive and negative tests for custom Semgrep rules in rules/ |
scaudit doctor |
Verify Python version, SQLite write access, all 5 analyzers, OSV connectivity, and UTF-8 mode |
| Option | Default | Description |
|---|---|---|
--tools |
all 5 enabled | Comma-separated subset: bandit,semgrep,secrets,deps,ast_python |
--offline |
False |
Skip network lookups (deps skips OSV API cleanly with SKIPPED status) |
--format |
table |
Output format: table, json, sarif, md, html, or guide |
--output, -o |
None |
Write rendered output (or Markdown summary when --format table) to file |
--fail-on |
None |
Return exit code 1 if active findings meet/exceed low, medium, high, or critical |
--min-severity |
info |
Minimum severity shown in CLI summary table (info..critical) |
--timeout |
120 |
Per-analyzer subprocess timeout in seconds (5–600) |
--db |
OS app data | Override SQLite database file path (or set SCAUDIT_DB env var) |
--host / --port |
127.0.0.1 / 8080 |
Dashboard bind interface & HTTP port (dashboard command) |
--allow-remote |
False |
Required to bind dashboard beyond loopback (automatically disables local-path scan) |
| Target Type / Language | Analyzers Applied | Notes |
|---|---|---|
Python (.py, .pyw, .pyi) |
Bandit + Semgrep + Python AST (+ Taint Trace) + Secrets | Deepest coverage: multi-engine consensus, custom YAML rules (rules/python-custom.yaml), AST sinks (eval, exec, pickle, yaml.load, weak hashes, Flask debug=True, 0.0.0.0 bind, shell=True, formatted SQL), and intra-procedural source-to-sink trace |
| JavaScript / TypeScript | Semgrep + Secrets | Covers child_process.exec injection, eval/new Function, DOM innerHTML XSS, TLS verification disabled, and hardcoded secrets |
| Java, PHP, Go, C/C++, Ruby, Shell, YAML, Dockerfile, Config | Semgrep + Secrets | Uses offline cached multi-language rules (rules/cache/owasp-multi.yaml) + regex/entropy secret checks |
| Dependencies & Lockfiles | Static Manifest Parser + OSV Batch API v1 | Statically parses requirements*.txt, pyproject.toml, poetry.lock, uv.lock, Pipfile.lock, package-lock.json, and go.mod without executing package managers |
| Skipped Files | Explicitly tracked in skipped_files |
Binary files, minified .min.js/.min.css bundles, vendor dirs (__pycache__, .venv, node_modules, vendor, .git), oversized files, and unsupported extensions are logged transparently rather than silently dropped |
| Format | CLI Flag / UI Route | Details |
|---|---|---|
| HTML Report | --format html |
Self-contained offline report with CSS styling, score card, and strict html.escape() XSS protection |
| Markdown Report | --format md |
Structured GFM summary, severity counts, analyzer execution table, findings, and skipped files |
| Canonical JSON | --format json |
Complete Pydantic ScanResult export matching shared SQLite schema |
| SARIF 2.1.0 | --format sarif |
Validated against the official OASIS sarif-schema-2.1.0.json schema for GitHub Code Scanning / CI |
| Secure Coding Guide | --format guide |
Auto-generated remediation handbook (MD or HTML) covering only the vulnerability classes actually discovered in the scan |
Because a SAST tool processes untrusted codebases and archives, SecureCodeAudit treats uploaded targets as hostile input (documented in full in docs/threat-model.md):
| Threat Vector | Implemented Defense |
|---|---|
| Code Execution via Target Files | Uploaded files are never imported or executed; dependency extraction uses pure-Python tomllib, json, and packaging.requirements instead of running pip or npm |
| Zip-Slip & Path Traversal | sanitize_rel_path() blocks .., absolute paths, drive letters (C:), UNC paths, null bytes, trailing spaces/dots, and Windows reserved device names (CON, NUL, COM1..LPT9), verifying Path.resolve().is_relative_to(sandbox) before every write |
| Zip Bombs & Archive Floods | Streaming extraction enforces 50 MiB compressed upload, 100 MiB extracted total, 5 MiB single file, 5,000 files max, and 50:1 compression ratio using actual decompressed byte counts rather than trusting archive headers |
| Symlink / Hardlink Escapes | Rejects Unix S_ISLNK, Windows DOS reparse point attribute (0x400), tar symlinks/hardlinks/device nodes, and disables symlink traversal (followlinks=False) during inventory walks |
Config Sabotage (.bandit, .semgrepignore) |
Bandit receives a controlled --ini outside the target; Semgrep runs --no-git-ignore --disable-version-check --metrics=off strictly against scaudit's own rules/ directory |
| Secret Leakage in Outputs | redact_text() and RedactingLogFilter mask tokens, PEM keys, and URI credentials before writing logs, SQLite rows, UI responses, or reports |
| Dashboard XSS, CSRF & Remote Probe | Loopback-only binding by default (--allow-remote disables /api/scans/local-path), SameSite=Strict cookie + X-CSRF-Token verification, Content-Security-Policy: default-src 'self', strict Jinja2 autoescaping, and sandbox temp cleanup after scans |
Both the Typer CLI and FastAPI Web UI share the exact same core pipeline and SQLite WAL database:
flowchart LR
CLI["Typer CLI (scaudit)"]
WEB["FastAPI Web Dashboard (127.0.0.1:8080)"]
ING["Safe Ingest (Zip-Slip, Zip-Bomb, Symlink, Windows Guards)"]
INV["Static Inventory (Language, LOC, Skips, Manifests)"]
B["Bandit (Python)"]
S["Semgrep / Opengrep (Local rules/)"]
SEC["Secrets (detect-secrets + Regex/Entropy)"]
DEP["Deps (Static Manifests -> OSV Batch API)"]
AST["Python AST + Source-to-Sink Trace"]
NORM["Normalize + Mask Secrets + Consensus Clustering"]
ENR["Enrich (OWASP 2025, CWE Top 25, CVSS, Offline KB)"]
SCR["Transparent A-F Scorer"]
DB[("Shared SQLite WAL DB")]
OUT["Reports (HTML, MD, JSON, SARIF, Guide) & Dry-Run Fixes"]
CLI --> ING
WEB --> ING
ING --> INV
INV --> B & S & SEC & DEP & AST
B & S & SEC & DEP & AST --> NORM --> ENR --> SCR --> DB
DB --> CLI & WEB & OUT
| Path | Responsibility |
|---|---|
| scaudit/config.py, logging_setup.py | AppConfig, IngestLimits, ExitCode, language/manifest maps, and RedactingLogFilter |
| scaudit/core/ | Safe archive/upload/local ingest (ingest.py), language/skip/LOC inventory (inventory.py), pure-Python manifest parsers (manifests.py), and parallel orchestrator (pipeline.py) |
| scaudit/analyzers/ | Unified adapter protocol (base.py), bandit_adapter.py, semgrep_adapter.py, secrets_adapter.py, deps_adapter.py, ast_python.py, and custom rule test runner (rules_runner.py) |
| rules/ | Offline multi-language OWASP rules (rules/cache/owasp-multi.yaml) and custom Python rules + test cases (rules/python-custom.yaml, rules/python-custom.test.py) |
| scaudit/normalize/ | Canonical Pydantic v2 models (schema.py), secret redaction (redact.py), tool-to-canonical mappers (mappers.py), and ±3 line consensus clustering (dedup.py) |
| scaudit/enrich/ | OWASP Top 10:2025 (owasp_2025.py), CWE Top 25 (cwe_top25.py), CVSS v3.1 / v4.0 (cvss.py), offline remediation KB (knowledge_base.json), and enricher.py |
| scaudit/scoring/scorer.py | Transparent LOC-normalized A–F grading and per-file risk scoring |
| scaudit/storage/ | SQLite WAL manager (db.py), versioned migrations (migrations.py), and scan/finding/triage repository (repository.py) |
| scaudit/fixes/ | Deterministic single-line patch templates (templates.py) and unified-diff generator/applier (patcher.py) |
| scaudit/reports/ | html_report.py, markdown_report.py, json_report.py, sarif_report.py, and coding_guide.py |
| scaudit/cli/ | Typer entrypoint (app.py) and subcommands (cmd_scan.py, cmd_dashboard.py, cmd_results.py, cmd_ops.py) |
| scaudit/web/ | FastAPI app (app.py), SSE job manager (state.py), REST/SSE routes (routes_api.py), HTML pages (routes_pages.py), local static JS/CSS/Chart.js (static/), and Jinja2 views (templates/) |
| tests/ | 52 automated tests covering ingest security, redaction, inventory, analyzers, SARIF OASIS schema, CLI, Web API/CSRF, fixes, and accuracy fixtures |
| docs/, samples/ | Architecture, methodology, threat model, secure coding guide, real audit report, and before/after sample exports |
- Consensus Clustering (
scaudit/normalize/dedup.py): Findings targeting the same relative path within±3lines and sharing a vulnerability family or CWE ID (or same dependency package/advisory) merge into one finding, keeping alldetected_bytools and elevating confidence tohighwhenconsensus_count >= 2. - Transparent A–F Grading (
scaudit/scoring/scorer.py):- Excludes findings triaged as
false_positiveoraccepted_risk. - Weights each active finding:
SEVERITY_WEIGHT(Critical=15,High=8,Medium=3,Low=1,Info=0) ×CONFIDENCE_MULTIPLIER(high=1.0,medium=0.75,low=0.5). - Computes LOC-normalized density (
kloc = max(0.2, total_loc / 1000)) and penalty100 * (1 - exp(-(points / kloc) / 40)). - Applies explicit safety caps: any active Critical caps score at 59.0 (Grade D); any active High caps score at 74.0 (Grade C).
- Excludes findings triaged as
Full tool comparison matrices, manual OWASP/ASVS findings, false-positive tallies, and verified fixes are documented in docs/real-audit-report.md and archived under samples/:
| Target Audited | Before Audit | Action / Fixes Applied | After Audit & Verification |
|---|---|---|---|
fportantier/vulpy (bad/) (MIT) |
Grade F (5.6 / 100) — 21 static hits (9 High, 8 Medium, 3 Low, 1 Info) + 7 manual logic/template flaws |
Wrote 13 remediation fixes (parameterized SQL, salted scrypt hashes, HMAC session signing, SHA-256 hashed API keys in SQLite, Jinja auto-escaping, POST MFA disable, env SECRET_KEY, debug=False) |
Grade A (97.1 / 100), +91.5 score delta, 20 findings fixed (vulpy-compare.txt) |
CodeAlpha_TrafficScope (Task 01) |
Grade A (99.8 / 100) — 1 Low (except Exception: pass), plus initial Semgrep JS regex FP tuned |
Replaced silent exception swallow in capture/capturer.py:264 with explicit OSError debug logging and tightened scaudit.js.child-process-exec Semgrep rule |
Grade A (100.0 / 100), 0 Low/Med/High/Crit findings, 52/52 tests passing (trafficscope-after.md) |
CodeAlpha_SentinelIDS (Task 02) |
77.0 active pts (5 High) |
Replaced dynamic SQL table interpolation in storage/repository.py with static _TABLE_DESC_QUERIES allowlist and removed PRAGMA f-string interpolation |
61.0 active pts (0 Semgrep hits), 35/35 tests passing (sentinelids-after.md) |
SecureCodeAudit (scaudit/) |
Self-audit baseline | Eliminated innerHTML usage in sse.js, filtered vendor JS bundles (vendor/), removed SQL sort f-strings in repository.py, and passed offline CI SARIF gate (--fail-on critical) |
0 exploitable bugs, 0 Critical findings (scaudit-self-audit.md) |
All 52 unit and integration tests run locally with pytest, and custom Semgrep YAML rules are verified independently via scaudit rules test:
# Run the full automated test suite (ingest security, redaction, analyzers, SARIF, CLI, Web API, fixes)
pytest tests -v
# Verify custom Semgrep rule positive and negative test cases
scaudit rules test
# Run Ruff linter across package and tests
ruff check scaudit tests
# Run the repository's own offline CI gate
scaudit scan scaudit --offline --fail-on critical --format sarif -o self-audit.sarif- Intra-Procedural Python Taint Only:
ast_pythontraces source-to-sink flows within single functions/route handlers; multi-hop cross-module helper chains and missing endpoint authorization checks (CWE-862,CWE-352) require manual review using docs/methodology.md. - Unpinned Dependency Ranges: Because package managers (
pip,npm) are never executed on untrusted projects, open version ranges such asflask>=2.0cannot be resolved to exact CVE matches without a pinned version or lockfile. - Per-Language Analyzer Depth: Python receives 3 independent code engines (
bandit,semgrep,ast_python) plussecretsanddeps; JavaScript/TypeScript, Java, PHP, Go, C/C++, Ruby, and config files rely on offlinesemgreppacks,secrets, and lockfiledeps. - Conservative SAST Warnings: Literal fallback IPs (
"0.0.0.0"), intentionalassertstatements outside test dirs, or static allowlist query dictionaries may still raise conservativeInfo/ heuristic warnings and can be recorded cleanly via Triage (False Positive/Accepted Risk).
| Component | Technology |
|---|---|
| Core Language & Schemas | Python 3.11+ + Pydantic v2 (StrEnum, canonical models) |
| Static Analyzers | Bandit + Semgrep + detect-secrets + Python ast + Regex/Entropy |
| Dependency Advisory Scan | Pure-Python manifest parsers (tomllib, json, packaging) + Google OSV Batch API v1 (httpx) |
| Web Dashboard & API | FastAPI + Uvicorn + Jinja2 + Server-Sent Events (SSE) + Chart.js (bundled locally) |
| CLI & Terminal UI | Typer + Rich |
| Code Highlighting & Reports | Pygments + SARIF 2.1.0 (jsonschema) + HTML / Markdown / JSON / Coding Guide |
| Database | SQLite (WAL mode, parameterized queries, schema migrations) |
| Testing, Linting & CI | pytest, pytest-asyncio, Ruff, GitHub Actions, pre-commit |
- Use SecureCodeAudit strictly for defensive code review, authorized security assessments, and educational learning on software you own or have explicit permission to audit.
- SecureCodeAudit analyzes target source code statically on your local machine; unless
--offlineis omitted (which sends only parsed open-source package names/versions toapi.osv.devfor CVE lookup), no code or findings ever leave your machine.
- License: Licensed under the MIT License — see LICENSE for full text.
- CodeAlpha: Cyber Security Internship Program (
CodeAlpha_SecureCodeAudit). - Open-Source Libraries & Standards: Bandit, Semgrep, detect-secrets, FastAPI, Typer, Rich, Pygments, Chart.js, Google OSV, OWASP Top 10:2025, MITRE CWE Top 25, OASIS SARIF 2.1.0, and
fportantier/vulpy(MIT audit benchmark).
Developed by Jaindu De Zoysa — CodeAlpha Cyber Security Internship (Task 03)