codeql-semgrep
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCodeQL & Semgrep
CodeQL & Semgrep
Part of Agent Skills™ by googleadsagent.ai™
属于 Agent Skills™,由 googleadsagent.ai™ 提供
Description
描述
CodeQL & Semgrep integrates production-grade static analysis into agent workflows for deep vulnerability detection, custom rule authoring, and automated code review enforcement. The agent writes CodeQL queries and Semgrep rules tailored to project-specific patterns, runs them against codebases, and interprets results with actionable remediation guidance.
Pattern-matching security scanners catch surface-level issues. CodeQL and Semgrep operate at a deeper level: CodeQL builds a relational database of the program's structure and evaluates queries that trace data flow from sources (user input) to sinks (dangerous operations). Semgrep matches syntactic patterns with type-aware analysis. Together, they catch vulnerabilities that regex-based scanners miss entirely.
This skill goes beyond running default rulesets. The agent writes custom rules for project-specific patterns: ensuring all database queries use the project's ORM wrapper, verifying that authentication middleware is applied to every route, or confirming that error responses never leak stack traces. Custom rules encode institutional security knowledge that persists beyond any individual reviewer.
CodeQL 与 Semgrep 将生产级静态分析集成到 Agent 工作流中,用于深度漏洞检测、自定义规则编写和自动化代码审查强制执行。Agent 会针对项目特定模式编写 CodeQL 查询和 Semgrep 规则,对代码库运行这些规则与查询,并解读结果,提供切实可行的修复建议。
基于模式匹配的安全扫描器只能发现表层问题。CodeQL 和 Semgrep 则能在更深层次运行:CodeQL 构建程序结构的关系型数据库,并通过查询追踪从源(用户输入)到汇点(危险操作)的数据流。Semgrep 使用类型感知分析匹配语法模式。二者结合使用,可以发现基于 regex 的扫描器完全无法检测到的漏洞。
该 Skill 不仅止于运行默认规则集。Agent 会针对项目特定模式编写自定义规则,例如确保所有数据库查询都使用项目的 ORM 封装层、验证每个路由都应用了身份验证中间件,或确认错误响应绝不泄露堆栈跟踪。自定义规则将组织的安全知识固化下来,使其不受任何单个审查者的影响而持续保留。
Use When
使用时机
- Running static analysis on AI-generated or human-written code
- Writing custom security rules for project-specific patterns
- Integrating security scanning into CI/CD pipelines
- Tracing data flow from user input to dangerous operations
- Enforcing architectural security constraints (auth on all routes, ORM usage)
- The user requests "static analysis", "CodeQL", or "Semgrep"
- 对 AI 生成或人工编写的代码运行静态分析
- 为项目特定模式编写自定义安全规则
- 将安全扫描集成到 CI/CD 流水线
- 追踪从用户输入到危险操作的数据流
- 强制执行架构安全约束(所有路由均需认证、使用 ORM)
- 用户请求“静态分析”、“CodeQL”或“Semgrep”
How It Works
工作原理
mermaid
graph TD
A[Codebase] --> B{Analysis Engine}
B -->|Data Flow| C[CodeQL: Build Database]
B -->|Pattern Match| D[Semgrep: Parse AST]
C --> E[Run CodeQL Queries]
D --> F[Run Semgrep Rules]
E --> G[Taint Tracking: Source → Sink]
F --> H[Pattern Matches + Metavariables]
G --> I[Merge Findings]
H --> I
I --> J[Deduplicate + Prioritize]
J --> K[Remediation Report]
K --> L[CI/CD Gate: Pass/Fail]CodeQL excels at data flow analysis (tracing tainted input through the program); Semgrep excels at pattern matching (finding structural anti-patterns). Running both provides comprehensive coverage.
mermaid
graph TD
A[Codebase] --> B{Analysis Engine}
B -->|Data Flow| C[CodeQL: Build Database]
B -->|Pattern Match| D[Semgrep: Parse AST]
C --> E[Run CodeQL Queries]
D --> F[Run Semgrep Rules]
E --> G[Taint Tracking: Source → Sink]
F --> H[Pattern Matches + Metavariables]
G --> I[Merge Findings]
H --> I
I --> J[Deduplicate + Prioritize]
J --> K[Remediation Report]
K --> L[CI/CD Gate: Pass/Fail]CodeQL 擅长数据流分析(追踪受污染输入在整个程序中的传播);Semgrep 擅长模式匹配(发现结构性反模式)。同时运行两者可提供全面覆盖。
Implementation
实现
Semgrep Rules
Semgrep 规则
yaml
undefinedyaml
undefined.semgrep/agent-rules.yml
.semgrep/agent-rules.yml
rules:
-
id: sql-injection-f-string patterns:
- pattern: | $CURSOR.execute(f"...", ...) message: > SQL query uses f-string interpolation, which is vulnerable to SQL injection. Use parameterized queries instead. severity: ERROR languages: [python] metadata: cwe: ["CWE-89"] confidence: HIGH
-
id: missing-auth-middleware patterns:
- pattern: | @app.route($PATH, ...) def $FUNC(...): ...
- pattern-not-inside: | @require_auth @app.route($PATH, ...) def $FUNC(...): ... message: > Route handler $FUNC lacks @require_auth decorator. All routes must be authenticated unless explicitly exempted. severity: WARNING languages: [python] metadata: cwe: ["CWE-306"]
-
id: no-eval-user-input patterns:
- pattern: eval($X)
- pattern-where-python: | not $X.startswith('"') message: "eval() called with potentially dynamic input" severity: ERROR languages: [python] metadata: cwe: ["CWE-95"]
undefinedrules:
-
id: sql-injection-f-string patterns:
- pattern: | $CURSOR.execute(f"...", ...) message: > SQL query uses f-string interpolation, which is vulnerable to SQL injection. Use parameterized queries instead. severity: ERROR languages: [python] metadata: cwe: ["CWE-89"] confidence: HIGH
-
id: missing-auth-middleware patterns:
- pattern: | @app.route($PATH, ...) def $FUNC(...): ...
- pattern-not-inside: | @require_auth @app.route($PATH, ...) def $FUNC(...): ... message: > Route handler $FUNC lacks @require_auth decorator. All routes must be authenticated unless explicitly exempted. severity: WARNING languages: [python] metadata: cwe: ["CWE-306"]
-
id: no-eval-user-input patterns:
- pattern: eval($X)
- pattern-where-python: | not $X.startswith('"') message: "eval() called with potentially dynamic input" severity: ERROR languages: [python] metadata: cwe: ["CWE-95"]
undefinedCodeQL Query
CodeQL 查询
ql
/**
* @name SQL injection from request parameter
* @description Finds SQL queries constructed from HTTP request parameters
* @kind path-problem
* @severity error
* @id agent-skills/sql-injection
* @tags security
* cwe-089
*/
import python
import semmle.python.dataflow.new.TaintTracking
import semmle.python.ApiGraphs
class SqlInjectionConfig extends TaintTracking::Configuration {
SqlInjectionConfig() { this = "SqlInjectionConfig" }
override predicate isSource(DataFlow::Node source) {
exists(API::CallNode call |
call = API::moduleImport("flask").getMember("request").getMember("args").getMember("get").getACall() and
source = call
)
}
override predicate isSink(DataFlow::Node sink) {
exists(API::CallNode call |
call = API::moduleImport("sqlite3").getMember("Cursor").getMember("execute").getACall() and
sink = call.getArg(0)
)
}
}
from SqlInjectionConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "SQL query depends on $@.", source.getNode(), "user input"ql
/**
* @name SQL injection from request parameter
* @description Finds SQL queries constructed from HTTP request parameters
* @kind path-problem
* @severity error
* @id agent-skills/sql-injection
* @tags security
* cwe-089
*/
import python
import semmle.python.dataflow.new.TaintTracking
import semmle.python.ApiGraphs
class SqlInjectionConfig extends TaintTracking::Configuration {
SqlInjectionConfig() { this = "SqlInjectionConfig" }
override predicate isSource(DataFlow::Node source) {
exists(API::CallNode call |
call = API::moduleImport("flask").getMember("request").getMember("args").getMember("get").getACall() and
source = call
)
}
override predicate isSink(DataFlow::Node sink) {
exists(API::CallNode call |
call = API::moduleImport("sqlite3").getMember("Cursor").getMember("execute").getACall() and
sink = call.getArg(0)
)
}
}
from SqlInjectionConfig config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, "SQL query depends on $@.", source.getNode(), "user input"CI/CD Integration
CI/CD 集成
yaml
undefinedyaml
undefinedGitHub Actions
GitHub Actions
-
name: Semgrep Scan uses: semgrep/semgrep-action@v1 with: config: >- p/owasp-top-ten p/r2c-security-audit .semgrep/agent-rules.yml
-
name: CodeQL Analysis uses: github/codeql-action/analyze@v3 with: languages: python, javascript queries: +.codeql/custom-queries
undefined-
name: Semgrep Scan uses: semgrep/semgrep-action@v1 with: config: >- p/owasp-top-ten p/r2c-security-audit .semgrep/agent-rules.yml
-
name: CodeQL Analysis uses: github/codeql-action/analyze@v3 with: languages: python, javascript queries: +.codeql/custom-queries
undefinedBest Practices
最佳实践
- Run both CodeQL (data flow) and Semgrep (pattern matching) for complementary coverage
- Write custom rules for project-specific security invariants (auth, ORM, input validation)
- Add rules incrementally—start with high-confidence, low-false-positive patterns
- Include CWE IDs in every rule for standardized vulnerability classification
- Run scans on every PR and block merges on ERROR-severity findings
- Review and update custom rules quarterly as the codebase architecture evolves
- 同时运行 CodeQL(数据流)和 Semgrep(模式匹配),获得互补覆盖
- 针对项目特定的安全不变量(认证、ORM、输入验证)编写自定义规则
- 增量添加规则——从高置信度、低误报模式开始
- 在每条规则中加入 CWE ID,以进行标准化漏洞分类
- 在每个 PR 上运行扫描,并在发现 ERROR 严重级别问题时阻止合并
- 随着代码库架构演进,每季度审查并更新自定义规则
Platform Compatibility
平台兼容性
| Platform | Support | Notes |
|---|---|---|
| Cursor | Full | Rule authoring + CI config |
| VS Code | Full | Semgrep extension |
| Windsurf | Full | Static analysis integration |
| Claude Code | Full | Query/rule generation |
| Cline | Full | Security rule authoring |
| aider | Partial | YAML/QL file editing |
| 平台 | 支持情况 | 备注 |
|---|---|---|
| Cursor | 完全支持 | 规则编写 + CI 配置 |
| VS Code | 完全支持 | Semgrep 扩展 |
| Windsurf | 完全支持 | 静态分析集成 |
| Claude Code | 完全支持 | 查询/规则生成 |
| Cline | 完全支持 | 安全规则编写 |
| aider | 部分支持 | YAML/QL 文件编辑 |
Related Skills
相关 Skills
- Agent Security Scanning - Broader vulnerability detection covering dependency CVEs and agent-specific threat models
- Secret Protection - Credential leak scanning that complements static analysis with secret-specific pattern matching
- CI/CD Pipelines - Pipeline configuration where CodeQL and Semgrep scans run as automated quality gates
- Agent Security Scanning - 覆盖依赖项 CVE 和 Agent 特定威胁模型的广泛漏洞检测
- Secret Protection - 凭据泄露扫描,通过密钥专用模式匹配补充静态分析
- CI/CD Pipelines - 运行 CodeQL 和 Semgrep 扫描并将其作为自动化质量门禁的流水线配置
Keywords
关键词
codeqlsemgrepstatic-analysissasttaint-trackingcustom-rulesvulnerability-detectionci-cd-security© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
codeqlsemgrepstatic-analysissasttaint-trackingcustom-rulesvulnerability-detectionci-cd-security© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License