
Implementing Semgrep for Custom SAST Rules
FreeEnhance code security with custom Semgrep rules.
Free · Opens the source repo
What Implementing Semgrep for Custom SAST Rules does
Implementing Semgrep for Custom SAST Rules is a skill designed to leverage Semgrep, an open-source static analysis tool, to create tailored security rules that can identify vulnerabilities and enforce coding standards in your codebase. By writing custom rules in YAML, developers can easily adapt Semgrep to their specific application needs without requiring deep compiler knowledge. This flexibility allows for the detection of application-specific vulnerabilities across more than 30 programming languages, including Python, JavaScript, Go, and Java.
The skill supports integration into CI/CD pipelines, enabling automated security checks as part of the development process. Users can run Semgrep to auto-detect rules, utilize existing registry rules, or apply their custom rules to ensure compliance with security standards. The output can be formatted in various ways, including JSON and SARIF, making it easy to integrate findings into existing workflows or reporting tools.
This skill is particularly useful for development teams focused on enhancing their security posture through proactive measures. By establishing a set of custom rules that align with their coding standards and security requirements, teams can significantly reduce the risk of vulnerabilities being introduced into their applications. Additionally, the ability to test these rules against code ensures that security measures are effective and reliable.
Whether you are building a new application or improving the security architecture of an existing one, this skill provides the necessary tools to implement robust static analysis practices. It is an essential addition for developers and security professionals aiming to integrate security into their development lifecycle effectively.
When to use it
Use this skill when you need to enforce specific coding standards or detect vulnerabilities in your codebase as part of a security assessment or CI/CD integration.
When not to use it
This skill may not be suitable for environments where static analysis is not a priority or where existing tools already meet security compliance needs.
What you can build with it
Integrating Security in CI/CD
Use this skill to automatically run Semgrep checks as part of your CI/CD pipeline, ensuring code security before deployment.
Custom Vulnerability Detection
Develop tailored Semgrep rules to identify specific vulnerabilities relevant to your application’s context.
Enforcing Coding Standards
Implement this skill to enforce coding standards across your development team, reducing the likelihood of security issues.
How to install Implementing Semgrep for Custom SAST Rules
View source1. Install with the skills CLI
npx skills add mukul975/anthropic-cybersecurity-skills/implementing-semgrep-for-custom-sast-rules --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by mukul975Implementing 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
# 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
# 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
# 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
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
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
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
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
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
# 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,))
# Run rule tests
semgrep --test rules/
# Test specific rule
semgrep --config rules/sql-injection.yaml --test
CI/CD Integration
GitHub Actions
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
semgrep:
stage: test
image: returntocorp/semgrep
script:
- semgrep --config auto --config ./custom-rules/ --json --output semgrep.json .
artifacts:
reports:
sast: semgrep.json
Configuration File
# .semgrep.yaml
rules:
- id: my-org-rules
# ... rules here
# .semgrepignore
tests/
node_modules/
vendor/
*.min.js
Best Practices
- Start with auto config then add custom rules for org-specific patterns
- Test rules with
# ruleid:and# ok:annotations - Use taint mode for data flow vulnerabilities (XSS, SQLi, SSRF)
- Include metadata (CWE, OWASP) for vulnerability classification
- Provide fix suggestions with the
fixkey where possible - Exclude test files to reduce false positives
- Version control rules in a shared repository
- Run in CI as a blocking check for ERROR severity findings
Frequently asked questions about Implementing Semgrep for Custom SAST Rules
Similar skills
CodeQL Code Scanning
Streamline CodeQL setup and configuration for security analysis.
Security Review
AI-powered codebase security scanner for vulnerabilities.
Integrating SAST into GitHub Actions
Automate SAST scanning in GitHub Actions workflows.
Infrastructure as Code Security Scanning
Automate security checks for your IaC deployments.
Implementing GitHub Advanced Security
Automate code scanning and vulnerability detection at scale.
Auditing Foundry Smart Contract Security
Ensure your Solidity contracts are secure before deployment.
