KALPA: Causal Cyber Reasoning System for AI Kavach
KALPA is an autonomous Causal Cyber Reasoning System (CRS) designed to discover vulnerabilities, reconstruct causal root causes, synthesize minimal code patches, compile durable security contracts, and prove fix robustness through a self-adversarial repair loop without human intervention. Built for mission-critical defense software in the simulated Indian Armed Forces operational environments (AI Kavach).
📑 Table of Contents
- Executive Overview & Motivation
- Causal Cyber Reasoning vs. Symptom Patching
- System Architecture Overview
- Key System Components & File Directory
- Feature Matrix & Core Capabilities
- Installation & Setup
- Comprehensive Usage Manual
- Configuration & Environment Variables
- Auditable Evidence Bundle Specification
- Benchmark Results & Performance Indicators
- Testing & Verification
- Project Documentation & Audit Dossier
🏛️ Executive Overview & Motivation
Defense and national security software operates under extreme reliability and security constraints. Vulnerabilities in military microservices or embedded software can translate directly into mission failure, operational compromise, or loss of life. Traditional vulnerability management workflows—manual code triage, human-written patches, slow regression testing cycles, and correlational static scanners—cannot scale with complex, evolving codebases.
AI Kavach challenges participants to build a Cyber Reasoning System (CRS) that lace Large Language Models (LLMs) with fuzzers, static/dynamic analyzers, and a regression harness to autonomously discover vulnerabilities, patch them, and prove fixes hold without human intervention.
🎯 Causal Cyber Reasoning vs. Symptom Patching
Most automated patching tools perform superficial correlational fixes (e.g., masking error return values or wrapping code in try/catch blocks). KALPA introduces Causal Cyber Reasoning:
- Reconstructing Root Causes: Traces input taint propagation through intermediate control and data flows directly to the exploit sink.
- Targeted Causal Interventions: Synthesizes minimal code diffs that remove the true root cause while preserving 100% of legitimate system functionality.
- Executable Security Contracts: Compiles vulnerability knowledge into durable security contracts (assertions, pytest regression suites, and fuzzing oracles).
- Self-Adversarial Repair Loop: Attempts to re-exploit patched binaries using automated fuzzing and regression tests to prove fix robustness.
⚡ System Architecture Overview
+------------------------------------+
| Target Intake & Code Slicing |
+-----------------+------------------+
|
v
+------------------------------------+
| Static & Dynamic Analysis / Fuzz |
| (SARIF, Sanitizers, POV Inputs) |
+-----------------+------------------+
|
v
+------------------------------------+
| KALPA Causal Reasoning Engine |
| (LLM Brain & Causal Graph JSON) |
+-----------------+------------------+
|
v
+------------------------------------+
| Patch & Security Contract Compiler |
| (Code Diffs + Assertions & Oracles)|
+-----------------+------------------+
|
v
+------------------------------------+
| Self-Adversarial Validation Loop |
| (Regression Tests & Refuzzing) |
+-----------------+------------------+
|
v
+------------------------------------+
| Evidence Bundle & Report |
| (POVs, Diffs, Contracts, Metrics) |
+------------------------------------+
📦 Key System Components & File Directory
| Module | Responsibility | Key Implementation File |
|---|---|---|
| Static Analyzer | Ingest SARIF reports, AST Python analysis, C/C++ regex scan, code line-slicing | kalpa/static_analysis/analyzer.py |
| SARIF Parser | Standard SARIF 2.1.0 and Bandit/Semgrep report intake | kalpa/static_analysis/sarif_parser.py |
| Dynamic Fuzzer | Payload mutation engine, dynamic test runner, crash & sanitizer log tracer | kalpa/dynamic_analysis/fuzzer.py |
| C Harness Generator | AFL++/libFuzzer C harness auto-generator (LLVMFuzzerTestOneInput) |
kalpa/dynamic_analysis/c_harness_generator.py |
| POV Generator | Confirmed Proof-of-Vulnerability payload generation | kalpa/dynamic_analysis/pov_generator.py |
| Causal LLM Brain | Causal narrative builder, root-cause identifier, intervention strategy ranker | kalpa/causal_engine/reasoner.py |
| Local LLM Provider | Air-gapped Ollama (/api/chat) and vLLM (/v1/chat/completions) provider |
kalpa/causal_engine/local_provider.py |
| Patch Synthesizer | Minimal, syntactically correct code diff synthesizer (Python & C/C++ strncpy/snprintf) |
kalpa/patching/synthesizer.py |
| Contract Compiler | Translates fixes into code assertions, pytest contracts, and fuzzing oracles | kalpa/contract_compiler/compiler.py |
| CI/CD Exporter | Generates GitHub Actions non-regression workflows (.github/workflows/kalpa_contracts.yml) |
kalpa/contract_compiler/cicd_exporter.py |
| Orchestrator Loop | Central controller managing intake $\to$ fuzz $\to$ patch $\to$ re-attack $\to$ accept/reject decision | kalpa/orchestrator/controller.py |
| Web Dashboard API | FastAPI backend serving status, CRS runner, and evidence bundle endpoints | kalpa/dashboard/app.py |
| Daemon File Watcher | Polls files tracking (st_mtime, st_size) signatures to eliminate redundant re-reads |
kalpa/utils/file_watcher.py |
🛠️ Feature Matrix & Core Capabilities
- 🐍 Python Microservice Support: Detects and patches SQL Injection, Path Traversal, Command Injection, and Auth flaws in Flask, FastAPI, and SQLAlchemy microservices.
- ⚙️ Native C/C++ Service Support: Detects and remediates Buffer Overflows (
strcpy$\to$strncpy,sprintf$\to$snprintf), format string issues, and unsafesystem()calls under AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan). - 🔒 100% Air-Gapped Local LLM Inference: Direct integration with local Ollama or vLLM inference servers (
DeepSeek-Coder,Llama-3) with strict JSON schema validation. - 🌐 Interactive Defense Operations Web Dashboard: FastAPI backend with a warm off-white terracotta UI, SVG Causal Graph visualizer, real-time telemetry stream, and code diff modal inspector.
- ⚙️ CI/CD Security Contract Exporter: Automatically outputs GitHub Actions workflows (
.github/workflows/kalpa_contracts.yml) to enforce non-regression on every git commit. - 📜 Strict Compliance Rules:
- SQLAlchemy ORM Read Methods: All queries call
session.expunge_all()beforesession.close()withlazy="subquery"relationships. - SQLite UTC-Naive Datetime Normalization: Normalizes datetimes to UTC-naive at input parse layer via
normalize_to_utc_naive()strippingtzinfo. - File-Polling Signature Cache: Daemon file watcher tracks
(st_mtime, st_size)in_file_seen_signatureto prevent duplicate re-read overhead.
- SQLAlchemy ORM Read Methods: All queries call
🚀 Installation & Setup
Prerequisites
- Python 3.9 or higher
- GCC / Clang (for native C/C++ targets)
- Docker & Docker Compose (optional for containerized run)
Setup Steps
# 1. Clone repository
git clone https://github.com/YOUR_USERNAME/kalpa.git
cd kalpa
# 2. Install dependencies
pip install -r requirements.txt
📖 Comprehensive Usage Manual
1. Single-Command CLI Execution
Run KALPA autonomously against any target codebase (Python microservice or C/C++ service):
python run_kalpa.py --target targets/vulnerable_service --output-dir evidence_bundles
2. Air-Gapped Local LLM Execution (Ollama / vLLM)
To execute KALPA in classified defense networks using a locally hosted LLM without internet connectivity:
python run_kalpa.py --target targets/vulnerable_service --provider ollama --ollama-host http://localhost:11434 --model deepseek-coder
3. Interactive Defense Operations Web Dashboard
Launch the FastAPI web dashboard server:
python run_kalpa.py --dashboard
Open your browser at http://127.0.0.1:8000 to access the warm off-white terracotta dashboard featuring interactive SVG Causal Graph rendering, real-time log streaming, and side-by-side patch diff inspection.
4. Docker Container Deployment
Run KALPA inside an air-gapped Docker container:
# Build container image
docker build -t kalpa-crs .
# Run autonomous loop
docker run --rm -v $(pwd)/evidence_bundles:/app/evidence_bundles kalpa-crs --target targets/vulnerable_service
Or using Docker Compose:
docker-compose up --build
5. AI Kavach Evaluation Suite
Benchmark KALPA across all target codebases to compute AI Kavach performance metrics:
python eval_kalpa.py --targets-dir targets --output eval_report.json
Outputs machine-readable eval_report.json and human-readable eval_report.md.
6. CI/CD Security Contract Exporter
Export ready-to-commit GitHub Actions workflows:
python run_kalpa.py --target targets/vulnerable_service --export-cicd
Creates .github/workflows/kalpa_contracts.yml to automatically verify security contracts on git push.
⚙️ Configuration & Environment Variables
| Variable | Description | Default Value |
|---|---|---|
LLM_PROVIDER |
Reasoning provider mode (auto, openai, ollama, vllm, rule_based) |
auto |
LLM_MODEL |
Remote LLM model name | gpt-4o |
LLM_API_KEY |
Remote API Key (OpenAI / Anthropic) | None |
OLLAMA_HOST |
Local Ollama / vLLM endpoint URL | http://localhost:11434 |
LOCAL_MODEL |
Local LLM model name | deepseek-coder |
MAX_FUZZ_TIME |
Maximum fuzzing budget per vulnerability (seconds) | 30 |
🛡️ Auditable Evidence Bundle Specification
Every fix processed by KALPA exports an auditable Evidence Bundle to evidence_bundles/<VULN_ID>/:
evidence_bundle.json: Complete machine-readable findings, causal explanation, and metrics.causal_explanation.md: Causal narrative detailing root cause and taint path.patch.diff: Unified code diff.test_contract_*.py: Executable pytest security contract.
📊 Benchmark Results & Performance Indicators
Evaluated using eval_kalpa.py across benchmark targets:
| Target Service | Language | Found | Fixed | Patch Success Rate (PSR) | MTTR (s) |
|---|---|---|---|---|---|
vulnerable_service |
Python (Flask/SQLAlchemy) | 2 | 2 | 100.0% | 2.51s |
vulnerable_cpp_service |
C/C++ (GCC/ASan) | 4 | 2 | 50.0% | 2.26s |
| TOTAL BENCHMARK | Multi-Language | 6 | 4 | 66.7% | 2.42s |
🔬 Testing & Verification
Run the full framework unit and integration test suite (100% pass rate):
python -m unittest discover -s tests -p "test_*.py"
📑 Project Documentation & Audit Dossier
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kalpa_crs-2.0.0.tar.gz.
File metadata
- Download URL: kalpa_crs-2.0.0.tar.gz
- Upload date:
- Size: 35.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
80acc9b956a7a588dd0fcf03844677da8072e50b596a94ae2e598486daa668e0
|
|
| MD5 |
5b506204759b60466a36d38598fd53c5
|
|
| BLAKE2b-256 |
712d046b60ad19afad744e8c633b1745e7addabfe6700bb74f382fb5f96b4c3f
|
File details
Details for the file kalpa_crs-2.0.0-py3-none-any.whl.
File metadata
- Download URL: kalpa_crs-2.0.0-py3-none-any.whl
- Upload date:
- Size: 34.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7155804fc64686ce81f4347a4623ed3fcf7677261a4c6ad703119c913d45ef3a
|
|
| MD5 |
87422e86a908afecd3aff72ed3927395
|
|
| BLAKE2b-256 |
106850e34c644c1b7bde874efdd0755aaf5f72358ea46f99648317d001d335eb
|