<div align="center">

<img src="media/logo.png" width="80" alt="CipherNest logo" />

# CipherNest

**Open Source AI Application Security Platform**

[![Version](https://img.shields.io/badge/version-v0.7.0-blue)](https://github.com/vmmuthu31/CipherNest)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![OWASP](https://img.shields.io/badge/OWASP-Top%2010%20%2B%20LLM%20Top%2010-red)](https://owasp.org/www-project-top-ten/)
[![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)

Most security tools were built before AI agents existed.  
CipherNest was built for the world where your code ships with an LLM attached to a database.

</div>

---

## Why CipherNest?

Most security tools stop at source code.

CipherNest secures the entire AI application stack.

| Layer                        | Coverage |
| ---------------------------- | -------- |
| Application Code             | ✓        |
| AI Prompts                   | ✓        |
| AI Agents                    | ✓        |
| MCP Servers                  | ✓        |
| Secrets & Credentials        | ✓        |
| Dependencies & Supply Chain  | ✓        |
| GitHub Actions & CI/CD       | ✓        |
| Docker & Containers          | ✓        |
| Kubernetes                   | ✓        |
| Infrastructure as Code       | ✓        |
| Runtime MCP Tool Calls       | ✓        |
| Attack Chains & Threat Paths | ✓        |

from a single security engine.

---

## Screenshots

### Security Dashboard

<img width="100%" alt="Dashboard" src="https://github.com/user-attachments/assets/bee691d0-f397-4ad2-b23a-0ef11fba8387" />

### Attack Graph

<img width="100%" alt="AttackGraph" src="https://github.com/user-attachments/assets/4a7d14a6-7f7c-4ab1-b4ec-14f772d1f37f" />

### NPM Shield

<img width="100%" alt="NPM Shield" src="https://github.com/user-attachments/assets/ac4cd750-dac4-4352-aaba-b21f8ca3c2e5" />

### Agent Permission Map

<img width="100%" alt="PermissionGraph" src="https://github.com/user-attachments/assets/c681c5a3-2e58-4d43-8b56-1130f8ce9d28" />

## Comparison

| Feature             | CipherNest | Semgrep | Snyk    | SonarQube |
| ------------------- | ---------- | ------- | ------- | --------- |
| Code Security       | ✓          | ✓       | ✓       | ✓         |
| LLM Security        | ✓          | ✗       | Partial | ✗         |
| MCP Security        | ✓          | ✗       | ✗       | ✗         |
| Agent Security      | ✓          | ✗       | ✗       | ✗         |
| Prompt Injection    | ✓          | ✗       | ✗       | ✗         |
| Attack Graphs       | ✓          | Partial | Partial | ✗         |
| Runtime MCP Gateway | ✓          | ✗       | ✗       | ✗         |
| Security Benchmark  | ✓          | ✗       | ✗       | ✗         |

---

## Quick start

```bash
npx ciphernest scan .
ciphernest benchmark .
```

Add CipherNest to any AI agent through MCP:

```json
{
  "mcpServers": {
    "ciphernest": {
      "command": "npx",
      "args": ["-y", "@ciphernest/mcp-server"]
    }
  }
}
```

---

## What CipherNest covers

| Layer            | What it scans                                                                                  |
| ---------------- | ---------------------------------------------------------------------------------------------- |
| **Code**         | OWASP Top 10 — SQLi, XSS, eval, path traversal, XXE, SSRF, RCE                                 |
| **LLM / AI**     | OWASP LLM Top 10 — prompt injection, excessive agency, insecure output, training poisoning     |
| **Secrets**      | 21 provider patterns — OpenAI, AWS, GitHub, Stripe, Anthropic, GCP, Twilio, SendGrid           |
| **Dependencies** | CVE lookup via OSV.dev for npm and pip                                                         |
| **MCP configs**  | Dangerous tool permissions, wildcard grants, missing auth in Claude/Cursor/Cline configs       |
| **AI Agents**    | LangChain, CrewAI, AutoGen, OpenAI Agents — tool over-permissioning, missing human-in-the-loop |
| **Supply chain** | Typosquat detection, install script analysis, lockfile integrity, dependency confusion         |
| **CI/CD**        | GitHub Actions and GitLab CI — script injection, unpinned actions, secret leaks                |
| **Docker**       | Dockerfile hardening — root user, secrets in layers, privileged mode                           |
| **IaC**          | Terraform, CloudFormation, Kubernetes — public S3, open security groups, unencrypted storage   |

---

## Run anywhere

CipherNest is a monorepo. All scanner logic lives once in `@ciphernest/core`. Every client is a thin wrapper.

### CLI

```bash
npx ciphernest scan .
```

```
  ╔═══════════════════════════════╗
  ║   CipherNest Security Scanner  ║
  ╚═══════════════════════════════╝

── CODE ──────────────────────────────
[CRITICAL] CODE001  Dangerous eval()
  src/api.ts:42
  Fix: Replace eval() with JSON.parse() or safer alternatives

── SECRET ──────────────────────────────
[CRITICAL] SEC001  OpenAI API Key
  config.ts:7  sk-proj-ab***REDACTED***

── LLM ──────────────────────────────
[HIGH    ] LLM001  Direct Prompt Injection Risk
  src/chat.ts:18

12 finding(s)  6 critical  6 high  0 medium

Security Grade: C  (score: 65/100)
✅ PASS — no findings at or above high severity
```

Options:

```bash
ciphernest scan .                          # table output (default)
ciphernest scan . --format json            # JSON output
ciphernest scan . --format sarif           # SARIF for GitHub Code Scanning
ciphernest scan . --severity high          # only high and above
ciphernest scan . --fail-on critical       # exit 1 only on critical
ciphernest scan . --no-llm --no-agent      # skip specific scanners
ciphernest scan . --no-docker --no-iac     # skip infrastructure scanners
```

### GitHub Action

```yaml
- name: CipherNest Security Scan
  uses: ciphernest/scan-action@v1

- name: Upload SARIF to Code Scanning
  uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: ciphernest-results.sarif
```

On every pull request, CipherNest posts:

- Inline annotations in the diff (red for critical/high, yellow for medium)
- A PR comment with the security grade and scanner breakdown
- A SARIF file for GitHub Code Scanning integration

```
## 🟠 CipherNest Security Scan

Security Grade: B  (82/100)

| Severity | Count |
|----------|-------|
| 🔴 Critical | 0 |
| 🟠 High | 2 |
| 🟡 Medium | 5 |

### Top Findings

| Rule     | Severity | Name                      | Location        |
|----------|----------|---------------------------|-----------------|
| `LLM001` | 🟠 high  | Direct Prompt Injection   | `chat.ts:18`    |
| `CICD002`| 🟠 high  | Unpinned GitHub Action    | `ci.yml:14`     |
```

Action inputs:

```yaml
- uses: ciphernest/scan-action@v1
  with:
    path: "."              # directory to scan (default: .)
    severity: "low"        # minimum severity to report (default: low)
    fail-on: "high"        # exit 1 if any finding at this level (default: high)
    post-pr-comment: "true"
    sarif-output: "ciphernest-results.sarif"
    github-token: ${{ secrets.GITHUB_TOKEN }}
```

Action outputs: `findings-count`, `critical-count`, `high-count`, `security-grade`, `sarif-file`

### MCP Server

Add CipherNest to any AI agent — Claude Desktop, Cursor, Windsurf, LangGraph, Mastra, OpenAI Agents:

```json
{
  "mcpServers": {
    "ciphernest": {
      "command": "npx",
      "args": ["-y", "@ciphernest/mcp-server"]
    }
  }
}
```

Available tools:

| Tool                 | Description                                                             |
| -------------------- | ----------------------------------------------------------------------- |
| `scan_repository`    | Full scan of a local directory — all scanners, returns grade + findings |
| `scan_code`          | Scan a code snippet for OWASP Top 10 vulnerabilities                    |
| `scan_llm_code`      | Scan LLM/agent code for OWASP LLM Top 10 risks                          |
| `scan_secrets`       | Detect hardcoded secrets and credentials                                |
| `scan_mcp_config`    | Audit an MCP server config for dangerous permissions                    |
| `scan_agent_code`    | Audit agent tool registrations for excessive permissions                |
| `scan_cicd`          | Scan CI/CD pipeline files for supply chain risks                        |
| `scan_docker`        | Scan Dockerfiles for root user, secrets in layers, unpinned tags        |
| `scan_iac`           | Scan Terraform/CloudFormation/K8s for public S3, open SGs, IAM `*`     |
| `get_security_score` | Compute score and grade from a finding list                             |

### VS Code Extension

Install from the marketplace or:

```bash
code --install-extension ciphernest-0.7.0.vsix
```

Findings appear inline as diagnostics. Open the **CipherNest** sidebar for the tree view, score, and attack graph.

---

## Architecture

<img width="1535" height="897" alt="Architecture" src="https://github.com/user-attachments/assets/6773540a-3fd0-4f63-85a7-cdae664d4400" />

Every product surface uses the same scanner, rules, scoring, policy, and attack-graph engine.

```
packages/
├── core/             @ciphernest/core — single source of truth for all scan logic
│   └── src/
│       ├── engine.ts        SecurityEngine orchestrator (9 scanners)
│       ├── types.ts         Finding, SecurityScore, Severity, ScanInput
│       ├── rules/           codeRules, llmRules, secretRules, agentRules
│       ├── scanners/        All scanners (vscode-agnostic)
│       ├── scoring/         scoreEngine — A–F grade
│       ├── policy/          policyEngine — .ciphernest.json
│       ├── attackGraph/     graphBuilder — Mermaid diagrams
│       └── npmShield/       supply chain scanner
│
├── cli/              ciphernest — npm binary + fixture benchmark runner
├── github-action/    ciphernest/scan-action — SARIF + PR comments
├── mcp-server/       @ciphernest/mcp-server — 10 MCP tools for AI agents
└── mcp-gateway/      @ciphernest/mcp-gateway — runtime proxy, block rules, audit log

src/                  VS Code extension — thin adapters over @ciphernest/core
```

---

## Policy as code

Configure with `.ciphernest.json` at the project root:

```jsonc
{
  "version": 1,
  "severityThreshold": "low",
  "enabledScanners": ["code", "llm", "secret", "dependency", "mcp", "agent", "docker", "iac", "cicd"],
  "disabledRules": ["CODE014"],
  "severityOverrides": { "SEC010": "high" },
  "excludePatterns": ["**/node_modules/**", "**/*.test.ts"],
  "ciFailThreshold": "high",
  "ciMaxFindings": 0,
  "complianceFrameworks": ["gdpr", "hipaa", "pci", "dpdp"],
  "approvedLLMProviders": ["openai", "anthropic"],
  "autoScanOnOpen": true,
}
```

Generate a scaffold: `CipherNest: Create .ciphernest.json Policy`

---

## Scoring

| Grade | Score  | Meaning                |
| ----- | ------ | ---------------------- |
| **A** | 90–100 | Production-ready       |
| **B** | 75–89  | Minor issues           |
| **C** | 60–74  | Review before shipping |
| **D** | 40–59  | Significant risk       |
| **F** | 0–39   | Block deployment       |

**Per-finding deductions:** Critical = 25 pts · High = 10 pts · Medium = 4 pts · Low = 1 pt

**Per-scanner caps** (max total deduction per bucket): Code/Secrets = 30 · LLM/Docker/IaC = 25 · Dependency/Agent/CI-CD = 20 · MCP = 15

The overall score is the **average across active scanners only** — disabled scanners are excluded from the average, so running fewer scanners does not inflate your grade.


---

## Benchmark results

Run the AI application security benchmark against your project:

```bash
ciphernest benchmark .
```

Run the detection benchmark against known-bad fixture code:

```bash
ciphernest benchmark --fixtures owasp-llm10      # OWASP LLM Top 10 (10 cases)
ciphernest benchmark --fixtures owasp-top10       # OWASP Web Top 10 (7 cases)
ciphernest benchmark --fixtures infrastructure    # Docker / IaC / CI-CD (10 cases)
```

Each fixture run writes the vulnerable code to a temp file, runs the actual scanner, and checks whether the expected rule ID fires — no hardcoded scores.

Example project benchmark output:

```
Prompt Injection Score      91  ████████████████████░  A
Agent Security Score        88  ████████████████████░  B+
MCP Security Score          93  █████████████████████  A
Supply Chain Score          84  ████████████████████░  B
Infrastructure Score        81  ███████████████████░░  B-

Overall Security Score      87  Grade: B+
```

---

## Rule reference

<details>
<summary><strong>Code rules (CODE001–020)</strong></summary>

| ID          | Name                                               | Severity    |
| ----------- | -------------------------------------------------- | ----------- |
| CODE001     | `eval()` — arbitrary code execution                | Critical    |
| CODE002     | `exec()` with dynamic input — OS command injection | Critical    |
| CODE003     | String concatenation in SQL — SQL injection        | Critical    |
| CODE004     | `innerHTML` with dynamic content — XSS             | High        |
| CODE005     | Unsafe object merge — prototype pollution          | High        |
| CODE006     | Unvalidated file path — path traversal             | High        |
| CODE007     | `Math.random()` — not cryptographically secure     | Medium      |
| CODE008     | Hardcoded password                                 | Critical    |
| CODE009     | TLS verification disabled                          | High        |
| CODE010     | MD5/SHA1 — broken hash algorithm                   | Medium      |
| CODE011     | Unsafe XML parsing — XXE                           | High        |
| CODE015     | Wildcard CORS                                      | High        |
| CODE016–020 | SSRF, CSRF, race condition, ReDoS, open redirect   | Medium–High |

</details>

<details>
<summary><strong>LLM / AI rules (LLM001–018)</strong></summary>

| ID     | Name                                              | OWASP LLM | Severity |
| ------ | ------------------------------------------------- | --------- | -------- |
| LLM001 | Prompt injection — unsanitized user input         | LLM01     | Critical |
| LLM002 | Insecure output handling — raw response to client | LLM02     | High     |
| LLM004 | Raw LLM output rendered as HTML                   | LLM02     | High     |
| LLM005 | PII/key in prompt                                 | LLM06     | High     |
| LLM007 | Agent with unrestricted file write                | LLM08     | Critical |
| LLM008 | Agent with database write/delete                  | LLM08     | Critical |
| LLM011 | LangChain agent without tool restrictions         | LLM08     | High     |
| LLM014 | AutoGen agent missing human approval              | LLM08     | High     |
| LLM018 | Shadow AI — unapproved LLM provider               | LLM09     | Medium   |

</details>

<details>
<summary><strong>Secret patterns (SEC001–021)</strong></summary>

OpenAI · Anthropic · AWS · Google · GitHub · Stripe · Slack · Twilio · SendGrid · Mailgun · Cloudflare · HuggingFace · Pinecone · Weaviate · MongoDB Atlas · Generic high-entropy secret

</details>

<details>
<summary><strong>CI/CD rules (CICD001–010+)</strong></summary>

| ID      | Name                                        | Severity |
| ------- | ------------------------------------------- | -------- |
| CICD001 | `pull_request_target` with code checkout    | Critical |
| CICD002 | Unpinned action (`@main`, `@latest`)        | Critical |
| CICD003 | Script injection via `github.event` context | High     |
| CICD004 | Secret exposed in `run:` command            | High     |
| CICD005 | `permissions: write-all`                    | Critical |

</details>

<details>
<summary><strong>Docker and IaC rules</strong></summary>

**Docker:** `FROM :latest` · Running as root · Secret in ENV/ARG · `--privileged` flag · Missing HEALTHCHECK

**IaC:** S3 public ACL · Security group 0.0.0.0/0 · RDS publicly accessible · No encryption at rest · IAM `*` wildcard · K8s privileged pod

</details>

---

## Platform roadmap and extensions

### GitHub App

Not an Action — an App. Inline PR comments per finding, like CodeQL and SonarQube:

```
LLM001 — Prompt Injection Risk

User input passed to LLM without sanitization on line 42.
Attacker can override system instructions and gain tool access.

Suggested fix:
  sanitizeInput(userMessage) before passing to chain.invoke()
```

### Runtime MCP Gateway

`@ciphernest/mcp-gateway` is a security-aware proxy that sits between an AI agent and any MCP server. It intercepts every tool call at runtime, applies configurable block rules, and logs all activity — without changing a line of agent code.

```
Agent
  ↓
CipherNest Gateway  ← intercepts every tool call
  ↓  allow / block / flag
MCP Server(s)
```

Add it to your Claude Desktop (or any MCP host) config:

```json
{
  "mcpServers": {
    "ciphernest-gateway": {
      "command": "npx",
      "args": ["-y", "@ciphernest/mcp-gateway"],
      "env": {
        "CIPHERNEST_GATEWAY_SERVERS": "{\"filesystem\":{\"command\":\"npx\",\"args\":[\"-y\",\"@modelcontextprotocol/server-filesystem\",\"/workspace\"]}}"
      }
    }
  }
}
```

Default block rules (all configurable via `CIPHERNEST_GATEWAY_POLICY` env var):

| Rule                     | Blocks                                                          |
| ------------------------ | --------------------------------------------------------------- |
| `blockDestructive`       | `delete_file`, `bash`, `rm`, `shell`, `exec`, `drop_table`, … |
| `blockDataExfiltration`  | URLs matching webhook.site, ngrok.io, pipedream.net, …         |
| `blockSqlInjection`      | SQL injection patterns in tool arguments                        |
| `blockCommandInjection`  | OS command injection in tool arguments                          |
| Prompt injection (warn)  | Flags but does **not** block — returns `riskLevel: "high"`      |
| Path traversal           | `/../` patterns in path arguments                               |

Gateway built-in tools exposed to the agent:

| Tool                  | Description                                  |
| --------------------- | -------------------------------------------- |
| `gateway_inspect`     | Test any tool call against the active policy |
| `gateway_audit_log`   | Read the last N audit log entries            |
| `gateway_list_rules`  | List all active block rules and their status |

Audit log is written to `~/.ciphernest/gateway-audit.jsonl`.

### Security Reasoning Engine

Move from rules → findings to rules → findings → explanation:

```
Current:  LLM001 detected at chat.ts:42

Future:   Prompt injection at chat.ts:42.
          Attacker controlling user_input can override the system prompt,
          gain access to the file_write tool registered at agents.ts:17,
          and exfiltrate /etc/passwd via the HTTP callback in tools.ts:91.
          Business impact: complete agent compromise, data breach.
```

### Marketplace rules (`packages/rules`)

Rules extracted into a standalone package so the community can contribute and enterprises can buy packs:

```bash
npm install @ciphernest/rules-enterprise
npm install @ciphernest/rules-hipaa
npm install @ciphernest/rules-pci
```

---

## Security

- Threat Model → [docs/threat-model.md](docs/threat-model.md)
- Security Policy → [SECURITY.md](SECURITY.md)
- Responsible Disclosure → [SECURITY.md](SECURITY.md)

---

## Triage and suppression

Suppress a false positive with a tracked reason:

```
CipherNest: Suppress Finding
```

All suppressions are stored in `.ciphernest-suppressions.json` and visible in the triage report. The audit log captures every suppression with timestamp and author.

---

## License

MIT © [Vairamuthu](https://github.com/vairamuthu)
