用途:Semgrep 是轻量级静态分析工具,通过 YAML 规则匹配代码模式。针对 Solidity,可编写自定义规则检测漏洞、反模式与协议特定缺陷,结合社区规则集与项目自定义规则使用。
主要能力:模式匹配基于 AST,忽略空白与格式差异;支持元变量($X)、省略号、深度表达式操作符;pattern-either(或)、pattern-not(排除)、pattern-inside(作用域)组合逻辑;taint 模式追踪从 source 到 sink 的数据流,支持标签与 sanitizer;fix 键可自动修复简单模式替换;内置规则测试(ruleid/ok/todoruleid 注解)。
使用方式:安装可用 pip install semgrep、brew install semgrep 或 Docker。运行社区规则:git clone https://github.com/Decurity/semgrep-smart-contracts.git /tmp/semgrep-rules 后执行 semgrep --config /tmp/semgrep-rules/solidity/ ./contracts/。单规则文件用 semgrep --config my-rules/reentrancy.yaml ./contracts/。JSON 输出加 --json。自动修复用 --autofix,预览加 --dryrun。测试用 semgrep --test ./rules/。CI 可集成 GitHub Actions 或 pre-commit。
适用场景:智能合约安全审计、CI/CD 流水线扫描、自定义项目不变量检测。
限制:Solidity 支持由社区维护(tree-sitter-solidity),非官方,可能滞后于最新语法;Semgrep 只匹配定义的 AST 模式,不做符号执行或约束求解;--config auto 不包含 Solidity 规则;自动修复仅适用于简单替换,无法处理复杂重构;不能替代 Slither 等具备深度 Solidity 理解的工具。