implementing-semgrep-for-custom-sast-rules

Write custom Semgrep SAST rules in YAML to detect application-specific vulnerabilities, enforce coding standards, and integrate into CI/CD pipelines.

4,032 stars

Best use case

implementing-semgrep-for-custom-sast-rules is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Write custom Semgrep SAST rules in YAML to detect application-specific vulnerabilities, enforce coding standards, and integrate into CI/CD pipelines.

Teams using implementing-semgrep-for-custom-sast-rules should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md --create-dirs "https://raw.githubusercontent.com/mukul975/Anthropic-Cybersecurity-Skills/main/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/implementing-semgrep-for-custom-sast-rules/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How implementing-semgrep-for-custom-sast-rules Compares

Feature / Agentimplementing-semgrep-for-custom-sast-rulesStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Write custom Semgrep SAST rules in YAML to detect application-specific vulnerabilities, enforce coding standards, and integrate into CI/CD pipelines.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Implementing Semgrep for Custom SAST Rules

## Overview

Semgrep is an open-source static analysis tool that uses pattern-matching to find bugs, enforce code standards, and detect security vulnerabilities. Custom rules are written in YAML using Semgrep's pattern syntax, making it accessible without requiring compiler knowledge. It supports 30+ languages including Python, JavaScript, Go, Java, and C.


## When to Use

- When deploying or configuring implementing semgrep for custom sast rules capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation

## Prerequisites

- Python 3.8+ or Docker
- Semgrep CLI installed
- Target codebase in a supported language

## Installation

```bash
# Install via pip
pip install semgrep

# Install via Homebrew
brew install semgrep

# Run via Docker
docker run -v "${PWD}:/src" returntocorp/semgrep semgrep --config auto /src

# Verify
semgrep --version
```

## Running Semgrep

```bash
# Auto-detect rules for your code
semgrep --config auto .

# Use Semgrep registry rules
semgrep --config r/python.lang.security

# Use custom rule file
semgrep --config my-rules.yaml .

# Use multiple configs
semgrep --config auto --config ./custom-rules/ .

# JSON output
semgrep --config auto --json . > results.json

# SARIF output for GitHub
semgrep --config auto --sarif . > results.sarif

# Filter by severity
semgrep --config auto --severity ERROR .
```

## Writing Custom Rules

### Basic Pattern Matching

```yaml
# rules/sql-injection.yaml
rules:
  - id: sql-injection-string-format
    languages: [python]
    severity: ERROR
    message: |
      Potential SQL injection via string formatting.
      Use parameterized queries instead.
    pattern: |
      cursor.execute(f"..." % ...)
    metadata:
      cwe: ["CWE-89"]
      owasp: ["A03:2021"]
      category: security
    fix: |
      cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
```

### Pattern Operators

```yaml
rules:
  - id: hardcoded-secret-in-code
    languages: [python, javascript, typescript]
    severity: ERROR
    message: Hardcoded secret detected in source code
    patterns:
      - pattern-either:
          - pattern: $VAR = "..."
          - pattern: $VAR = '...'
      - metavariable-regex:
          metavariable: $VAR
          regex: (?i)(password|secret|api_key|token|aws_secret)
      - pattern-not: $VAR = ""
      - pattern-not: $VAR = "changeme"
      - pattern-not: $VAR = "PLACEHOLDER"
    metadata:
      cwe: ["CWE-798"]
      category: security
```

### Taint Analysis

```yaml
rules:
  - id: xss-taint-tracking
    languages: [python]
    severity: ERROR
    message: User input flows to HTML response without sanitization
    mode: taint
    pattern-sources:
      - pattern: request.args.get(...)
      - pattern: request.form.get(...)
      - pattern: request.form[...]
    pattern-sinks:
      - pattern: return render_template_string(...)
      - pattern: Markup(...)
    pattern-sanitizers:
      - pattern: bleach.clean(...)
      - pattern: escape(...)
    metadata:
      cwe: ["CWE-79"]
      owasp: ["A03:2021"]
```

### Multiple Language Rule

```yaml
rules:
  - id: insecure-random
    languages: [python, javascript, go, java]
    severity: WARNING
    message: |
      Using insecure random number generator. Use cryptographically
      secure alternatives for security-sensitive operations.
    pattern-either:
      # Python
      - pattern: random.random()
      - pattern: random.randint(...)
      # JavaScript
      - pattern: Math.random()
      # Go
      - pattern: math/rand.Intn(...)
      # Java
      - pattern: new java.util.Random()
    metadata:
      cwe: ["CWE-330"]
```

### Enforce Coding Standards

```yaml
rules:
  - id: require-error-handling
    languages: [go]
    severity: WARNING
    message: Error return value not checked
    pattern: |
      $VAR, _ := $FUNC(...)
    fix: |
      $VAR, err := $FUNC(...)
      if err != nil {
        return fmt.Errorf("$FUNC failed: %w", err)
      }

  - id: no-console-log-in-production
    languages: [javascript, typescript]
    severity: WARNING
    message: Remove console.log before merging to production
    pattern: console.log(...)
    paths:
      exclude:
        - "tests/*"
        - "*.test.*"
```

### JWT Security Rules

```yaml
rules:
  - id: jwt-none-algorithm
    languages: [python]
    severity: ERROR
    message: JWT decoded without algorithm verification - allows token forgery
    patterns:
      - pattern: jwt.decode($TOKEN, ..., algorithms=["none"], ...)
    metadata:
      cwe: ["CWE-347"]

  - id: jwt-no-verification
    languages: [python]
    severity: ERROR
    message: JWT decoded with verification disabled
    patterns:
      - pattern: jwt.decode($TOKEN, ..., options={"verify_signature": False}, ...)
    metadata:
      cwe: ["CWE-345"]
```

## Rule Testing

```yaml
# rules/test-sql-injection.yaml
rules:
  - id: sql-injection-format-string
    languages: [python]
    severity: ERROR
    message: SQL injection via format string
    pattern: |
      cursor.execute(f"...{$VAR}...")

# Test annotation in test file:
# test-sql-injection.py
def bad_query(user_id):
    # ruleid: sql-injection-format-string
    cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

def good_query(user_id):
    # ok: sql-injection-format-string
    cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
```

```bash
# Run rule tests
semgrep --test rules/

# Test specific rule
semgrep --config rules/sql-injection.yaml --test
```

## CI/CD Integration

### GitHub Actions

```yaml
name: Semgrep SAST
on: [pull_request]

jobs:
  semgrep:
    runs-on: ubuntu-latest
    container:
      image: returntocorp/semgrep
    steps:
      - uses: actions/checkout@v4

      - name: Run Semgrep
        run: |
          semgrep --config auto \
            --config ./custom-rules/ \
            --sarif --output results.sarif \
            --severity ERROR \
            .

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

### GitLab CI

```yaml
semgrep:
  stage: test
  image: returntocorp/semgrep
  script:
    - semgrep --config auto --config ./custom-rules/ --json --output semgrep.json .
  artifacts:
    reports:
      sast: semgrep.json
```

## Configuration File

```yaml
# .semgrep.yaml
rules:
  - id: my-org-rules
    # ... rules here

# .semgrepignore
tests/
node_modules/
vendor/
*.min.js
```

## Best Practices

1. **Start with auto config** then add custom rules for org-specific patterns
2. **Test rules** with `# ruleid:` and `# ok:` annotations
3. **Use taint mode** for data flow vulnerabilities (XSS, SQLi, SSRF)
4. **Include metadata** (CWE, OWASP) for vulnerability classification
5. **Provide fix suggestions** with the `fix` key where possible
6. **Exclude test files** to reduce false positives
7. **Version control rules** in a shared repository
8. **Run in CI as a blocking check** for ERROR severity findings

Related Skills

performing-threat-hunting-with-yara-rules

4032
from mukul975/Anthropic-Cybersecurity-Skills

Use YARA pattern-matching rules to hunt for malware, suspicious files, and indicators of compromise across filesystems and memory dumps. Covers rule authoring, yara-python scanning, and integration with threat intel feeds.

integrating-sast-into-github-actions-pipeline

4032
from mukul975/Anthropic-Cybersecurity-Skills

This skill covers integrating Static Application Security Testing (SAST) tools—CodeQL and Semgrep—into GitHub Actions CI/CD pipelines. It addresses configuring automated code scanning on pull requests and pushes, tuning rules to reduce false positives, uploading SARIF results to GitHub Advanced Security, and establishing quality gates that block merges when high-severity vulnerabilities are detected.

implementing-zero-trust-with-hashicorp-boundary

4032
from mukul975/Anthropic-Cybersecurity-Skills

Implement HashiCorp Boundary for identity-aware zero trust infrastructure access management with dynamic credential brokering, session recording, and Vault integration.

implementing-zero-trust-with-beyondcorp

4032
from mukul975/Anthropic-Cybersecurity-Skills

Deploy Google BeyondCorp Enterprise zero trust access controls using Identity-Aware Proxy (IAP), context-aware access policies, device trust validation, and Access Context Manager to enforce identity and posture-based access to GCP resources and internal applications.

implementing-zero-trust-network-access

4032
from mukul975/Anthropic-Cybersecurity-Skills

Implementing Zero Trust Network Access (ZTNA) in cloud environments by configuring identity-aware proxies, micro-segmentation, continuous verification with conditional access policies, and replacing traditional VPN-based access with BeyondCorp-style architectures across AWS, Azure, and GCP.

implementing-zero-trust-network-access-with-zscaler

4032
from mukul975/Anthropic-Cybersecurity-Skills

Implement Zero Trust Network Access using Zscaler Private Access (ZPA) to replace traditional VPN with identity-based, context-aware access to private applications through the Zscaler Zero Trust Exchange.

implementing-zero-trust-in-cloud

4032
from mukul975/Anthropic-Cybersecurity-Skills

This skill guides organizations through implementing zero trust architecture in cloud environments following NIST SP 800-207 and Google BeyondCorp principles. It covers identity-centric access controls, micro-segmentation, continuous verification, device trust assessment, and deploying Identity-Aware Proxy to eliminate implicit network trust in AWS, Azure, and GCP environments.

implementing-zero-trust-for-saas-applications

4032
from mukul975/Anthropic-Cybersecurity-Skills

Implementing zero trust access controls for SaaS applications using CASB, SSPM, conditional access policies, OAuth app governance, and session controls to enforce identity verification, device compliance, and data protection for cloud-hosted services.

implementing-zero-trust-dns-with-nextdns

4032
from mukul975/Anthropic-Cybersecurity-Skills

Implement NextDNS as a zero trust DNS filtering layer with encrypted resolution, threat intelligence blocking, privacy protection, and organizational policy enforcement across all endpoints.

implementing-zero-standing-privilege-with-cyberark

4032
from mukul975/Anthropic-Cybersecurity-Skills

Deploy CyberArk Secure Cloud Access to eliminate standing privileges in hybrid and multi-cloud environments using just-in-time access with time, entitlement, and approval controls.

implementing-zero-knowledge-proof-for-authentication

4032
from mukul975/Anthropic-Cybersecurity-Skills

Zero-Knowledge Proofs (ZKPs) allow a prover to demonstrate knowledge of a secret (such as a password or private key) without revealing the secret itself. This skill implements the Schnorr identificati

implementing-web-application-logging-with-modsecurity

4032
from mukul975/Anthropic-Cybersecurity-Skills

Configure ModSecurity WAF with OWASP Core Rule Set (CRS) for web application logging, tune rules to reduce false positives, analyze audit logs for attack detection, and implement custom SecRules for application-specific threats. The analyst configures SecRuleEngine, SecAuditEngine, and CRS paranoia levels to balance security coverage with operational stability. Activates for requests involving WAF configuration, ModSecurity rule tuning, web application audit logging, or CRS deployment.