---
title: "semgrep/skills"
description: "A collection of skills for AI coding agents from Semgrep"
source: https://github.com/semgrep/skills
ref: main
license: null
licenseName: "Other"
canonical: https://skillsdocs.com/semgrep/skills
base: https://github.com/semgrep/skills/blob/main/
chapters: 3
inlined: 3
withheld: 0
words: 1537
updated: 2026-07-28T05:28:16Z
generator: "Skills Docs"
---

> **semgrep/skills** — every Agent Skill in this repository, inlined verbatim.
>
> Canonical HTML: https://skillsdocs.com/semgrep/skills
> Per-chapter Markdown: https://skillsdocs.com/semgrep/skills/<skill>.md
> Machine manifest: https://skillsdocs.com/semgrep/skills/.well-known/agent-skills/index.json
> JSON: https://skillsdocs.com/api/v1/books/semgrep/skills
> Install: `npx skills add semgrep/skills`
> Upstream: https://github.com/semgrep/skills @ `main`
> Licence: Other
>
> Content is mirrored from GitHub and © its authors, served unmodified. Takedown: https://github.com/kyleledbetter/skillsdocs/issues/new?labels=takedown&title=Takedown+request

# semgrep/skills

A collection of skills for AI coding agents from Semgrep

- **Chapters:** 3
- **Inlined:** 3 (licence detected)
- **Words:** 1,537
- **Reading time:** 7 min
- **Stars:** 260

## Table of contents

1. [code-security](https://skillsdocs.com/semgrep/skills/code-security.md) — Security guidelines for writing secure code. Use when writing code, reviewing code for vulnerabilities, or asking about secure coding practices like 'check for…
2. [llm-security](https://skillsdocs.com/semgrep/skills/llm-security.md) — Security guidelines for LLM applications based on OWASP Top 10 for LLM 2025. Use when building LLM apps, reviewing AI security, implementing RAG systems, or as…
3. [semgrep](https://skillsdocs.com/semgrep/skills/semgrep.md) — Run Semgrep static analysis scans and create custom detection rules. Use when asked to scan code with Semgrep, find security vulnerabilities, write custom YAML…


## Front matter

_The repository README, verbatim except that relative links are resolved against https://github.com/semgrep/skills/blob/main/._

# Agent Skills [Beta]

A collection of skills for AI coding agents. Skills are packaged instructions and scripts that extend agent capabilities. This should be considered beta-level software; it's primarily generated by transforming open-source Semgrep rules into skill format.

Skills follow the [Agent Skills](https://agentskills.io/) format.

## Installation

```bash
npx skills add semgrep/skills
```

## Available Skills

### code-security

Comprehensive code security guidelines from Semgrep Engineering covering OWASP Top 10, infrastructure security, and secure coding best practices across 15+ languages.

**Use when:**
- Writing new code
- Reviewing code for security vulnerabilities
- Asking about secure coding practices
- Configuring cloud infrastructure (Terraform, Kubernetes, Docker)

**Categories covered:**

| Impact | Category | Description |
|--------|----------|-------------|
| **Critical** | SQL Injection | Parameterized queries, ORM safety |
| **Critical** | Command Injection | Shell command safety, input validation |
| **Critical** | Cross-Site Scripting (XSS) | Output encoding, DOM safety |
| **Critical** | XML External Entity (XXE) | XML parser configuration |
| **Critical** | Path Traversal | File path validation |
| **Critical** | Insecure Deserialization | Safe deserialization patterns |
| **Critical** | Code Injection | Eval safety, template injection |
| **Critical** | Hardcoded Secrets | Environment variables, secret management |
| **Critical** | Memory Safety | Buffer overflows, use-after-free (C/C++) |
| **High** | Insecure Cryptography | Strong hashing (SHA-256+), encryption (AES) |
| **High** | Insecure Transport | HTTPS, certificate validation, TLS |
| **High** | Server-Side Request Forgery | URL validation, allowlists |
| **High** | JWT Authentication | Signature verification, algorithm safety |
| **High** | Cross-Site Request Forgery | CSRF tokens, SameSite cookies |
| **High** | Prototype Pollution | Object key validation (JavaScript) |
| **High** | Unsafe Functions | Dangerous function alternatives |
| **High** | Terraform AWS | S3, IAM, EC2, RDS security |
| **High** | Terraform Azure | Storage, App Service, Key Vault |
| **High** | Terraform GCP | GCS, GCE, GKE, IAM |
| **High** | Kubernetes | Pod security, RBAC, secrets |
| **High** | Docker | Non-root containers, image pinning |
| **High** | GitHub Actions | Script injection, action pinning |
| **Medium** | Regex DoS | Catastrophic backtracking prevention |
| **Medium** | Race Conditions | TOCTOU, secure temp files |
| **Medium** | Code Correctness | Common bugs, type errors |
| **Low** | Best Practices | Code quality patterns |
| **Low** | Performance | Efficiency anti-patterns |
| **Low** | Maintainability | Code organization |

**Languages:** Python, JavaScript/TypeScript, Java, Go, Ruby, PHP, C/C++, C#, Scala, Kotlin, Rust, HCL (Terraform), YAML (Kubernetes)

---

### llm-security

Security guidelines for LLM applications based on the OWASP Top 10 for Large Language Model Applications 2025.

**Use when:**
- Building LLM-powered applications
- Implementing RAG systems
- Securing AI/ML pipelines
- Reviewing code that interacts with language models

**Categories covered:**

| Impact | Category | Description |
|--------|----------|-------------|
| **Critical** | Prompt Injection | Input validation, content segregation, output filtering |
| **Critical** | Sensitive Information Disclosure | PII detection, permission-aware RAG |
| **Critical** | Supply Chain | Model verification, safetensors, ML-BOM |
| **Critical** | Data and Model Poisoning | Training data validation, anomaly detection |
| **Critical** | Improper Output Handling | Context-aware encoding, parameterized queries |
| **High** | Excessive Agency | Least privilege, human-in-the-loop |
| **High** | System Prompt Leakage | External guardrails, no secrets in prompts |
| **High** | Vector and Embedding Weaknesses | Permission-aware retrieval, tenant isolation |
| **High** | Misinformation | RAG, fact verification, confidence scoring |
| **High** | Unbounded Consumption | Rate limiting, budget controls |

**Frameworks:** OWASP LLM Top 10, MITRE ATLAS, NIST AI RMF

---

### semgrep

Run Semgrep static analysis scans and create custom detection rules for security vulnerabilities and bug patterns.

**Use when:**
- Running security scans with Semgrep
- Creating custom Semgrep rules
- Detecting specific vulnerability patterns
- Setting up Semgrep in CI/CD pipelines

**Capabilities:**

| Feature | Description |
|---------|-------------|
| **Quick Scans** | Run `semgrep --config auto` or use curated rulesets |
| **Rulesets** | security-audit, owasp-top-ten, cwe-top-25, trailofbits |
| **Custom Rules** | Pattern matching and taint mode for data flow analysis |
| **Test-Driven** | Write test cases first with `ruleid:` and `ok:` annotations |
| **CI/CD** | GitHub Actions integration with diff-aware scanning |

**Rule Creation Workflow:**
1. Analyze the vulnerability pattern
2. Create test cases first (test-driven development)
3. Analyze AST structure with `semgrep --dump-ast`
4. Write the rule (taint mode for injection, pattern matching for syntax)
5. Iterate until 100% tests pass
6. Optimize patterns

**When to use taint mode:** SQL injection, command injection, XSS, path traversal, SSRF - any vulnerability where untrusted data flows to a dangerous sink.

---

## Usage

Skills are automatically available once installed. The agent will use them when relevant tasks are detected.

**Examples:**
```
Review this React component for security issues
```
```
Help me implement input validation for my LLM chat endpoint
```
```
Create a Semgrep rule to detect hardcoded API keys in Python
```

## Development

### Building Skills

```bash
make install     # Install dependencies
make validate    # Validate all skills
make build       # Build AGENTS.md for all skills
make zip         # Create distribution packages
make             # All of the above
```

### Single Skill Operations

```bash
make validate-skill SKILL=code-security
make build-skill SKILL=llm-security
```

## Skill Structure

Each skill contains:
- `SKILL.md` - Instructions for the agent
- `rules/` - Individual rule files (for skills with rules)
- `scripts/` - Helper scripts for automation (optional)
- `references/` - Supporting documentation (optional)

## Acknowledgments

Originally created by [@DrewDennison](https://x.com/drewdennison) at [Semgrep](https://semgrep.dev). This work was heavily inspired by Vercel's [React Best Practices](https://vercel.com/blog/introducing-react-best-practices).

---

<!-- chapter:begin slug=code-security position=1 -->

## 1. code-security

- **Source:** https://github.com/semgrep/skills/blob/main/skills/code-security/SKILL.md
- **Raw:** https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/SKILL.md
- **Markdown:** https://skillsdocs.com/semgrep/skills/code-security.md
- **Licence:** Other — https://github.com/semgrep/skills

Bundled files (33), referenced from this skill's directory:
  - `AGENTS.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/AGENTS.md
  - `metadata.json` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/metadata.json
  - `README.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/README.md
  - `rules/_sections.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/_sections.md
  - `rules/_template.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/_template.md
  - `rules/authentication-jwt.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/authentication-jwt.md
  - `rules/best-practice.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/best-practice.md
  - `rules/code-injection.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/code-injection.md
  - `rules/command-injection.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/command-injection.md
  - `rules/correctness.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/correctness.md
  - `rules/csrf.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/csrf.md
  - `rules/docker.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/docker.md
  - `rules/github-actions.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/github-actions.md
  - `rules/insecure-crypto.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/insecure-crypto.md
  - `rules/insecure-deserialization.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/insecure-deserialization.md
  - `rules/insecure-transport.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/insecure-transport.md
  - `rules/kubernetes.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/kubernetes.md
  - `rules/maintainability.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/maintainability.md
  - `rules/memory-safety.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/memory-safety.md
  - `rules/path-traversal.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/path-traversal.md
  - `rules/performance.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/performance.md
  - `rules/prototype-pollution.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/prototype-pollution.md
  - `rules/race-condition.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/race-condition.md
  - `rules/regex-dos.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/code-security/rules/regex-dos.md
  - …and 9 more, listed in https://skillsdocs.com/api/v1/books/semgrep/skills/skills/code-security

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: code-security
description: "Security guidelines for writing secure code. Use when writing code, reviewing code for vulnerabilities, or asking about secure coding practices like 'check for SQL injection' or 'review security'. IMPORTANT: Always consult this skill when writing or reviewing any code that handles user input, authentication, file operations, database queries, network requests, cryptography, or infrastructure configuration (Terraform, Kubernetes, Docker, GitHub Actions) — even if the user doesn't explicitly mention security. Also use when users ask to 'review my code', 'check this for bugs', or 'is this safe'."
---

# Code Security Guidelines

Comprehensive security rules for writing secure code across 15+ languages. Covers OWASP Top 10, infrastructure security, and coding best practices with 28 rule categories.

## How to Use This Skill

**Proactive mode** — When writing or reviewing code, automatically check for relevant vulnerabilities based on the language and patterns present. You don't need to wait for the user to ask about security.

**Reactive mode** — When the user asks about security, use the categories below to find the relevant rule file, then read it for detailed vulnerable/secure code examples.

### Workflow
1. Identify the language and what the code does (handles input? queries a DB? reads files?)
2. Check the relevant rules below — focus on Critical and High impact first
3. Read the specific rule file from `rules/` for detailed code examples in that language
4. Apply the secure patterns, or flag the vulnerable patterns if reviewing

## Language-Specific Priority Rules

When writing code in these languages, check these rules first:

| Language | Priority Rules to Check |
|----------|------------------------|
| **Python** | SQL injection, command injection, path traversal, code injection, SSRF, insecure crypto |
| **JavaScript/TypeScript** | XSS, prototype pollution, code injection, insecure transport, CSRF |
| **Java** | SQL injection, XXE, insecure deserialization, insecure crypto, SSRF |
| **Go** | SQL injection, command injection, path traversal, insecure transport |
| **C/C++** | Memory safety, unsafe functions, command injection, path traversal |
| **Ruby** | SQL injection, command injection, code injection, insecure deserialization |
| **PHP** | SQL injection, XSS, command injection, code injection, path traversal |
| **HCL/YAML** | Terraform (AWS/Azure/GCP), Kubernetes, Docker, GitHub Actions |

## Categories

### Critical Impact
- **SQL Injection** (`rules/sql-injection.md`) - Use parameterized queries, never concatenate user input
- **Command Injection** (`rules/command-injection.md`) - Avoid shell commands with user input, use safe APIs
- **XSS** (`rules/xss.md`) - Escape output, use framework protections
- **XXE** (`rules/xxe.md`) - Disable external entities in XML parsers
- **Path Traversal** (`rules/path-traversal.md`) - Validate and sanitize file paths
- **Insecure Deserialization** (`rules/insecure-deserialization.md`) - Never deserialize untrusted data
- **Code Injection** (`rules/code-injection.md`) - Never eval() user input
- **Hardcoded Secrets** (`rules/secrets.md`) - Use environment variables or secret managers
- **Memory Safety** (`rules/memory-safety.md`) - Prevent buffer overflows, use-after-free (C/C++)

### High Impact
- **Insecure Crypto** (`rules/insecure-crypto.md`) - Use SHA-256+, AES-256, avoid MD5/SHA1/DES
- **Insecure Transport** (`rules/insecure-transport.md`) - Use HTTPS, verify certificates
- **SSRF** (`rules/ssrf.md`) - Validate URLs, use allowlists
- **JWT Issues** (`rules/authentication-jwt.md`) - Always verify signatures
- **CSRF** (`rules/csrf.md`) - Use CSRF tokens on state-changing requests
- **Prototype Pollution** (`rules/prototype-pollution.md`) - Validate object keys in JavaScript

### Infrastructure
- **Terraform AWS/Azure/GCP** (`rules/terraform-aws.md`, `rules/terraform-azure.md`, `rules/terraform-gcp.md`) - Encryption, least privilege, no public access
- **Kubernetes** (`rules/kubernetes.md`) - No privileged containers, run as non-root
- **Docker** (`rules/docker.md`) - Don't run as root, pin image versions
- **GitHub Actions** (`rules/github-actions.md`) - Avoid script injection, pin action versions

### Medium/Low Impact
- **Regex DoS** (`rules/regex-dos.md`) - Avoid catastrophic backtracking
- **Race Conditions** (`rules/race-condition.md`) - Use proper synchronization
- **Correctness** (`rules/correctness.md`) - Avoid common logic bugs
- **Best Practices** (`rules/best-practice.md`) - General secure coding patterns

See `rules/_sections.md` for the full index with CWE/OWASP references.

## Quick Reference

| Vulnerability | Key Prevention |
|--------------|----------------|
| SQL Injection | Parameterized queries |
| XSS | Output encoding |
| Command Injection | Avoid shell, use APIs |
| Path Traversal | Validate paths |
| SSRF | URL allowlists |
| Secrets | Environment variables |
| Crypto | SHA-256, AES-256 |

<!-- chapter:end slug=code-security -->

---

<!-- chapter:begin slug=llm-security position=2 -->

## 2. llm-security

- **Source:** https://github.com/semgrep/skills/blob/main/skills/llm-security/SKILL.md
- **Raw:** https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/SKILL.md
- **Markdown:** https://skillsdocs.com/semgrep/skills/llm-security.md
- **Licence:** Other — https://github.com/semgrep/skills

Bundled files (13), referenced from this skill's directory:
  - `AGENTS.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/AGENTS.md
  - `README.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/README.md
  - `rules/_sections.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/_sections.md
  - `rules/data-poisoning.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/data-poisoning.md
  - `rules/excessive-agency.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/excessive-agency.md
  - `rules/misinformation.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/misinformation.md
  - `rules/output-handling.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/output-handling.md
  - `rules/prompt-injection.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/prompt-injection.md
  - `rules/sensitive-disclosure.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/sensitive-disclosure.md
  - `rules/supply-chain.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/supply-chain.md
  - `rules/system-prompt-leakage.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/system-prompt-leakage.md
  - `rules/unbounded-consumption.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/unbounded-consumption.md
  - `rules/vector-embedding.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/llm-security/rules/vector-embedding.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: llm-security
description: "Security guidelines for LLM applications based on OWASP Top 10 for LLM 2025. Use when building LLM apps, reviewing AI security, implementing RAG systems, or asking about LLM vulnerabilities like 'prompt injection' or 'check LLM security'. IMPORTANT: Always consult this skill when building chatbots, AI agents, RAG pipelines, tool-using LLMs, agentic systems, or any application that calls an LLM API (OpenAI, Anthropic, Gemini, etc.) — even if the user doesn't explicitly mention security. Also use when users import 'openai', 'anthropic', 'langchain', 'llamaindex', or similar LLM libraries."
---

# LLM Security Guidelines (OWASP Top 10 for LLM 2025)

Security rules for building secure LLM applications, based on the OWASP Top 10 for LLM Applications 2025.

## How to Use This Skill

**Proactive mode** — When building or reviewing LLM applications, automatically check for relevant security risks based on the application pattern. You don't need to wait for the user to ask about LLM security.

**Reactive mode** — When the user asks about LLM security, use the mapping below to find relevant rule files with detailed vulnerable/secure code examples.

### Workflow
1. Identify what the user is building (see "What Are You Building?" below)
2. Check the priority rules for that pattern
3. Read the specific rule files from `rules/` for code examples
4. Apply the secure patterns or flag vulnerable ones

## What Are You Building?

Use this to quickly identify which rules matter most for the user's task:

| Building... | Priority Rules |
|-------------|---------------|
| **Chatbot / conversational AI** | Prompt Injection (LLM01), System Prompt Leakage (LLM07), Output Handling (LLM05), Unbounded Consumption (LLM10) |
| **RAG system** | Vector/Embedding Weaknesses (LLM08), Prompt Injection (LLM01), Sensitive Disclosure (LLM02), Misinformation (LLM09) |
| **AI agent with tools** | Excessive Agency (LLM06), Prompt Injection (LLM01), Output Handling (LLM05), Sensitive Disclosure (LLM02) |
| **Fine-tuning / training** | Data Poisoning (LLM04), Supply Chain (LLM03), Sensitive Disclosure (LLM02) |
| **LLM-powered API** | Unbounded Consumption (LLM10), Prompt Injection (LLM01), Output Handling (LLM05), Sensitive Disclosure (LLM02) |
| **Content generation** | Misinformation (LLM09), Output Handling (LLM05), Prompt Injection (LLM01) |

## Categories

### Critical Impact
- **LLM01: Prompt Injection** (`rules/prompt-injection.md`) - Prevent direct and indirect prompt manipulation
- **LLM02: Sensitive Information Disclosure** (`rules/sensitive-disclosure.md`) - Protect PII, credentials, and proprietary data
- **LLM03: Supply Chain** (`rules/supply-chain.md`) - Secure model sources, training data, and dependencies
- **LLM04: Data and Model Poisoning** (`rules/data-poisoning.md`) - Prevent training data manipulation and backdoors
- **LLM05: Improper Output Handling** (`rules/output-handling.md`) - Sanitize LLM outputs before downstream use

### High Impact
- **LLM06: Excessive Agency** (`rules/excessive-agency.md`) - Limit LLM permissions, functionality, and autonomy
- **LLM07: System Prompt Leakage** (`rules/system-prompt-leakage.md`) - Protect system prompts from disclosure
- **LLM08: Vector and Embedding Weaknesses** (`rules/vector-embedding.md`) - Secure RAG systems and embeddings
- **LLM09: Misinformation** (`rules/misinformation.md`) - Mitigate hallucinations and false outputs
- **LLM10: Unbounded Consumption** (`rules/unbounded-consumption.md`) - Prevent DoS, cost attacks, and model theft

See `rules/_sections.md` for the full index with OWASP/MITRE references.

## Quick Reference

| Vulnerability | Key Prevention |
|--------------|----------------|
| Prompt Injection | Input validation, output filtering, privilege separation |
| Sensitive Disclosure | Data sanitization, access controls, encryption |
| Supply Chain | Verify models, SBOM, trusted sources only |
| Data Poisoning | Data validation, anomaly detection, sandboxing |
| Output Handling | Treat LLM as untrusted, encode outputs, parameterize queries |
| Excessive Agency | Least privilege, human-in-the-loop, minimize extensions |
| System Prompt Leakage | No secrets in prompts, external guardrails |
| Vector/Embedding | Access controls, data validation, monitoring |
| Misinformation | RAG, fine-tuning, human oversight, cross-verification |
| Unbounded Consumption | Rate limiting, input validation, resource monitoring |

## Key Principles

1. **Never trust LLM output** - Validate and sanitize all outputs before use
2. **Least privilege** - Grant minimum necessary permissions to LLM systems
3. **Defense in depth** - Layer multiple security controls
4. **Human oversight** - Require approval for high-impact actions
5. **Monitor and log** - Track all LLM interactions for anomaly detection

## References

- [OWASP Top 10 for LLM Applications 2025](https://genai.owasp.org/llm-top-10/)
- [MITRE ATLAS - Adversarial Threat Landscape for AI Systems](https://atlas.mitre.org/)
- [NIST AI Risk Management Framework](https://www.nist.gov/itl/ai-risk-management-framework)

<!-- chapter:end slug=llm-security -->

---

<!-- chapter:begin slug=semgrep position=3 -->

## 3. semgrep

- **Source:** https://github.com/semgrep/skills/blob/main/skills/semgrep/SKILL.md
- **Raw:** https://raw.githubusercontent.com/semgrep/skills/main/skills/semgrep/SKILL.md
- **Markdown:** https://skillsdocs.com/semgrep/skills/semgrep.md
- **Licence:** Other — https://github.com/semgrep/skills

Bundled files (3), referenced from this skill's directory:
  - `README.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/semgrep/README.md
  - `references/quick-reference.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/semgrep/references/quick-reference.md
  - `references/workflow.md` — https://raw.githubusercontent.com/semgrep/skills/main/skills/semgrep/references/workflow.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: semgrep
description: "Run Semgrep static analysis scans and create custom detection rules. Use when asked to scan code with Semgrep, find security vulnerabilities, write custom YAML rules, or detect specific bug patterns. IMPORTANT: Also use this skill when users ask to 'scan for bugs', 'check code quality', 'find vulnerabilities', 'static analysis', 'lint for security', 'audit this code', or want to enforce coding standards — even if they don't mention Semgrep by name. Semgrep is the right tool for pattern-based code scanning across 30+ languages."
---

# Semgrep Static Analysis

Fast, pattern-based static analysis for security scanning and custom rule creation.

## MCP Tools Available

If Semgrep MCP tools are available in your environment, prefer them for scanning:

- **`semgrep_scan`** — Scan code files for security vulnerabilities using built-in rulesets. Pass absolute file paths and an optional config (e.g., `p/security-audit`, `auto`).
- **`semgrep_scan_with_custom_rule`** — Scan code with a custom YAML rule you've written. Pass code content inline along with the rule.
- **`semgrep_findings`** — Fetch existing findings from the Semgrep AppSec Platform for a repository.
- **`semgrep_rule_schema`** — Get the full schema for writing Semgrep rules.
- **`get_supported_languages`** — List all languages Semgrep supports.

When MCP tools aren't available, fall back to the CLI commands below.

## When to Use Semgrep

**Ideal scenarios:**
- Quick security scans (minutes, not hours)
- Pattern-based bug and vulnerability detection
- Enforcing coding standards and best practices
- Finding known vulnerability patterns (OWASP, CWE)
- Creating custom detection rules for your codebase
- Data flow analysis with taint mode

## Installation (CLI)

```bash
# pip (recommended)
python3 -m pip install semgrep

# Homebrew
brew install semgrep

# Docker
docker run --rm -v "${PWD}:/src" semgrep/semgrep semgrep --config auto /src
```

---

# Part 1: Running Scans

## Quick Scan

```bash
semgrep --config auto .                    # Auto-detect rules
```

## Using Rulesets

```bash
semgrep --config p/<RULESET> .             # Single ruleset
semgrep --config p/security-audit --config p/trailofbits .  # Multiple
```

| Ruleset | Description |
|---------|-------------|
| `p/default` | General security and code quality |
| `p/security-audit` | Comprehensive security rules |
| `p/owasp-top-ten` | OWASP Top 10 vulnerabilities |
| `p/cwe-top-25` | CWE Top 25 vulnerabilities |
| `p/trailofbits` | Trail of Bits security rules |
| `p/python` | Python-specific |
| `p/javascript` | JavaScript-specific |
| `p/golang` | Go-specific |

## Output Formats

```bash
semgrep --config p/security-audit --sarif -o results.sarif .   # SARIF
semgrep --config p/security-audit --json -o results.json .     # JSON
```

## Scan Specific Paths

```bash
semgrep --config p/python app.py           # Single file
semgrep --config p/javascript src/         # Directory
semgrep --config auto --include='**/test/**' .  # Include tests
```

## Configuration

### .semgrepignore

```
tests/fixtures/
**/testdata/
generated/
vendor/
node_modules/
```

### Suppress False Positives

```python
password = get_from_vault()  # nosemgrep: hardcoded-password
dangerous_but_safe()  # nosemgrep
```

---

# Part 2: Creating Custom Rules

## When to Create Custom Rules

- Detecting project-specific vulnerability patterns
- Enforcing internal coding standards
- Building security checks for custom frameworks
- Creating taint-mode rules for data flow analysis

## Approach Selection

| Approach | Use When |
|----------|----------|
| **Taint mode** | Data flows from untrusted source to dangerous sink (injection vulnerabilities) |
| **Pattern matching** | Syntactic patterns without data flow requirements (deprecated APIs, hardcoded values) |

**Prioritize taint mode** for injection vulnerabilities. Pattern matching alone can't distinguish between `eval(user_input)` (vulnerable) and `eval("safe_literal")` (safe).

## Quick Start: Pattern Matching

```yaml
rules:
  - id: hardcoded-password
    languages: [python]
    message: "Hardcoded password detected: $PASSWORD"
    severity: ERROR
    pattern: password = "$PASSWORD"
```

## Quick Start: Taint Mode

```yaml
rules:
  - id: command-injection
    languages: [python]
    message: User input flows to command execution
    severity: ERROR
    mode: taint
    pattern-sources:
      - pattern: request.args.get(...)
      - pattern: request.form[...]
    pattern-sinks:
      - pattern: os.system(...)
      - pattern: subprocess.call($CMD, shell=True, ...)
    pattern-sanitizers:
      - pattern: shlex.quote(...)
```

## Pattern Syntax Quick Reference

| Syntax | Description | Example |
|--------|-------------|---------|
| `...` | Match anything | `func(...)` |
| `$VAR` | Capture metavariable | `$FUNC($INPUT)` |
| `<... ...>` | Deep expression match | `<... user_input ...>` |

| Operator | Description |
|----------|-------------|
| `pattern` | Match exact pattern |
| `patterns` | All must match (AND) |
| `pattern-either` | Any matches (OR) |
| `pattern-not` | Exclude matches |
| `pattern-inside` | Match only inside context |
| `pattern-not-inside` | Match only outside context |
| `metavariable-regex` | Regex on captured value |

## Testing Rules

**Test-first is mandatory.** Create test files with annotations:

```python
# test_rule.py
def test_vulnerable():
    user_input = request.args.get("id")
    # ruleid: my-rule-id
    cursor.execute("SELECT * FROM users WHERE id = " + user_input)

def test_safe():
    user_input = request.args.get("id")
    # ok: my-rule-id
    cursor.execute("SELECT * FROM users WHERE id = ?", (user_input,))
```

Run tests:
```bash
semgrep --test --config rule.yaml test-file
```

## Command Reference

| Task | Command |
|------|---------|
| Run tests | `semgrep --test --config rule.yaml test-file` |
| Validate YAML | `semgrep --validate --config rule.yaml` |
| Dump AST | `semgrep --dump-ast -l <lang> <file>` |
| Debug taint flow | `semgrep --dataflow-traces -f rule.yaml file` |

## Rule Creation Workflow

1. **Analyze the problem** - Understand the bug pattern, determine taint vs pattern approach
2. **Create test cases first** - Write `ruleid:` and `ok:` annotations before the rule
3. **Analyze AST** - Run `semgrep --dump-ast` to understand code structure
4. **Write the rule** - Start simple, iterate
5. **Test until 100% pass** - No "missed lines" or "incorrect lines"
6. **Optimize patterns** - Remove redundancies only after tests pass

**Output structure:**
```
<rule-id>/
├── <rule-id>.yaml     # Semgrep rule
└── <rule-id>.<ext>    # Test file
```

## Detailed References

**Official Semgrep Documentation:**
- [Rule Syntax](https://semgrep.dev/docs/writing-rules/rule-syntax) - Complete YAML structure, operators, and options
- [Rule Schema](https://github.com/semgrep/semgrep-interfaces/blob/main/rule_schema_v1.yaml) - Full JSON schema specification

**Local References:**
- [Workflow Guide](references/workflow.md) - Complete step-by-step rule creation process
- [Quick Reference](references/quick-reference.md) - Pattern operators and taint components

## Anti-Patterns to Avoid

**Too broad:**
```yaml
# BAD: Matches any function call
pattern: $FUNC(...)

# GOOD: Specific dangerous function
pattern: eval(...)
```

**Missing safe cases:**
```python
# BAD: Only tests vulnerable case
# ruleid: my-rule
dangerous(user_input)

# GOOD: Include safe cases
# ruleid: my-rule
dangerous(user_input)

# ok: my-rule
dangerous(sanitize(user_input))
```

## Rationalizations to Reject

| Shortcut | Why It's Wrong |
|----------|----------------|
| "Semgrep found nothing, code is clean" | Semgrep is pattern-based; can't track complex cross-function data flow |
| "The pattern looks complete" | Untested rules have hidden false positives/negatives |
| "It matches the vulnerable case" | Matching vulnerabilities is half the job; verify safe cases don't match |
| "Taint mode is overkill" | For injection vulnerabilities, taint mode gives better precision |
| "One test case is enough" | Include edge cases: different coding styles, sanitized inputs, safe alternatives |

---

# CI/CD Integration

## GitHub Actions

```yaml
name: Semgrep

on:
  push:
    branches: [main]
  pull_request:
  schedule:
    - cron: '0 0 1 * *'

jobs:
  semgrep:
    runs-on: ubuntu-latest
    container:
      image: returntocorp/semgrep

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Run Semgrep
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            semgrep ci --baseline-commit ${{ github.event.pull_request.base.sha }}
          else
            semgrep ci
          fi
        env:
          SEMGREP_RULES: >-
            p/security-audit
            p/owasp-top-ten
            p/trailofbits
```

---

# Resources

**Rule Writing:**
- Rule Syntax: https://semgrep.dev/docs/writing-rules/rule-syntax
- Pattern Syntax: https://semgrep.dev/docs/writing-rules/pattern-syntax
- Rule Schema: https://github.com/semgrep/semgrep-interfaces/blob/main/rule_schema_v1.yaml

**General:**
- Registry: https://semgrep.dev/explore
- Playground: https://semgrep.dev/playground
- Docs: https://semgrep.dev/docs/
- Trail of Bits Rules: https://github.com/trailofbits/semgrep-rules

<!-- chapter:end slug=semgrep -->
