implementing-semgrep-for-custom-sast-rules
使用 YAML 编写自定义 Semgrep SAST 规则,以检测应用程序特定漏洞、执行编码标准并集成到 CI/CD 管道中。
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.
使用 YAML 编写自定义 Semgrep SAST 规则,以检测应用程序特定漏洞、执行编码标准并集成到 CI/CD 管道中。
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
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/implementing-semgrep-for-custom-sast-rules/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How implementing-semgrep-for-custom-sast-rules Compares
| Feature / Agent | implementing-semgrep-for-custom-sast-rules | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
使用 YAML 编写自定义 Semgrep SAST 规则,以检测应用程序特定漏洞、执行编码标准并集成到 CI/CD 管道中。
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.
SKILL.md Source
# 使用 Semgrep 实施自定义 SAST 规则
## 概述
Semgrep 是一个开源静态分析工具,使用模式匹配来发现漏洞、执行代码标准并检测安全漏洞。自定义规则使用 Semgrep 的模式语法以 YAML 编写,无需编译器知识即可使用。支持 30+ 种语言,包括 Python、JavaScript、Go、Java 和 C。
## 前置条件
- Python 3.8+ 或 Docker
- 已安装 Semgrep CLI
- 支持语言的目标代码库
## 安装
```bash
# 通过 pip 安装
pip install semgrep
# 通过 Homebrew 安装
brew install semgrep
# 通过 Docker 运行
docker run -v "${PWD}:/src" returntocorp/semgrep semgrep --config auto /src
# 验证
semgrep --version
```
## 运行 Semgrep
```bash
# 自动检测代码规则
semgrep --config auto .
# 使用 Semgrep 注册表规则
semgrep --config r/python.lang.security
# 使用自定义规则文件
semgrep --config my-rules.yaml .
# 使用多个配置
semgrep --config auto --config ./custom-rules/ .
# JSON 输出
semgrep --config auto --json . > results.json
# SARIF 输出(用于 GitHub)
semgrep --config auto --sarif . > results.sarif
# 按严重性过滤
semgrep --config auto --severity ERROR .
```
## 编写自定义规则
### 基本模式匹配
```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,))
```
### 模式运算符
```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
```
### 污点分析
```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"]
```
### 多语言规则
```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"]
```
### 执行编码标准
```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 安全规则
```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"]
```
## 规则测试
```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-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
# 运行规则测试
semgrep --test rules/
# 测试特定规则
semgrep --config rules/sql-injection.yaml --test
```
## CI/CD 集成
### 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
```
## 配置文件
```yaml
# .semgrep.yaml
rules:
- id: my-org-rules
# ... rules here
# .semgrepignore
tests/
node_modules/
vendor/
*.min.js
```
## 最佳实践
1. **从 auto 配置开始**,然后为组织特定模式添加自定义规则
2. **使用 `# ruleid:` 和 `# ok:` 注解测试规则**
3. **对数据流漏洞(XSS、SQLi、SSRF)使用污点模式**
4. **包含元数据**(CWE、OWASP)用于漏洞分类
5. **在可能的情况下通过 `fix` 键提供修复建议**
6. **排除测试文件**以减少误报
7. **在共享仓库中对规则进行版本控制**
8. **在 CI 中作为 ERROR 严重性发现的阻塞检查运行**Related Skills
performing-threat-hunting-with-yara-rules
使用 YARA 模式匹配规则在文件系统和内存转储中狩猎恶意软件、可疑文件和入侵指标。 涵盖规则编写、yara-python 扫描以及与威胁情报源的集成。
integrating-sast-into-github-actions-pipeline
本技能涵盖将静态应用安全测试(SAST)工具 CodeQL 和 Semgrep 集成到 GitHub Actions CI/CD 管道中。 内容包括配置对 pull request 和推送的自动代码扫描、调整规则以减少误报、将 SARIF 结果上传到 GitHub Advanced Security,以及建立在检测到高严重性漏洞时阻止合并的质量门禁。
implementing-zero-trust-with-hashicorp-boundary
使用 HashiCorp Boundary 实现具备动态凭据代理、会话录制和 Vault 集成的身份感知零信任基础设施访问管理。
implementing-zero-trust-with-beyondcorp
使用身份感知代理(IAP,Identity-Aware Proxy)、上下文感知访问策略、设备信任验证和 Access Context Manager,部署 Google BeyondCorp Enterprise 零信任访问控制,对 GCP 资源和内部应用强制执行基于身份和安全态势的访问。
implementing-zero-trust-network-access
通过配置身份感知代理、微分段、基于条件访问策略的持续验证,以及在 AWS、Azure 和 GCP 环境中以 BeyondCorp 风格的架构替代传统 VPN 访问,在云环境中实施零信任网络访问(ZTNA)。
implementing-zero-trust-network-access-with-zscaler
使用 Zscaler 实施零信任网络访问(Zero Trust Network Access,ZTNA),通过 Zscaler Private Access(ZPA)配置应用分段、访问策略和连接器,替代传统 VPN 架构
implementing-zero-trust-in-cloud
本技能指导组织按照 NIST SP 800-207 和 Google BeyondCorp 原则在云环境中实施零信任(Zero Trust)架构,涵盖以身份为中心的访问控制、微分段(Micro-Segmentation)、持续验证、设备信任评估,以及部署身份感知代理(Identity-Aware Proxy)以消除 AWS、Azure 和 GCP 环境中的隐式网络信任。
implementing-zero-trust-for-saas-applications
使用 CASB、SSPM、条件访问策略、OAuth 应用治理和会话控制,为 SaaS 应用实施零信任访问控制, 对云托管服务强制执行身份验证、设备合规性检查和数据保护。
implementing-zero-trust-dns-with-nextdns
将 NextDNS 实施为零信任 DNS 过滤层,提供加密解析、威胁情报阻断、隐私保护,以及跨所有端点的组织策略执行。
implementing-zero-standing-privilege-with-cyberark
部署 CyberArk Secure Cloud Access,通过基于时间、权限和审批控制的即时访问,在混合云和多云环境中消除常设权限。
implementing-zero-knowledge-proof-for-authentication
零知识证明(ZKP)允许证明者在不泄露秘密本身的情况下证明对某个秘密(如密码或私钥)的了解。本技能实现 Schnorr 身份识别协议和使用离散对数问题的简化 ZKPP,使服务器永远不需要获取用户密码即可完成认证。
implementing-web-application-logging-with-modsecurity
配置带有 OWASP 核心规则集(CRS)的 ModSecurity WAF,实现 Web 应用程序日志记录, 调整规则以减少误报,分析审计日志进行攻击检测,并为应用程序特定威胁实现自定义 SecRules。 分析师配置 SecRuleEngine、SecAuditEngine 和 CRS 偏执级别,以在安全覆盖范围和运营稳定性之间取得平衡。 适用于涉及 WAF 配置、ModSecurity 规则调整、Web 应用审计日志或 CRS 部署的场景。