Semgrep

semgrep/skills/skills/semgrep

作者 semgrep68177b8830f9無授權條款322 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

執行 Semgrep 靜態分析掃描,並協助撰寫自訂 YAML 偵測規則,用於安全性與程式碼品質模式。

功能
提供透過 MCP 工具或命令列執行 Semgrep 掃描的說明,包括規則集選擇、輸出格式、路徑指定與忽略設定。它也指導使用模式比對或汙點模式建立自訂 YAML 規則,並包含測試優先的工作流程與驗證命令。內容涵蓋透過 GitHub Actions 範例進行 CI/CD 整合。
適用情境
當被要求掃描程式碼中的安全性弱點、缺陷或程式碼規範違規,或撰寫與測試自訂 Semgrep 偵測規則時使用。也適用於支援語言中的模式式靜態分析。
執行需求
需透過 pip、Homebrew 或 Docker 安裝 Semgrep,或環境中提供 Semgrep MCP 工具。取得規則集與文件可能需要網路存取。此技能不附帶指令碼。

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
# Homebrewbrew install semgrep
# Dockerdocker 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 rulesetsemgrep --config p/security-audit --config p/trailofbits .  # Multiple
RulesetDescription
p/defaultGeneral security and code quality
p/security-auditComprehensive security rules
p/owasp-top-tenOWASP Top 10 vulnerabilities
p/cwe-top-25CWE Top 25 vulnerabilities
p/trailofbitsTrail of Bits security rules
p/pythonPython-specific
p/javascriptJavaScript-specific
p/golangGo-specific

Output Formats

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

Scan Specific Paths

bash
semgrep --config p/python app.py           # Single filesemgrep --config p/javascript src/         # Directorysemgrep --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-passworddangerous_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

ApproachUse When
Taint modeData flows from untrusted source to dangerous sink (injection vulnerabilities)
Pattern matchingSyntactic 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

SyntaxDescriptionExample
...Match anythingfunc(...)
$VARCapture metavariable$FUNC($INPUT)
<... ...>Deep expression match<... user_input ...>
OperatorDescription
patternMatch exact pattern
patternsAll must match (AND)
pattern-eitherAny matches (OR)
pattern-notExclude matches
pattern-insideMatch only inside context
pattern-not-insideMatch only outside context
metavariable-regexRegex on captured value

Testing Rules

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

python
# test_rule.pydef 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

TaskCommand
Run testssemgrep --test --config rule.yaml test-file
Validate YAMLsemgrep --validate --config rule.yaml
Dump ASTsemgrep --dump-ast -l <lang> <file>
Debug taint flowsemgrep --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:

Local References:

  • Workflow Guide [blocked] - Complete step-by-step rule creation process
  • Quick Reference [blocked] - Pattern operators and taint components

Anti-Patterns to Avoid

Too broad:

yaml
# BAD: Matches any function callpattern: $FUNC(...)
# GOOD: Specific dangerous functionpattern: eval(...)

Missing safe cases:

python
# BAD: Only tests vulnerable case# ruleid: my-ruledangerous(user_input)
# GOOD: Include safe cases# ruleid: my-ruledangerous(user_input)
# ok: my-ruledangerous(sanitize(user_input))

Rationalizations to Reject

ShortcutWhy 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:

General:

來源與署名

來源:semgrep/skills位於skills/semgrep提交68177b8

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架