/testing-handbook-skills:codeqlfrom testing-handbook-skills
Queries codebases for interprocedural control flow and data flow patterns to find bugs and security vulnerabilities using CodeQL.
Ships in testing-handbook-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
CodeQL is a powerful static analysis framework that allows developers and security researchers to query a codebase for specific code patterns. The CodeQL standard libraries implement support for both inter- and intraprocedural control flow and data flow analysis. However, the learning curve for writing custom queries is steep, and documentation for the CodeQL standard libraries is still scant.
Use CodeQL when:
Consider alternatives when:
| Task | Command |
|---|---|
| Create database (C/C++) | codeql database create codeql.db --language=cpp --command='make -j8' |
| Create database (Go) | codeql database create codeql.db --language=go |
| Create database (Java/Kotlin) | codeql database create codeql.db --language=java |
| Create database (JavaScript/TypeScript) | codeql database create codeql.db --language=javascript |
| Create database (Python) | codeql database create codeql.db --language=python |
| Analyze database | codeql database analyze codeql.db --format=sarif-latest --output=results.sarif -- codeql/cpp-queries |
| List installed packs | codeql resolve qlpacks |
| Download query pack | codeql pack download trailofbits/cpp-queries |
| Run custom query | codeql query run --database codeql.db -- path/to/Query.ql |
| Test custom queries | codeql test run -- path/to/test/pack/ |
CodeQL can be installed manually or via Homebrew on macOS/Linux.
Manual Installation:
Navigate to the CodeQL release page and download the latest bundle for your architecture. The bundle contains the codeql binary, query libraries for supported languages, and pre-compiled queries.
Using Homebrew:
brew install --cask codeql
CodeQL is under active development. Update regularly to benefit from improvements.
Manual installation: Download new updates from the CodeQL release page.
Homebrew installation:
brew upgrade codeql
codeql --version
To build a CodeQL database, you typically need to be able to build the corresponding codebase. Ensure the codebase is in a clean state (e.g., run make clean, go clean, or similar).
For compiled languages (C/C++, Swift):
codeql database create codeql.db --language=cpp --command='make -j8'
If using CMake or out-of-source builds, add --source-root to specify the source file tree root:
codeql database create codeql.db --language=cpp --source-root=/path/to/source --command='cmake --build build'
For interpreted languages (Python, JavaScript):
codeql database create codeql.db --language=python
For languages with auto-detection (Go, Java):
codeql database create codeql.db --language=go
For complex build systems, use the --command argument to pass the build command.
Run pre-compiled query packs on the database:
codeql database analyze codeql.db --format=sarif-latest --output=results.sarif -- codeql/cpp-queries
Output formats include SARIF and CSV. SARIF results can be viewed with the VSCode SARIF Explorer extension.
SARIF files contain findings with location, severity, and description. Import into your IDE or CI/CD pipeline for review and remediation.
Published query packs are identified by scope/name/version. For example:
codeql pack download trailofbits/cpp-queries trailofbits/go-queries
For Trail of Bits public CodeQL queries, see trailofbits/codeql-queries.
CodeQL queries use a declarative, object-oriented language called QL with Java-like syntax and SQL-like query expressions.
Basic query structure:
import cpp
from FunctionCall call
where call.getTarget().getName() = "memcpy"
select call.getLocation(), call.getArgument(0)
This selects all expressions passed as the first argument to memcpy.
Creating a custom class:
import cpp
class MemcpyCall extends FunctionCall {
MemcpyCall() {
this.getTarget().getName() = "memcpy"
}
Expr getDestination() {
result = this.getArgument(0)
}
Expr getSource() {
result = this.getArgument(1)
}
Expr getSize() {
result = this.getArgument(2)
}
}
from MemcpyCall call
select call.getLocation(), call.getDestination()
| Syntax/Operator | Description | Example |
|---|---|---|
from Type x where P(x) select f(x) | Query: select f(x) for all x where P(x) is true | from FunctionCall call where call.getTarget().getName() = "memcpy" select call |
exists(...) | Existential quantification | exists(FunctionCall call | call.getTarget() = fun) |
forall(...) | Universal quantification | forall(Expr e | e = arg.getAChild() | e.isConstant()) |
+ | Transitive closure (1+ times) | start.getASuccessor+() |
* | Reflexive transitive closure (0+ times) | start.getASuccessor*() |
result | Special variable for method/function output | result = this.getArgument(0) |
import cpp
/**
* @name Unhandled error return value
* @id custom/unhandled-error
* @description Function calls that return error codes that are not checked
* @kind problem
* @problem.severity warning
* @precision medium
*/
predicate isErrorReturningFunction(Function f) {
f.getName().matches("%error%") or
f.getName().matches("%Error%")
}
from FunctionCall call
where
isErrorReturningFunction(call.getTarget()) and
not exists(Expr parent |
parent = call.getParent*() and
(parent instanceof IfStmt or parent instanceof SwitchStmt)
)
select call, "Error return value not checked"
Query metadata is defined in an initial comment:
/**
* @name Short name for the issue
* @id scope/query-name
* @description Longer description of the issue
* @kind problem
* @tags security external/cwe/cwe-123
* @problem.severity error
* @precision high
*/
Required fields:
name: Short string identifying the issueid: Unique identifier (lowercase letters, numbers, /, -)description: Longer description (a few sentences)kind: Either problem or path-problemproblem.severity: error, warning, or recommendationprecision: low, medium, high, or very-highOutput format requirements:
problem queries: Output must be (Location, string)path-problem queries: Output must be (DataFlow::Node, DataFlow::PathNode, DataFlow::PathNode, string)Create a test pack with qlpack.yml:
name: scope/name-test
version: 0.0.1
dependencies:
codeql-query-pack-to-test: "*"
extractor: cpp
Create a test directory (e.g., MemcpyCall/) containing:
test.c: Source file with code pattern to detectMemcpyCall.qlref: Text file with path to the queryMemcpyCall.expected: Expected outputRun tests:
codeql test run -- path/to/test/pack/
If MemcpyCall.expected is missing or incorrect, an MemcpyCall.actual file is created. Review it, and if correct, rename to MemcpyCall.expected.
Initialize a query pack:
codeql pack init <scope>/<name>
This creates a qlpack.yml file:
---
library: false
warnOnImplicitThis: false
name: <scope>/<name>
version: 0.0.1
Add standard library dependencies:
codeql pack add codeql/cpp-all
Create a workspace file (codeql-workspace.yml) for the CLI to work correctly.
Install dependencies:
codeql pack install
Configure the CLI to find your queries by creating ~/.config/codeql/config:
--search-path /full/path/to/your/codeql/root/directory
.
├── codeql-workspace.yml
├── cpp
│ ├── lib
│ │ ├── qlpack.yml
│ │ └── scope
│ │ └── security
│ │ └── someLibrary.qll
│ ├── src
│ │ ├── qlpack.yml
│ │ ├── suites
│ │ │ ├── scope-cpp-code-scanning.qls
│ │ │ └── scope-cpp-security.qls
│ │ └── security
│ │ └── AppSecAnalysis
│ │ ├── AppSecAnalysis.c
│ │ ├── AppSecAnalysis.qhelp
│ │ └── AppSecAnalysis.ql
│ └── test
│ ├── qlpack.yml
│ └── query-tests
│ └── security
│ └── AppSecAnalysis
│ ├── AppSecAnalysis.c
│ ├── AppSecAnalysis.expected
│ └── AppSecAnalysis.qlref
Recursive predicate:
predicate isReachableFrom(BasicBlock start, BasicBlock end) {
start = end or isReachableFrom(start.getASuccessor(), end)
}
Using transitive closure (equivalent):
predicate isReachableFrom(BasicBlock start, BasicBlock end) {
end = start.getASuccessor*()
}
Use * for zero or more applications, + for one or more.
CodeQL instruments the build process. If object files already exist and are up-to-date, corresponding source files won't be added to the database. This can reduce database size but means CodeQL has only partial knowledge about excluded files and cannot reason about data flow through them.
Recommendation: Include third-party libraries and filter issues based on location rather than excluding files during database creation.
VSCode: CodeQL extension provides LSP support, syntax highlighting, query running, and AST visualization.
Neovim: codeql.nvim provides similar functionality.
Helix/Other editors: Use the CodeQL LSP server and Tree-sitter grammar for CodeQL.
VSCode Quick Query: Use "CodeQL: Quick Query" command to run single queries against a database.
Debugging queries: Add database source to workspace, then use "CodeQL: View AST" to display the AST for individual nodes.
CodeQL standard libraries are language-specific. Refer to API documentation:
CodeQL supports C/C++, C#, Go, Java, Kotlin, JavaScript, TypeScript, Python, Ruby, and Swift. Check supported languages and frameworks for details.
Enable code scanning from "Code security and analysis" in repository settings. Choose default or advanced setup.
Advanced setup workflow:
name: "CodeQL"
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '34 10 * * 6'
jobs:
analyze:
name: Analyze
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'cpp' ]
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
For compiled languages, replace autobuild with custom build commands:
- run: |
make -j8
Specify query packs and queries in the "Initialize CodeQL" step:
- uses: github/codeql-action/init@v3
with:
queries: security-extended,security-and-quality
packs: trailofbits/cpp-queries
For repository-local queries:
- uses: github/codeql-action/init@v3
with:
queries: ./codeql/UnhandledError.ql
packs: trailofbits/cpp-queries
Note the . prefix for repository-relative paths. All queries must be part of a query pack with a qlpack.yml file.
name: Test CodeQL queries
on: [push, pull_request]
jobs:
codeql-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: init
uses: github/codeql-action/init@v3
- uses: actions/cache@v4
with:
path: ~/.codeql
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.init.outputs.codeql-version }}
- name: Run tests
run: |
${{ steps.init.outputs.codeql-path }} test run ./path/to/query/tests/
This workflow caches query extraction and compilation for faster subsequent runs.
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
| Not building project before creating database | CodeQL won't have complete information | Run make clean or equivalent, then build with CodeQL |
| Excluding third-party libraries from database | Prevents interprocedural analysis through library code | Include libraries, filter results by location |
| Using relative imports in query packs | Causes resolution issues | Use absolute imports from standard libraries |
| Not adding query metadata | SARIF output lacks severity, description | Always add metadata comment with required fields |
| Forgetting workspace file | CLI won't find query packs | Create codeql-workspace.yml in root directory |
| Skill | When to Use Together |
|---|---|
| semgrep | Use Semgrep first for quick pattern-based analysis, then CodeQL for deeper interprocedural analysis |
| sarif-parsing | For processing CodeQL SARIF output in custom CI/CD pipelines |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub fodhol/skills --plugin testing-handbook-skills17 skills in this plugin
/address-sanitizerAddressSanitizer detects memory errors during fuzzing. Use when fuzzing C/C++ code to find buffer overflows and use-after-free bugs.
/aflppAFL++ is a fork of AFL with better fuzzing performance and advanced features. Use for multi-core fuzzing of C/C++ projects.
/atherisAtheris is a coverage-guided Python fuzzer based on libFuzzer. Use for fuzzing pure Python code and Python C extensions.
/cargo-fuzzcargo-fuzz is the de facto fuzzing tool for Rust projects using Cargo. Use for fuzzing Rust code with libFuzzer backend.
/constant-time-testingConstant-time testing detects timing side channels in cryptographic code. Use when auditing crypto implementations for timing vulnerabilities.
/coverage-analysisCoverage analysis measures code exercised during fuzzing. Use when assessing harness effectiveness or identifying fuzzing blockers.
Other plugins' skills for the same job