Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
name: Bug report
about: Report a false positive, false negative, or crash in a query
title: ''
labels: bug
assignees: ''

---

**Describe the bug**
A clear description of what is wrong. Is this a false positive, false negative, crash, or something else?

**Query involved**
Which query or pack is affected (for example, `trailofbits/cpp-queries` or the specific query ID reported in the alert).

**To reproduce**
1. CodeQL CLI version (`codeql --version`):
2. Language/database under analysis:
3. Exact command invocation:
4. Minimal code snippet or repository link that triggers the issue:

**Expected behavior**
What you expected the query to report (or not report).

**Actual behavior**
What the query actually reported, including alert locations and any error output.

**Additional context**
Add any other context about the problem here.
20 changes: 20 additions & 0 deletions .github/ISSUE_TEMPLATE/request_feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
13 changes: 13 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
version: 2

updates:
- package-ecosystem: github-actions
cooldown:
default-days: 7
directory: /
groups:
actions:
patterns:
- "*"
schedule:
interval: daily
27 changes: 27 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Publish CodeQL packs

on:
release:
types: [published]

permissions: {}

jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- uses: trailofbits/setup-codeql@615e3864087261d42cce229e3eec419ab9b22c36 # main
with:
version: '2.25.1'
platform: 'linux64'
checksum: '4f070e6cc7009e75aec307ed109c2fcf0501e579c20a31080b893e31209523d5'
- run: make test
- run: make publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
17 changes: 13 additions & 4 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,24 @@ on:
branches:
- main

permissions: {}

jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: trailofbits/setup-codeql@main
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- uses: trailofbits/setup-codeql@615e3864087261d42cce229e3eec419ab9b22c36 # main
with:
version: '2.23.8'
version: '2.25.1'
platform: 'linux64'
checksum: 'e61bc8aa8d86d45acd9d1c36629a12bbfb3365cd07a31666a2ebc91c6a1940b2'
checksum: '4f070e6cc7009e75aec307ed109c2fcf0501e579c20a31080b893e31209523d5'
- uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0
- run: make format-check
- run: make test
- name: Verify doc/QUERIES.md is up to date
run: |
make generate-table
git diff --exit-code doc/QUERIES.md
13 changes: 9 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,19 @@ Test `.cpp` files include stubs via relative paths:

Stubs only need enough declarations for CodeQL to resolve types and function names — no implementations required.

## Updating README Query Tables
## Updating Query Tables

When a query is added, removed, or its metadata changes, regenerate the README tables:
When a query is added, removed, or its metadata changes, regenerate `doc/QUERIES.md`:
```sh
python ./scripts/queries_table_generator.py 2>/dev/null
make generate-table
```

This reads query metadata from all "full" suites and outputs markdown tables. Copy-paste the output into `README.md` under the `## Queries` section.
This reads query metadata from all "full" suites and writes markdown tables to `doc/QUERIES.md`. The file is generated — do not hand-edit it.

The accompanying per-query markdown docs in `<lang>/src/docs/` are regenerated from each query's `.qhelp` file with:
```sh
make generate-help
```

## Qlpack Versioning

Expand Down
21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ format-check:
find . \( -iname '*.ql' -o -iname '*.qll' \) -print0 | \
xargs -0 codeql query format --check-only

download:
codeql pack download trailofbits/cpp-all trailofbits/cpp-queries trailofbits/go-queries trailofbits/java-queries

pack-install:
find . -iname "qlpack.yml" -exec \
sh -c 'codeql pack install $$(dirname "$$1")' sh {} \;
Expand All @@ -18,4 +21,20 @@ pack-upgrade:
find . -iname "qlpack.yml" -exec \
sh -c 'codeql pack upgrade $$(dirname "$$1")' sh {} \;

.PHONY: test format format-check pack-install pack-upgrade
generate-table:
uv run --with pyyaml \
python ./scripts/queries_table_generator.py > doc/QUERIES.md.tmp
mv doc/QUERIES.md.tmp doc/QUERIES.md

generate-help:
codeql generate query-help ./cpp/src/ --format=markdown --output ./cpp/src/docs
codeql generate query-help ./go/src/ --format=markdown --output ./go/src/docs
codeql generate query-help ./java/src/ --format=markdown --output ./java/src/docs

publish:
codeql pack publish cpp/lib/
codeql pack publish cpp/src/
codeql pack publish go/src/
codeql pack publish java/src/

.PHONY: test format format-check download pack-install pack-upgrade generate-table generate-help publish
131 changes: 24 additions & 107 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,137 +2,54 @@

This repository contains CodeQL queries developed by Trail of Bits and made available to the public. They are part of our ongoing development efforts and are used in our security audits, vulnerability research, and internal projects. They will evolve over time as we identify new techniques.

## Using custom CodeQL queries
## Setup

The easiest is to [download all packs](https://docs.github.com/en/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/publishing-and-using-codeql-packs#running-codeql-pack-download-scopepack) from the GitHub registry:
```sh
codeql pack download trailofbits/cpp-queries trailofbits/go-queries
```bash
make download
codeql resolve packs | grep trailofbits
```

Then verify that new queries are installed:
```sh
codeql resolve qlpacks | grep trailofbits
```
See [QUERIES.md](doc/QUERIES.md) for the full list of queries.

And use the queries for analysis:
```sh
## Usage

```bash
codeql database analyze database.db --format=sarif-latest --output=./tob.sarif -- trailofbits/cpp-queries
# or
codeql database analyze database.db --format=sarif-latest --output=./tob.sarif -- trailofbits/go-queries
codeql database analyze database.db --format=sarif-latest --output=./tob.sarif -- trailofbits/java-queries
```

## Queries

### C and C++

#### Cryptography

| Name | Description | Severity | Precision |
| --- | ----------- | :----: | :--------: |
|[BN_CTX_free called before BN_CTX_end](./cpp/src/docs/crypto/BnCtxFreeBeforeEnd.md)|Detects BN_CTX_free called before BN_CTX_end, which violates the required lifecycle|error|medium|
|[Unbalanced BN_CTX_start and BN_CTX_end pair](./cpp/src/docs/crypto/UnbalancedBnCtx.md)|Detects if one call in the BN_CTX_start/BN_CTX_end pair is missing|warning|medium|
|[Crypto variable initialized using static key](./cpp/src/docs/crypto/StaticKeyFlow.md)|Finds crypto variables initialized using static keys|error|high|
|[Crypto variable initialized using static password](./cpp/src/docs/crypto/StaticPasswordFlow.md)|Finds crypto variables initialized using static passwords|error|high|
|[Crypto variable initialized using weak randomness](./cpp/src/docs/crypto/WeakRandomnessTaint.md)|Finds crypto variables initialized using weak randomness|error|high|
|[Invalid key size](./cpp/src/docs/crypto/InvalidKeySize.md)|Tests if keys passed to EVP_EncryptInit and EVP_EncryptInit_ex have the same size as the key size of the cipher used|warning|medium|
|[Memory leak related to custom allocator](./cpp/src/docs/crypto/CustomAllocatorLeak.md)|Finds memory leaks from custom allocated memory|warning|medium|
|[Memory use after free related to custom allocator](./cpp/src/docs/crypto/CustomAllocatorUseAfterFree.md)|Finds use-after-frees related to custom allocators like `BN_new`|warning|medium|
|[Missing OpenSSL engine initialization](./cpp/src/docs/crypto/MissingEngineInit.md)|Finds created OpenSSL engines that may not be properly initialized|warning|medium|
|[Missing error handling](./cpp/src/docs/crypto/MissingErrorHandling.md)|Checks if returned error codes are properly checked|warning|high|
|[Missing zeroization of potentially sensitive random BIGNUM](./cpp/src/docs/crypto/MissingZeroization.md)|Determines if random bignums are properly zeroized|warning|medium|
|[Random buffer too small](./cpp/src/docs/crypto/RandomBufferTooSmall.md)|Finds buffer overflows in calls to CSPRNGs|warning|high|
|[Use of legacy cryptographic algorithm](./cpp/src/docs/crypto/UseOfLegacyAlgorithm.md)|Detects potential instantiations of legacy cryptographic algorithms|warning|medium|

#### Security

| Name | Description | Severity | Precision |
| --- | ----------- | :----: | :--------: |
|[Async unsafe signal handler](./cpp/src/docs/security/AsyncUnsafeSignalHandler/AsyncUnsafeSignalHandler.md)|Async unsafe signal handler (like the one used in CVE-2024-6387)|warning|high|
|[Decrementation overflow when comparing](./cpp/src/docs/security/DecOverflowWhenComparing/DecOverflowWhenComparing.md)|This query finds unsigned integer overflows resulting from unchecked decrementation during comparison.|error|high|
|[Find all problematic implicit casts](./cpp/src/docs/security/UnsafeImplicitConversions/UnsafeImplicitConversions.md)|Find all implicit casts that may be problematic. That is, casts that may result in unexpected truncation, reinterpretation or widening of values.|error|high|
|[Inconsistent handling of return values from a specific function](./cpp/src/docs/security/InconsistentReturnValueHandling/InconsistentReturnValueHandling.md)|Detects functions whose return values are compared inconsistently across call sites, which may indicate bugs|warning|medium|
|[Invalid string size passed to string manipulation function](./cpp/src/docs/security/CStrnFinder/CStrnFinder.md)|Finds calls to functions that take as input a string and its size as separate arguments (e.g., `strncmp`, `strncat`, ...) and the size argument is wrong|error|low|
|[Iterator invalidation](./cpp/src/docs/security/IteratorInvalidation/IteratorInvalidation.md)|Modifying a container while iterating over it can invalidate iterators, leading to undefined behavior.|warning|medium|
|[Missing null terminator](./cpp/src/docs/security/NoNullTerminator/NoNullTerminator.md)|This query finds incorrectly initialized strings that are passed to functions expecting null-byte-terminated strings|error|high|

### Go

#### Cryptography

| Name | Description | Severity | Precision |
| --- | ----------- | :----: | :--------: |
|[Message not hashed before signature verification](./go/src/docs/crypto/MsgNotHashedBeforeSigVerfication/MsgNotHashedBeforeSigVerfication.md)|Detects calls to (EC)DSA APIs with a message that was not hashed. If the message is longer than the expected hash digest size, it is silently truncated|error|medium|

#### Security

| Name | Description | Severity | Precision |
| --- | ----------- | :----: | :--------: |
|[Invalid file permission parameter](./go/src/docs/security/FilePermsFlaws/FilePermsFlaws.md)|Finds non-octal (e.g., `755` vs `0o755`) and unsupported (e.g., `04666`) literals used as a filesystem permission parameter (`FileMode`)|error|medium|
|[Missing MinVersion in tls.Config](./go/src/docs/security/MissingMinVersionTLS/MissingMinVersionTLS.md)|Finds uses of tls.Config where MinVersion is not set and the project's minimum Go version (from go.mod) indicates insecure defaults: Go < 1.18 for clients or Go < 1.22 for servers. Does not mark explicitly set versions (including explicitly insecure ones).|error|medium|
|[Trim functions misuse](./go/src/docs/security/TrimMisuse/TrimMisuse.md)|Finds calls to `string.{Trim,TrimLeft,TrimRight}` with the 2nd argument not being a cutset but a continuous substring to be trimmed|error|low|

### Java-kotlin

#### Security

| Name | Description | Severity | Precision |
| --- | ----------- | :----: | :--------: |
|[Recursive functions](./java-kotlin/src/docs/security/Recursion/Recursion.md)|Detects possibly unbounded recursive calls|warning|low|

## Query suites

CodeQL queries are grouped into "suites". To execute queries from a specific suit add its name after a colon: `trailofbits/cpp-queries:codeql-suites/tob-cpp-full.qls`.
CodeQL queries are grouped into suites. To execute queries from a specific suite add its name after a colon: `trailofbits/cpp-queries:codeql-suites/tob-cpp-full.qls`.

The recommended suit - `tob-cpp-code-scanning.qls` - is chosen and executed when you do not explicitly specify any suit. Other suits in this repository are:
The recommended suite - `tob-cpp-code-scanning.qls` - is chosen and executed when you do not explicitly specify any suite. Other suites in this repository are:

* `tob-<lang>-crypto.qls` - queries targeting cryptographic vulnerabilities
* `tob-<lang>-security.qls` - queries targeting standard security issues
* `tob-<lang>-full.qls` - all queries, including experimental ones

## Development

#### Prepare environment
### Prepare environment

Configure global CodeQL's search path:

Clone this repository and configure global CodeQL's search path:
```sh
git clone git@github.com:trailofbits/codeql-queries.git
```bash
git clone https://github.com/trailofbits/codeql-queries
mkdir -p "${HOME}/.config/codeql/"
echo "--search-path '$PWD/codeql-queries'" > "${HOME}/.config/codeql/config"
```

Check that CodeQL CLI detects the new qlpacks:
```sh
codeql resolve packs | grep trailofbits
```

#### Before committing
cd codeql-queries/
make pack-install

Run tests:

```sh
make test
```

Format queries:

```sh
make format
```

Install dependencies:

```sh
make install
codeql resolve packs | grep trailofbits
```

Generate query tables and copy-paste it to README.md file
```sh
python ./scripts/queries_table_generator.py 2>/dev/null
```
### Before committing

Generate markdown query help files
```sh
codeql generate query-help ./cpp/src/ --format=markdown --output ./cpp/src/docs
codeql generate query-help ./go/src/ --format=markdown --output ./go/src/docs
codeql generate query-help ./java/src/ --format=markdown --output ./java/src/docs
```bash
make pack-upgrade
make test format
make generate-table generate-help
```
24 changes: 12 additions & 12 deletions cpp/lib/codeql-pack.lock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@
lockVersion: 1.0.0
dependencies:
codeql/controlflow:
version: 2.0.22
version: 2.0.31
codeql/cpp-all:
version: 6.1.3
version: 9.0.0
codeql/dataflow:
version: 2.0.22
version: 2.1.3
codeql/mad:
version: 1.0.38
version: 1.0.47
codeql/quantum:
version: 0.0.16
version: 0.0.25
codeql/rangeanalysis:
version: 1.0.38
version: 1.0.47
codeql/ssa:
version: 2.0.14
version: 2.0.23
codeql/tutorial:
version: 1.0.38
version: 1.0.47
codeql/typeflow:
version: 1.0.38
version: 1.0.47
codeql/typetracking:
version: 2.0.22
version: 2.0.31
codeql/util:
version: 2.0.25
version: 2.0.34
codeql/xml:
version: 1.0.38
version: 1.0.47
compiled: false
Loading
Loading