SAST with Semgrep
Overview
Perform comprehensive static application security testing using Semgrep, a fast, open-source
static analysis tool. This skill provides automated vulnerability detection, security code
review workflows, and remediation guidance mapped to OWASP Top 10 and CWE standards.
Quick Start
Scan a codebase for security vulnerabilities:
semgrep --config=auto --severity=ERROR --severity=WARNING /path/to/code
Run with OWASP Top 10 ruleset:
semgrep --config="p/owasp-top-ten" /path/to/code
Core Workflows
Workflow 1: Initial Security Scan
- Identify the primary languages in the codebase
- Run
scripts/semgrep_scan.py with appropriate rulesets
- Parse findings and categorize by severity (CRITICAL, HIGH, MEDIUM, LOW)
- Map findings to OWASP Top 10 and CWE categories
- Generate prioritized remediation report
Workflow 2: Security Code Review
- For pull requests or commits, run targeted scans on changed files
- Use
semgrep --diff to scan only modified code
- Flag high-severity findings as blocking issues
- Provide inline remediation guidance from
references/remediation_guide.md
- Link findings to secure coding patterns
Workflow 3: Custom Rule Development
- Identify organization-specific security patterns to detect
- Create custom Semgrep rules in YAML format using
assets/rule_template.yaml
- Test rules against known vulnerable code samples
- Integrate custom rules into CI/CD pipeline
- Document rules in
references/custom_rules.md
Workflow 4: CI/CD Integration
- Add Semgrep to CI/CD pipeline using
assets/ci_config_examples/
- Configure baseline scanning for pull requests
- Set severity thresholds (fail on CRITICAL/HIGH)
- Generate SARIF output for security dashboards
- Track metrics: vulnerabilities found, fix rate, false positives
Security Considerations
Sensitive Data Handling: Semgrep scans code locally; ensure scan results don't leak
secrets or proprietary code patterns. Use --max-lines-per-finding to limit output.
Access Control: Semgrep scans require read access to source code. Restrict scan
result access to authorized security and development teams.
Audit Logging: Log all scan executions with timestamps, user, commit hash, and
findings count for compliance auditing.
Compliance: SAST scanning supports SOC2, PCI-DSS, and GDPR compliance requirements.
Maintain scan history and remediation tracking.
Safe Defaults: Use --config=auto for balanced detection. For security-critical
applications, use --config="p/security-audit" for comprehensive coverage.
Language Support
Semgrep supports 30+ languages including:
- Web: JavaScript, TypeScript, Python, Ruby, PHP, Java, C#, Go
- Mobile: Swift, Kotlin, Java (Android)
- Infrastructure: Terraform, Dockerfile, YAML, JSON
- Other: C, C++, Rust, Scala, Solidity
Bundled Resources
Scripts
scripts/semgrep_scan.py - Full-featured scanning with OWASP/CWE mapping and reporting
scripts/baseline_scan.sh - Quick baseline scan for CI/CD
scripts/diff_scan.sh - Scan only changed files (for PRs)
References
references/owasp_cwe_mapping.md - OWASP Top 10 to CWE mapping with Semgrep rules
references/remediation_guide.md - Vulnerability remediation patterns by category
references/rule_library.md - Curated list of useful Semgrep rulesets
Assets
assets/rule_template.yaml - Template for creating custom Semgrep rules
assets/ci_config_examples/ - CI/CD integration examples (GitHub Actions, GitLab CI)
assets/semgrep_config.yaml - Recommended Semgrep configuration
Common Patterns
Pattern 1: Daily Security Baseline Scan
# Run comprehensive scan and generate report
scripts/semgrep_scan.py --config security-audit \
--output results.json \
--format json \
--severity HIGH CRITICAL
Pattern 2: Pull Request Security Gate
# Scan only changed files, fail on HIGH/CRITICAL
scripts/diff_scan.sh --fail-on high \
--base-branch main \
--output sarif
Pattern 3: Vulnerability Research
# Search for specific vulnerability patterns
semgrep --config "r/javascript.lang.security.audit.xss" \
--json /path/to/code | jq '.results'
Pattern 4: Custom Rule Validation
# Test custom rule against vulnerable samples
semgrep --config assets/custom_rules.yaml \
--test tests/vulnerable_samples/
Integration Points
CI/CD Integration
- GitHub Actions: Use
semgrep/semgrep-action@v1 with SARIF upload
- GitLab CI: Run as security scanning job with artifact reports
- Jenkins: Execute as build step with quality gate integration
- pre-commit hooks: Run lightweight scans on staged files
See assets/ci_config_examples/ for ready-to-use configurations.
Security Tool Integration
- SIEM/SOAR: Export findings in JSON/SARIF for ingestion
- Vulnerability Management: Integrate with Jira, DefectDojo, or ThreadFix
- IDE Integration: Use Semgrep IDE plugins for real-time detection
- Secret Scanning: Combine with tools like trufflehog, gitleaks
SDLC Integration
- Requirements Phase: Define security requirements and custom rules
- Development: IDE plugins provide real-time feedback
- Code Review: Automated security review in PR workflow
- Testing: Integrate with security testing framework
- Deployment: Final security gate before production
Severity Classification
Semgrep findings are classified by severity:
- CRITICAL: Exploitable vulnerabilities (SQLi, RCE, Auth bypass)
- HIGH: Significant security risks (XSS, CSRF, sensitive data exposure)
- MEDIUM: Security weaknesses (weak crypto, missing validation)
- LOW: Code quality issues with security implications
- INFO: Security best practice recommendations
Performance Optimization
For large codebases:
# Use --jobs for parallel scanning
semgrep --config auto --jobs 4
# Exclude vendor/test code
semgrep --config auto --exclude "vendor/" --exclude "test/"
# Use lightweight rulesets for faster feedback
semgrep --config "p/owasp-top-ten" --exclude-rule "generic.*"
Troubleshooting
Issue: Too Many False Positives
Solution:
- Use
--exclude-rule to disable noisy rules
- Create
.semgrepignore file to exclude false positive patterns
- Tune rules using
--severity filtering
- Add
# nosemgrep comments for confirmed false positives (with justification)
Issue: Scan Taking Too Long
Solution:
- Use
--exclude for vendor/generated code
- Increase
--jobs for parallel processing
- Use targeted rulesets instead of
--config=auto
- Run incremental scans with
--diff
Issue: Missing Vulnerabilities
Solution:
- Use comprehensive rulesets:
p/security-audit or p/owasp-top-ten
- Consult
references/rule_library.md for specialized rules
- Create custom rules for organization-specific patterns
- Combine with dynamic analysis (DAST) and dependency scanning
Advanced Usage
Creating Custom Rules
See references/rule_library.md for guidance on writing effective Semgrep rules.
Use assets/rule_template.yaml as a starting point.
Example rule structure:
rules:
- id: custom-sql-injection
patterns:
- pattern: execute($QUERY)
- pattern-inside: |
$QUERY = $USER_INPUT + ...
message: Potential SQL injection from user input concatenation
severity: ERROR
languages: [python]
metadata:
cwe: "CWE-89"
owasp: "A03:2021-Injection"
OWASP Top 10 Coverage
This skill provides detection for all OWASP Top 10 2021 categories.
See references/owasp_cwe_mapping.md for complete coverage matrix.
Best Practices
- Baseline First: Establish security baseline before enforcing gates
- Progressive Rollout: Start with HIGH/CRITICAL, expand to MEDIUM over time
- Developer Training: Educate team on common vulnerabilities and fixes
- Rule Maintenance: Regularly update rulesets and tune for your stack
- Metrics Tracking: Monitor vulnerability trends, MTTR, and false positive rate
- Defense in Depth: Combine with DAST, SCA, and manual code review
References
1---2name: sast-semgrep3description: Static application security testing (SAST) using Semgrep for vulnerability detection, security code review, and secure coding guidance with OWASP and CWE framework mapping. Use when: (1) Scanning code for security vulnerabilities across multiple languages, (2) Performing security code reviews with pattern-based detection, (3) Integrating SAST checks into CI/CD pipelines, (4) Providing remediation guidance with OWASP Top 10 and CWE mappings, (5) Creating custom security rules for organization-specific patterns, (6) Analyzing dependencies for known vulnerabilities.4---56# SAST with Semgrep78## Overview910Perform comprehensive static application security testing using Semgrep, a fast, open-source11static analysis tool. This skill provides automated vulnerability detection, security code12review workflows, and remediation guidance mapped to OWASP Top 10 and CWE standards.1314## Quick Start1516Scan a codebase for security vulnerabilities:1718```bash19semgrep --config=auto --severity=ERROR --severity=WARNING /path/to/code20```2122Run with OWASP Top 10 ruleset:2324```bash25semgrep --config="p/owasp-top-ten" /path/to/code26```2728## Core Workflows2930### Workflow 1: Initial Security Scan31321. Identify the primary languages in the codebase332. Run `scripts/semgrep_scan.py` with appropriate rulesets343. Parse findings and categorize by severity (CRITICAL, HIGH, MEDIUM, LOW)354. Map findings to OWASP Top 10 and CWE categories365. Generate prioritized remediation report3738### Workflow 2: Security Code Review39401. For pull requests or commits, run targeted scans on changed files412. Use `semgrep --diff` to scan only modified code423. Flag high-severity findings as blocking issues434. Provide inline remediation guidance from `references/remediation_guide.md`445. Link findings to secure coding patterns4546### Workflow 3: Custom Rule Development47481. Identify organization-specific security patterns to detect492. Create custom Semgrep rules in YAML format using `assets/rule_template.yaml`503. Test rules against known vulnerable code samples514. Integrate custom rules into CI/CD pipeline525. Document rules in `references/custom_rules.md`5354### Workflow 4: CI/CD Integration55561. Add Semgrep to CI/CD pipeline using `assets/ci_config_examples/`572. Configure baseline scanning for pull requests583. Set severity thresholds (fail on CRITICAL/HIGH)594. Generate SARIF output for security dashboards605. Track metrics: vulnerabilities found, fix rate, false positives6162## Security Considerations6364- **Sensitive Data Handling**: Semgrep scans code locally; ensure scan results don't leak65 secrets or proprietary code patterns. Use `--max-lines-per-finding` to limit output.6667- **Access Control**: Semgrep scans require read access to source code. Restrict scan68 result access to authorized security and development teams.6970- **Audit Logging**: Log all scan executions with timestamps, user, commit hash, and71 findings count for compliance auditing.7273- **Compliance**: SAST scanning supports SOC2, PCI-DSS, and GDPR compliance requirements.74 Maintain scan history and remediation tracking.7576- **Safe Defaults**: Use `--config=auto` for balanced detection. For security-critical77 applications, use `--config="p/security-audit"` for comprehensive coverage.7879## Language Support8081Semgrep supports 30+ languages including:82- **Web**: JavaScript, TypeScript, Python, Ruby, PHP, Java, C#, Go83- **Mobile**: Swift, Kotlin, Java (Android)84- **Infrastructure**: Terraform, Dockerfile, YAML, JSON85- **Other**: C, C++, Rust, Scala, Solidity8687## Bundled Resources8889### Scripts9091- `scripts/semgrep_scan.py` - Full-featured scanning with OWASP/CWE mapping and reporting92- `scripts/baseline_scan.sh` - Quick baseline scan for CI/CD93- `scripts/diff_scan.sh` - Scan only changed files (for PRs)9495### References9697- `references/owasp_cwe_mapping.md` - OWASP Top 10 to CWE mapping with Semgrep rules98- `references/remediation_guide.md` - Vulnerability remediation patterns by category99- `references/rule_library.md` - Curated list of useful Semgrep rulesets100101### Assets102103- `assets/rule_template.yaml` - Template for creating custom Semgrep rules104- `assets/ci_config_examples/` - CI/CD integration examples (GitHub Actions, GitLab CI)105- `assets/semgrep_config.yaml` - Recommended Semgrep configuration106107## Common Patterns108109### Pattern 1: Daily Security Baseline Scan110111```bash112# Run comprehensive scan and generate report113scripts/semgrep_scan.py --config security-audit \114 --output results.json \115 --format json \116 --severity HIGH CRITICAL117```118119### Pattern 2: Pull Request Security Gate120121```bash122# Scan only changed files, fail on HIGH/CRITICAL123scripts/diff_scan.sh --fail-on high \124 --base-branch main \125 --output sarif126```127128### Pattern 3: Vulnerability Research129130```bash131# Search for specific vulnerability patterns132semgrep --config "r/javascript.lang.security.audit.xss" \133 --json /path/to/code | jq '.results'134```135136### Pattern 4: Custom Rule Validation137138```bash139# Test custom rule against vulnerable samples140semgrep --config assets/custom_rules.yaml \141 --test tests/vulnerable_samples/142```143144## Integration Points145146### CI/CD Integration147148- **GitHub Actions**: Use `semgrep/semgrep-action@v1` with SARIF upload149- **GitLab CI**: Run as security scanning job with artifact reports150- **Jenkins**: Execute as build step with quality gate integration151- **pre-commit hooks**: Run lightweight scans on staged files152153See `assets/ci_config_examples/` for ready-to-use configurations.154155### Security Tool Integration156157- **SIEM/SOAR**: Export findings in JSON/SARIF for ingestion158- **Vulnerability Management**: Integrate with Jira, DefectDojo, or ThreadFix159- **IDE Integration**: Use Semgrep IDE plugins for real-time detection160- **Secret Scanning**: Combine with tools like trufflehog, gitleaks161162### SDLC Integration163164- **Requirements Phase**: Define security requirements and custom rules165- **Development**: IDE plugins provide real-time feedback166- **Code Review**: Automated security review in PR workflow167- **Testing**: Integrate with security testing framework168- **Deployment**: Final security gate before production169170## Severity Classification171172Semgrep findings are classified by severity:173174- **CRITICAL**: Exploitable vulnerabilities (SQLi, RCE, Auth bypass)175- **HIGH**: Significant security risks (XSS, CSRF, sensitive data exposure)176- **MEDIUM**: Security weaknesses (weak crypto, missing validation)177- **LOW**: Code quality issues with security implications178- **INFO**: Security best practice recommendations179180## Performance Optimization181182For large codebases:183184```bash185# Use --jobs for parallel scanning186semgrep --config auto --jobs 4187188# Exclude vendor/test code189semgrep --config auto --exclude "vendor/" --exclude "test/"190191# Use lightweight rulesets for faster feedback192semgrep --config "p/owasp-top-ten" --exclude-rule "generic.*"193```194195## Troubleshooting196197### Issue: Too Many False Positives198199**Solution**:200- Use `--exclude-rule` to disable noisy rules201- Create `.semgrepignore` file to exclude false positive patterns202- Tune rules using `--severity` filtering203- Add `# nosemgrep` comments for confirmed false positives (with justification)204205### Issue: Scan Taking Too Long206207**Solution**:208- Use `--exclude` for vendor/generated code209- Increase `--jobs` for parallel processing210- Use targeted rulesets instead of `--config=auto`211- Run incremental scans with `--diff`212213### Issue: Missing Vulnerabilities214215**Solution**:216- Use comprehensive rulesets: `p/security-audit` or `p/owasp-top-ten`217- Consult `references/rule_library.md` for specialized rules218- Create custom rules for organization-specific patterns219- Combine with dynamic analysis (DAST) and dependency scanning220221## Advanced Usage222223### Creating Custom Rules224225See `references/rule_library.md` for guidance on writing effective Semgrep rules.226Use `assets/rule_template.yaml` as a starting point.227228Example rule structure:229```yaml230rules:231 - id: custom-sql-injection232 patterns:233 - pattern: execute($QUERY)234 - pattern-inside: |235 $QUERY = $USER_INPUT + ...236 message: Potential SQL injection from user input concatenation237 severity: ERROR238 languages: [python]239 metadata:240 cwe: "CWE-89"241 owasp: "A03:2021-Injection"242```243244### OWASP Top 10 Coverage245246This skill provides detection for all OWASP Top 10 2021 categories.247See `references/owasp_cwe_mapping.md` for complete coverage matrix.248249## Best Practices2502511. **Baseline First**: Establish security baseline before enforcing gates2522. **Progressive Rollout**: Start with HIGH/CRITICAL, expand to MEDIUM over time2533. **Developer Training**: Educate team on common vulnerabilities and fixes2544. **Rule Maintenance**: Regularly update rulesets and tune for your stack2555. **Metrics Tracking**: Monitor vulnerability trends, MTTR, and false positive rate2566. **Defense in Depth**: Combine with DAST, SCA, and manual code review257258## References259260- [Semgrep Documentation](https://semgrep.dev/docs/)261- [Semgrep Rule Registry](https://semgrep.dev/explore)262- [OWASP Top 10 2021](https://owasp.org/Top10/)263- [CWE Top 25](https://cwe.mitre.org/top25/)264- [SANS Top 25](https://www.sans.org/top25-software-errors/)