Skip to content
Merged
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
11 changes: 11 additions & 0 deletions .clusterfuzzlite/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Build image of the ClusterFuzzLite fuzzers (see build.sh). Pinned by digest; Dependabot or a manual bump
# moves it. tcl is needed to build the SQLite amalgamation, OpenSSL 3 is built by build.sh.
FROM gcr.io/oss-fuzz-base/base-builder@sha256:1f9cf74bc3d7029b528494542f9d9851b256dceed38d3f420989434dc5ae0760

RUN apt-get update \
&& apt-get install -y --no-install-recommends tcl zip \
&& rm -rf /var/lib/apt/lists/*

COPY . $SRC/sealite
WORKDIR $SRC/sealite
COPY .clusterfuzzlite/build.sh $SRC/build.sh
69 changes: 69 additions & 0 deletions .clusterfuzzlite/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/bin/bash -eu
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 pasichdev
#
# Builds the libFuzzer target fuzz/sealite_fuzz.c against the SQLCipher amalgamation. ClusterFuzzLite
# provides CC, CFLAGS (sanitizer and coverage instrumentation), LIB_FUZZING_ENGINE, SRC and OUT.
# SQLCipher's and OpenSSL's versions and sha256 are read from the Gradle build so there is one place to
# bump them. OpenSSL 3 is built from source, statically, with the same instrumentation as the harness: the
# base image ships OpenSSL 1.1, which SQLCipher's provider (EVP_MAC) does not build against. Only the sha256
# of the tarball is checked here, not the PGP signature the Gradle build also checks.

set -eu
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)"
[ -f "$root/fuzz/sealite_fuzz.c" ] || root="$SRC/sealite"
build_file="$root/build-logic/src/main/kotlin/sealite.native.gradle.kts"
version="$(sed -n 's/^val sqlcipherVersion = "\(.*\)"/\1/p' "$build_file")"
sha256="$(sed -n 's/^val sqlcipherSha256 = "\(.*\)"/\1/p' "$build_file")"
cross_file="$root/build-logic/src/main/kotlin/io/github/pasichdev/sealite/build/SealiteCrossPlugin.kt"
ossl_version="$(sed -n 's/^ *val osslVersion = "\(.*\)"/\1/p' "$cross_file")"
ossl_sha256="$(sed -n 's/^ *val osslSha256 = "\(.*\)"/\1/p' "$cross_file")"
[ -n "$version" ] && [ -n "$sha256" ] && [ -n "$ossl_version" ] && [ -n "$ossl_sha256" ]

work="$(mktemp -d)"
curl -fsSL -o "$work/sqlcipher.tar.gz" "https://github.com/sqlcipher/sqlcipher/archive/refs/tags/v${version}.tar.gz"
echo "${sha256} $work/sqlcipher.tar.gz" | sha256sum -c -
tar -xzf "$work/sqlcipher.tar.gz" -C "$work"

curl -fsSL -o "$work/openssl.tar.gz" \
"https://github.com/openssl/openssl/releases/download/openssl-${ossl_version}/openssl-${ossl_version}.tar.gz"
echo "${ossl_sha256} $work/openssl.tar.gz" | sha256sum -c -
tar -xzf "$work/openssl.tar.gz" -C "$work"
mkdir "$work/ossl"
(
cd "$work/ossl"
# Instrumented like the harness (CC and CFLAGS), static, only what SQLCipher's provider calls.
CC="$CC" CFLAGS="$CFLAGS" "$work/openssl-${ossl_version}/Configure" no-shared no-tests no-apps no-docs \
no-module no-engine no-legacy no-ssl no-tls no-dtls no-quic no-comp no-autoload-config > configure.log
make -j"$(nproc)" build_libs > make.log
)
ossl_include=(-I "$work/openssl-${ossl_version}/include" -I "$work/ossl/include")

mkdir "$work/bld"
(
cd "$work/bld"
# The sanitizer flags are for the objects we compile below, not for the build tools of the amalgamation.
CFLAGS= CXXFLAGS= LDFLAGS= "$work"/sqlcipher-*/configure --with-tempstore=yes CFLAGS=-DSQLITE_HAS_CODEC > configure.log
CFLAGS= CXXFLAGS= LDFLAGS= make sqlite3.c > make.log
)

# The flags of the shipped library (NativeFlags.kt), without the progress handler switch (the harness
# uses it to stop runaway queries) and with the same threading mode.
defines=(
-DSQLITE_HAS_CODEC -DSQLCIPHER_CRYPTO_OPENSSL -DSQLITE_TEMP_STORE=3 -DSQLITE_THREADSAFE=2
-DSQLITE_EXTRA_INIT=sqlcipher_extra_init -DSQLITE_EXTRA_SHUTDOWN=sqlcipher_extra_shutdown
-DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_DEFAULT_MEMSTATUS=0 -DSQLITE_SECURE_DELETE
-DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS5
-DSQLITE_ENABLE_JSON1 -DSQLITE_ENABLE_MATH_FUNCTIONS -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_STAT4
-DSQLITE_ENABLE_COLUMN_METADATA -DSQLITE_ENABLE_NORMALIZE -DSQLITE_OMIT_DEPRECATED
-DSQLITE_OMIT_SHARED_CACHE -DSQLITE_HAVE_ISNAN -DHAVE_USLEEP=1
)

"$CC" $CFLAGS "${defines[@]}" -w -I "$work/bld" "${ossl_include[@]}" \
"$root/fuzz/sealite_fuzz.c" "$work/bld/sqlite3.c" \
$LIB_FUZZING_ENGINE "$work/ossl/libcrypto.a" -lpthread -ldl -lm -o "$OUT/sealite_fuzz"

cp "$root/fuzz/sealite_fuzz.dict" "$OUT/sealite_fuzz.dict"
printf '[libfuzzer]\nmax_len = 4096\ntimeout = 20\n' > "$OUT/sealite_fuzz.options"
(cd "$root/fuzz/corpus" && zip -q -j "$OUT/sealite_fuzz_seed_corpus.zip" ./*)
rm -rf "$work"
5 changes: 5 additions & 0 deletions .clusterfuzzlite/project.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
language: c
sanitizers:
- address
- undefined
main_repo: https://github.com/pasichDev/sealite
51 changes: 51 additions & 0 deletions .github/workflows/fuzz-batch.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: fuzz-batch

# ClusterFuzzLite, batch mode: a longer weekly run of the same harness on main, for the inputs a
# five-minute pull-request run does not reach. The corpus is not stored between runs (that needs a
# separate repository and a token); every run starts from the seed corpus in fuzz/corpus.

on:
schedule:
- cron: '17 3 * * 3'
workflow_dispatch:

permissions: {}

concurrency:
group: fuzz-batch
cancel-in-progress: false

jobs:
fuzz:
name: fuzz (${{ matrix.sanitizer }})
runs-on: ubuntu-24.04
timeout-minutes: 90
permissions:
contents: read
strategy:
fail-fast: false
matrix:
sanitizer: [address, undefined]
steps:
- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build the fuzzers (${{ matrix.sanitizer }})
id: build
uses: google/clusterfuzzlite/actions/build_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1
with:
language: c
sanitizer: ${{ matrix.sanitizer }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Run the fuzzers (${{ matrix.sanitizer }})
uses: google/clusterfuzzlite/actions/run_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fuzz-seconds: 3000
mode: batch
sanitizer: ${{ matrix.sanitizer }}
report-unreproducible-crashes: false
output-sarif: false
56 changes: 56 additions & 0 deletions .github/workflows/fuzz-pr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: fuzz-pr

# ClusterFuzzLite, code-change mode: fuzzes the SQLCipher harness (fuzz/sealite_fuzz.c) for a few minutes
# on pull requests that touch the native code or the fuzz setup, with AddressSanitizer and UBSan, and
# fails on a crash or a sanitizer finding. Kept out of ci.yml: it is not part of the required checks.

on:
pull_request:
branches: [main]
paths:
- 'sealite/src/native/**'
- 'fuzz/**'
- '.clusterfuzzlite/**'
- 'build-logic/src/main/kotlin/sealite.native.gradle.kts'
- '.github/workflows/fuzz-pr.yml'

permissions: {}

concurrency:
group: fuzz-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true

jobs:
fuzz:
name: fuzz (${{ matrix.sanitizer }})
runs-on: ubuntu-24.04
timeout-minutes: 30
permissions:
contents: read
strategy:
fail-fast: false
matrix:
sanitizer: [address, undefined]
steps:
- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build the fuzzers (${{ matrix.sanitizer }})
id: build
uses: google/clusterfuzzlite/actions/build_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1
with:
language: c
sanitizer: ${{ matrix.sanitizer }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Run the fuzzers (${{ matrix.sanitizer }})
uses: google/clusterfuzzlite/actions/run_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fuzz-seconds: 300
mode: code-change
sanitizer: ${{ matrix.sanitizer }}
report-unreproducible-crashes: false
output-sarif: false
79 changes: 79 additions & 0 deletions .github/workflows/sanitizers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
name: sanitizers

# Weekly run of the JVM tests against a JNI library built with AddressSanitizer (SQLCipher and the glue)
# and UBSan (the glue), on Linux x86-64: `jvmTestAsan`, see build-logic/.../sealite.asan.gradle.kts and
# CONTRIBUTING.md. Any finding stops the process and fails the job (halt_on_error, -fno-sanitize-recover),
# and the report is uploaded. Kept out of ci.yml: it is slow and not a required check.

on:
schedule:
- cron: '47 2 * * 2'
workflow_dispatch:

permissions: {}

concurrency:
group: sanitizers
cancel-in-progress: false

jobs:
asan:
name: asan + ubsan (linux-x64)
runs-on: ubuntu-24.04
timeout-minutes: 60
permissions:
contents: read
steps:
- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1
with:
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
# clang 18 explicitly (the one Ubuntu 24.04 ships), and put it first on the PATH as plain `clang`,
# which is the name the Gradle task calls: the runner image may carry another default.
- name: Install clang 18, its sanitizer runtime, the OpenSSL headers and the tools that build SQLCipher
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends clang-18 libclang-rt-18-dev libssl-dev make tcl
mkdir -p "${RUNNER_TEMP}/toolchain"
ln -s /usr/bin/clang-18 "${RUNNER_TEMP}/toolchain/clang"
echo "${RUNNER_TEMP}/toolchain" >> "$GITHUB_PATH"
"${RUNNER_TEMP}/toolchain/clang" --version
# The shipped natives come from the Mac job and are not used here: an empty prebuilt layout only
# keeps Gradle from trying to build them. The sanitizer library is built on this host.
- name: Tests against the sanitizer build
timeout-minutes: 50
env:
PREBUILT: ${{ runner.temp }}/no-natives
run: |
mkdir -p "${PREBUILT}/jvm/natives"
./gradlew :sealite:jvmTestAsan -Psealite.prebuiltNatives="${PREBUILT}" --stacktrace
# With log_path set, a finding is written to asan.<pid> next to the test reports, so a red job
# always has the report to read.
- name: A finding fails the job even if Gradle did not
if: always()
run: |
if compgen -G "sealite/build/reports/asan/asan.*" > /dev/null; then
echo "::error::a sanitizer report was written"
head -n 80 sealite/build/reports/asan/asan.*
exit 1
fi
- name: Upload reports
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: reports-sanitizers
path: |
sealite/build/reports/asan
sealite/build/reports/tests
sealite/build/test-results
if-no-files-found: ignore
retention-days: 14
40 changes: 40 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,44 @@ The Kotlin library code must stay at **100 % line and branch coverage** of the J
against it and writes line and branch coverage of `sealite_jni.c` and `sealite_key.c` (not the
SQLCipher amalgamation) to `sealite/build/reports/c-coverage/`.

### Sanitizers and fuzzing

Two checks look for memory errors in the C code. Neither is part of `ci.yml` or of the required checks.

**Sanitizer run** (`sanitizers.yml`, every Tuesday and on demand; locally `./gradlew :sealite:jvmTestAsan`,
on a Mac with no other setup, on Linux with `-Psealite.prebuiltNatives=<dir>` where `<dir>/jvm/natives`
may be empty). It builds the SQLCipher amalgamation and the JNI glue with AddressSanitizer, builds our own
C (`sealite/src/native/jni`) also with UBSan (`-fno-sanitize-recover`), preloads the sanitizer runtime into
the JVM and runs the whole JVM test suite against that library, including the boundary tests
(`BoundaryInputTest`, `CloseRaceTest`: invalid SQL, U+0000, unpaired surrogates, empty and multi-megabyte
values, long paths, statement and connection misuse, close racing prepare and step). A finding stops the
process and fails the job; the report is uploaded as `reports-sanitizers`.

What it covers: use-after-free, overflows and leaks of the glue and of SQLCipher/SQLite on Linux x86-64
(and, locally, macOS arm64); undefined behaviour in the glue; every code path the shared tests reach.

What it does not cover:

- the shipped libraries are different builds: Windows, Android and Apple code, CommonCrypto, the static
OpenSSL of the release libraries and the Kotlin/Native bindings (`NativeRawDb`, `NativeStatement`) are not
sanitized. On Linux the system OpenSSL is linked and is not instrumented;
- UBSan is off for the SQLite amalgamation, which trips it by design (for example a signed overflow when
a statement is bound at index `Int.MIN_VALUE`, wrapped before SQLite's own range check);
- leak detection is off (the JVM would report its own allocations);
- the tests choose the inputs: the sanitizer finds what they reach. The fuzzer below picks its own;
- Java and Kotlin memory safety, and races between threads (no ThreadSanitizer run).

**Fuzzing** (`fuzz-pr.yml`, `fuzz-batch.yml`; ClusterFuzzLite). `fuzz/sealite_fuzz.c` is a libFuzzer harness
for the C layer without the JVM: it opens a temporary or in-memory SQLCipher database, keys it the way the
library does (compatibility, KDF iterations, page size, key and rekey from the input), and prepares and
steps SQL from the input with bound text, text16 and blob values. Pull requests that touch the native code
fuzz for five minutes with AddressSanitizer and with UBSan; a weekly batch runs 50 minutes. The seed corpus
is `fuzz/corpus`; the corpus found by a run is not stored between runs. Reproduce a crash with the
`.clusterfuzzlite/build.sh` build (see the file for the variables it reads) and run the binary on the
crashing input. A crash that is a bug of ours becomes a test in `BoundaryInputTest`; one in SQLite or
SQLCipher goes upstream. The harness covers the SQLCipher layer, not the JNI glue (`sealite_jni.c`),
which needs a JVM and is covered by the sanitizer run.

## Before you open a pull request

```sh
Expand Down Expand Up @@ -133,6 +171,8 @@ ci.yml (pull requests, main)
`- ci-ok fails unless every job above succeeded
pr-title.yml the pull request title is a Conventional Commit
codeql.yml CodeQL for the C glue
sanitizers.yml weekly: the JVM tests against an ASan + UBSan build (Linux)
fuzz-pr.yml, fuzz-batch.yml ClusterFuzzLite: the SQLCipher harness, five minutes per pull request, weekly batch
security.yml zizmor, the linter for the workflows themselves
scorecard.yml OpenSSF Scorecard
release-please.yml, release.yml see Releases
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,20 @@ abstract class BuildJniLibraryTask
val jniIncludes = listOf(jdk.resolve("include"), jdk.resolve("include").resolve(jniIncludeSubdir.get()))
jniIncludes.forEach { if (!it.isDirectory) throw GradleException("No JNI headers at $it") }

val sysroot = capture("xcrun", "--sdk", "macosx", "--show-sdk-path").trim()
val common =
listOf("clang") + targetArgs.get() +
// An Apple SDK on a Mac; the system headers on a Linux host (the sanitizer build).
val mac = System.getProperty("os.name").startsWith("Mac")
val sysrootArgs =
if (mac) {
listOf(
"-isysroot",
sysroot,
capture("xcrun", "--sdk", "macosx", "--show-sdk-path").trim(),
)
} else {
emptyList()
}
val common =
listOf("clang") + targetArgs.get() + sysrootArgs +
listOf(
"-fvisibility=hidden",
"-fPIC",
"-include",
Expand Down Expand Up @@ -163,7 +171,8 @@ abstract class BuildJniLibraryTask
commandLine(
listOf(
"clang",
) + targetArgs.get() + listOf("-isysroot", sysroot, "-dynamiclib", "-fvisibility=hidden") +
) + targetArgs.get() + sysrootArgs +
listOf(if (mac) "-dynamiclib" else "-shared", "-fvisibility=hidden") +
objects.map { it.absolutePath } + linkArgs.get() + listOf("-o", lib.absolutePath),
)
}
Expand Down
Loading
Loading