Static analysis fails when rules are too slow to run in pull requests or too noisy for developers to read. Generic rules miss internal architecture patterns, and writing custom checks often feels like deciphering abstract syntax trees. If your team relies on custom patterns to catch business logic flaws or recurring internal bugs, you need a rule writing workflow that integrates cleanly into existing pipelines.
This guide covers how to write a custom Semgrep rule from scratch, test it locally against a target codebase, optimize its performance for large repositories, and run it in continuous integration without adding minutes to your build times.
Anatomy of a Semgrep Rule
Semgrep uses pattern matching based on concrete syntax trees rather than text regex or deep type resolution. This makes rules fast and portable across languages. A rule consists of an id, metadata, a message, severity, language specifier, and the pattern itself.
Create a file named custom-sql-concat.yaml in your rules directory:
rules:
- id: custom-sql-concatenation
message: Detected raw string concatenation inside a database query execution. Use parameterized queries instead.
severity: ERROR
languages:
- python
patterns:
- pattern: cursor.execute($QUERY + $PARAMS)
- metavariable-regex:
metavariable: $QUERY
regex: .*(SELECT|INSERT|UPDATE|DELETE).*
In this example, $QUERY and $PARAMS are metavariables. Semgrep binds any expression to these variables during traversal. The metavariable-regex operator narrows matches down to queries containing SQL keywords, avoiding false positives on harmless string additions.
Testing Your Rule Locally
Never push a new rule straight to CI. Test it locally against vulnerable and clean code snippets to verify that it flags the intended anti-pattern while ignoring safe usages.
Create a test file named test_target.py:
# Vulnerable
cursor.execute("SELECT * FROM users WHERE id = " + user_id)
# Safe
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
Run Semgrep locally using the config flag pointing to your YAML rule:
semgrep --config custom-sql-concat.yaml test_target.py
The output highlights the exact line where the vulnerable concatenation occurs, showing the matched code block and the corresponding message. If the rule matches the safe example, refine your patterns using either pattern-not or stricter metavariable constraints.
Handling Complex Patterns with Ellipses
Real world code rarely matches rigid single-line patterns. Semgrep provides the ellipsis operator (...) to match arbitrary code structures, arguments, or statements.
Suppose you want to catch instances where an internal logging function receives sensitive key names without masking. Your rule needs to traverse function arguments regardless of how many parameters are passed.
rules:
- id: unmasked-token-logging
message: Logging potential secret or token without redaction.
severity: WARNING
languages:
- python
pattern: logger.info(..., token=$TOKEN...)
The leading and trailing ellipses tell Semgrep to ignore any arguments preceding or following the token= keyword argument. This technique keeps your rules concise while covering varied call signatures across different modules.
Integrating the Rule Into Continuous Integration
Adding custom rules to your CI pipeline requires balancing thoroughness with execution speed. Running every rule against every file on every commit causes bottlenecks as codebases grow.
Here is a GitHub Actions workflow snippet that runs Semgrep using the official CLI with your local rule set:
name: Security Analysis
on:
pull_request:
branches: [main]
jobs:
semgrep:
runs-on: ubuntu-latest
container:
image: returntocorp/semgrep
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Run custom rules
run: semgrep --config=.github/rules/custom-sql-concat.yaml --error --metrics=off
To prevent slow builds, use incremental scanning. Instead of scanning the entire repository on every pull request, target only the changed files or directories when possible. The Semgrep CLI accepts specific paths as arguments, allowing you to pass git diff output directly into the scan command.
Fixing Violations Without Waiting for Upstream
When a custom rule flags an active violation in production code, waiting for the original author to refactor can leave a window open. You can automate the remediation process by pairing Semgrep with automated refactoring using pattern replacement.
Add a fix key to your rule definition:
rules:
- id: insecure-hash-md5
message: MD5 is cryptographically broken. Use SHA-256 instead.
severity: ERROR
languages:
- python
pattern: hashlib.md5(...)
fix: hashlib.sha256(...)
When developers run Semgrep locally with the auto-fix flag, it rewrites the code automatically:
semgrep --config insecure-hash.yaml --autofix .
This turns detection into an active remediation workflow, reducing the manual toil of opening tickets and waiting for code reviews for straightforward cryptographic upgrades.
Optimizing Rule Performance
Poorly written regex within rules can cause exponential backtracking during AST traversal. Follow these practices to keep scan times under ten seconds:
- Anchor your patterns with specific function calls or object names before using ellipses.
- Avoid broad catch-all regex inside
metavariable-regexwhen structural operators can achieve the same result. - Exclude generated files, test fixtures, and vendor directories using a
.semgrepignorefile.
By keeping rules targeted and testing them locally, static analysis becomes a fast, reliable part of the engineering loop rather than a roadblock.