diff --git a/.forgejo/workflows/android-release.yml b/.forgejo/workflows/android-release.yml index ce98027..6de3ce7 100644 --- a/.forgejo/workflows/android-release.yml +++ b/.forgejo/workflows/android-release.yml @@ -7,10 +7,6 @@ name: android-release # toolchain runs in a sibling debian:bookworm container, # the same stdin-tar + docker cp pattern as .forgejo/workflows/ci.yml. # -# Publish is a separate job on the Pi runner (`docker`). POST /releases from -# the amd64 dind egress returns 422 with an empty body (core run 116); -# core's publish job on the Pi (run 135) is the proven path. -# # First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the # latest v*.*.* tag UNLESS that tag's release is missing the Android assets — # then join it (core owns tag creation). Never move or delete a tag. @@ -71,11 +67,6 @@ jobs: android: runs-on: docker-amd64 timeout-minutes: 90 - outputs: - version: ${{ steps.version.outputs.version }} - tag: ${{ steps.version.outputs.tag }} - version_code: ${{ steps.version.outputs.version_code }} - dry_run: ${{ steps.version.outputs.dry_run }} steps: - name: Checkout uses: https://code.forgejo.org/actions/checkout@v4 @@ -357,75 +348,31 @@ jobs: docker images "$ANDROID_IMAGE" --format '{{.Repository}}:{{.Tag}} {{.Size}}' || true docker system df || true - - name: Upload dist artifact - uses: https://code.forgejo.org/actions/upload-artifact@v3 - with: - name: onionwire-android - path: dist/ - if-no-files-found: error - retention-days: 1 - - - name: Scrub keystore - if: always() - run: | - set -euo pipefail - rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android - echo "keystore removed from runner" - - publish: - needs: android - # Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422 - # with an empty body (core run 116). This job only curls the Forgejo API. - if: needs.android.result == 'success' && needs.android.outputs.dry_run != 'true' - runs-on: docker - timeout-minutes: 20 - steps: - - name: Checkout CI tooling - uses: https://code.forgejo.org/actions/checkout@v4 - with: - path: .ci-tools - - - name: Download Android dist - uses: https://code.forgejo.org/actions/download-artifact@v3 - with: - path: artifacts - - name: Publish (create-or-join) + id: publish + if: steps.version.outputs.dry_run != 'true' env: FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} EVENT_SHA: ${{ github.sha }} - TAG: ${{ needs.android.outputs.tag }} - VERSION: ${{ needs.android.outputs.version }} + TAG: ${{ steps.version.outputs.tag }} + VERSION: ${{ steps.version.outputs.version }} run: | set -euo pipefail + cd "${GITHUB_WORKSPACE}" : "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}" - echo "publish host=$(hostname) arch=$(uname -m) tag=$TAG version=$VERSION" - mkdir -p dist - abi="$ONIONWIRE_ANDROID_ABI" - apk="onionwire-$VERSION-android-$abi.apk" - aar="onionwire-sdk-$VERSION.aar" + apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk" + aar="dist/onionwire-sdk-$VERSION.aar" for f in "$apk" "$apk.sha256" "$aar" "$aar.sha256"; do - src=$(find artifacts -type f -name "$f" -print -quit) - if [ -z "$src" ]; then - echo "missing artifact $f" >&2 - find artifacts -type f >&2 || true - exit 1 - fi - cp "$src" "dist/$f" - done - for f in dist/"$apk" dist/"$apk".sha256 dist/"$aar" dist/"$aar".sha256; do bytes=$(wc -c < "$f") - echo "on disk: $f $bytes bytes" [ "$bytes" -gt 0 ] || { echo "refusing to publish empty $f" >&2; exit 1; } - file "$f" || true done tag_exists=0 i=0 while [ "$i" -lt 6 ]; do code=$(curl -sS --http1.1 -o /tmp/tag.json -w '%{http_code}' \ - -H "Authorization: Bearer ${FORGEJO_TOKEN}" \ + -H "Authorization: Bearer $FORGEJO_TOKEN" \ "$REPO_API/tags/$TAG" || true) if [ "$code" = "200" ]; then tag_exists=1 @@ -437,18 +384,39 @@ jobs: sleep 10 done + created_tag=false if [ "$tag_exists" = "1" ]; then unset TARGET_COMMITISH || true else export TARGET_COMMITISH="$EVENT_SHA" + created_tag=true echo "creating tag $TAG at $TARGET_COMMITISH" fi + echo "created_tag=$created_tag" >> "$GITHUB_OUTPUT" - echo "publishing $TAG from $REPO_API" - .ci-tools/scripts/publish-release.sh \ - "$TAG" "OnionWire $TAG" \ - .ci-tools/scripts/release-body.md \ - "dist/$apk" \ - "dist/$apk.sha256" \ - "dist/$aar" \ - "dist/$aar.sha256" + export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}" + PUB_C=onionwire-android-publish-${{ github.run_id }} + docker rm -f "$PUB_C" >/dev/null 2>&1 || true + docker create --name "$PUB_C" -i \ + -e FORGEJO_TOKEN \ + -e REPO_API \ + -e TARGET_COMMITISH="${TARGET_COMMITISH:-}" \ + -e TAG \ + -w /src \ + "$ANDROID_IMAGE" \ + bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && apt-get update && apt-get install -y --no-install-recommends python3 curl ca-certificates >/dev/null && scripts/publish-release.sh "$TAG" "OnionWire $TAG" scripts/release-body.md dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk.sha256 dist/onionwire-sdk-'"$VERSION"'.aar dist/onionwire-sdk-'"$VERSION"'.aar.sha256' + tar czf - \ + --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./android/.gradle --exclude=./android/app/build \ + --exclude=./android/sdk/build \ + --exclude=./crates/onionwire-sdk/target \ + . \ + | docker start -a -i "$PUB_C" + docker rm -f "$PUB_C" >/dev/null || true + + - name: Scrub keystore + if: always() + run: | + set -euo pipefail + rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android + echo "keystore removed from runner" diff --git a/.forgejo/workflows/arti-watch.yml b/.forgejo/workflows/arti-watch.yml deleted file mode 100644 index 10a0e5f..0000000 --- a/.forgejo/workflows/arti-watch.yml +++ /dev/null @@ -1,72 +0,0 @@ -name: arti-watch - -# Daily upstream check for the in-process Tor stack. Arti onion services are -# experimental (README) and tor-*/arti-* are the largest attack surface here, -# so when crates.io has a newer major.minor than the pins in Cargo.toml this -# files ONE Forgejo issue (deduped on the title — a second run is a no-op). -# -# Forgejo has no Dependabot: this workflow IS the dependency alert. It -# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain -# floor and the tests it must pass are in docs/ARTI_UPGRADE.md. -# -# NOT covered, by design: Tor Project security announcements (a fix that ships -# with no crates.io version bump is invisible here) and a yanked crate / -# vulnerability in a version that has not changed. Read -# https://blog.torproject.org/ yourself. -on: - schedule: - # 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose. - - cron: "17 6 * * *" - workflow_dispatch: - inputs: - dry_run: - description: Compare and log only, file no issue (true/false) - required: false - type: string - default: "false" - simulate_pin: - description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.' - required: false - type: string - -# Never two watchers at once: two simultaneous runs could both see "no issue -# with this title yet" and file twice. -concurrency: - group: onionwire-arti-watch - cancel-in-progress: false - -jobs: - watch: - # Same Pi runner + `docker` job image as ci.yml / release.yml (which run - # python3 and curl there). No cargo, no docker: four crates.io GETs and at - # most one issue POST. - runs-on: docker - timeout-minutes: 10 - steps: - - name: Checkout - uses: https://code.forgejo.org/actions/checkout@v4 - - - name: Compare pins against crates.io and file an issue on a bump - shell: bash - env: - FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} - REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} - INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }} - INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }} - run: | - set -euo pipefail - args=(--cargo-toml Cargo.toml) - case "${INPUT_DRY_RUN:-false}" in - true|True|TRUE|1|yes|YES) args+=(--dry-run) ;; - esac - if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then - IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN" - for pair in "${pairs[@]}"; do - pair="${pair// /}" - if [ -n "$pair" ]; then - args+=(--simulate-pin "$pair") - fi - done - fi - echo "run: python3 scripts/arti-watch.py ${args[*]}" - python3 scripts/arti-watch.py "${args[@]}" diff --git a/Cargo.lock b/Cargo.lock index 758ba2d..1f99c80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2295,7 +2295,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", - "openssl-sys", "pkg-config", "vcpkg", ] @@ -2693,15 +2692,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "openssl-src" -version = "300.6.1+3.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" -dependencies = [ - "cc", -] - [[package]] name = "openssl-sys" version = "0.9.117" @@ -2710,7 +2700,6 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" dependencies = [ "cc", "libc", - "openssl-src", "pkg-config", "vcpkg", ] diff --git a/Cargo.toml b/Cargo.toml index dca8916..7285691 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ futures = "0.3" safelog = "0.9" ed25519-dalek = { version = "2", features = ["rand_core"] } rand = "0.8" -rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] } +rusqlite = { version = "0.36", features = ["bundled"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] } tor-cell = "0.46" tor-hsservice = "0.46" diff --git a/README.md b/README.md index 82aeb2c..fc2f559 100644 --- a/README.md +++ b/README.md @@ -245,26 +245,19 @@ peer and a Linux peer that exchange invites interoperate — one protocol, not t - **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack Compose + Material 3 messenger that depends on the SDK and nothing else. -It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is -amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK. -[`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) -builds on `docker-amd64`, then a second job on the Pi (`docker`) attaches the -APK + AAR (+ `.sha256`) to the same Forgejo tag as the Linux binaries. If that -tag's release already exists and is missing the APK, the workflow **joins** it -instead of minting patch+1. Publish does not run from amd64 dind: `POST /releases` -from that egress returns 422 with an empty body. +It is not a WebView, and `src/tui.rs` is untouched. Both are built on a host with +the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK: ```bash # one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358, # rustup target add aarch64-linux-android, cargo install cargo-ndk scripts/build-android-local.sh # -> dist/, with .sha256 files -PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release +PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release ``` -Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the -repo-owned release keystore. A local run without those env vars still -debug-signs for sideload, not Play. Full build notes, the `minSdk 26` -rationale, the 16 KB page-size check and the signing story are in +Every asset has a matching `.sha256` so `sha256sum -c` works. The APK is +**debug-signed** and is for sideloading, not for Play. Full build notes, the +`minSdk 26` rationale, the 16 KB page-size check and the signing story are in [`android/README.md`](android/README.md). ## Releases (maintainers) diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md deleted file mode 100644 index bb0ad7b..0000000 --- a/docs/ARTI_UPGRADE.md +++ /dev/null @@ -1,143 +0,0 @@ -# Upgrading the Arti / Tor crates - -The in-process Tor stack is the largest attack surface in OnionWire. Arti's -onion services are still **experimental** and OnionWire does not fall back to a -C-tor subprocess, so an upstream fix only reaches users when we bump these -crates, rebuild, and cut a release. - -## What is pinned - -Direct dependencies that come from the Arti repository, exactly as -`Cargo.toml` has them: - -| crate | requirement | features in `Cargo.toml` | -|---|---|---| -| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` | -| `tor-cell` | `0.46` | — | -| `tor-hsservice` | `0.46` | — | -| `tor-rtcompat` | `0.46` | `tokio` | - -`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not -part of a Tor upgrade. - -Two crate features re-expose Arti's TLS backends, which Arti marks -**non-additive** — exactly one may be selected per build graph: - -* `native-tls` (default) → Linux TUI build, via OpenSSL. -* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has - no OpenSSL. - -Published Arti releases move all four crates together in lockstep. Bump them as -**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is -not a configuration anyone tests upstream, and cargo will usually refuse or -silently pick one `tor-*` version and mismatched `tor-*` internals fail at -runtime. - -## Toolchain floor - -**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`; -the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm` -(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`). - -A bump may raise the floor. Take the actual MSRV from the upstream release -notes / the crate's own `rust-version`, then raise it in the same PR: - -* `rust-version` in `Cargo.toml`, -* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`, -* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it - when that lands, or ask the owner). - -## How this gets noticed - -`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks -crates.io for the newest stable version of each crate above. If the -major.minor moved past the pin, it files one Forgejo issue titled -`Arti upstream: → `. It is deduped on that title across open -and closed issues, so re-running it never files a second issue and never -comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit. - -Test the alert path without waiting for upstream (it compares real crates.io -data against a pretend pin): - -``` -# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45 -python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45 -``` - -**What the watcher does not cover.** It does not subscribe to Tor Project -security announcements — a fix that ships without a crates.io version bump is -invisible to it. It will not catch a yanked crate, and it will not catch a -vulnerability in a version that has not changed. Watch - and yourself, and -treat a Tor security advisory as an instruction to bump **now**, ahead of any -issue the watcher files. - -## Procedure - -1. Read the upstream release notes (Arti tags: ) - and the CHANGELOG for breaking API changes. Check the new MSRV. -2. Branch from `main`; bump all four requirements in `[dependencies]` of - `Cargo.toml` together, and `rust-version` if the floor moved. -3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is - committed): - ``` - cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat - git diff --stat Cargo.lock - ``` - Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate - moving alone is a sign the set is not actually lockstep — stop and look. -4. Build and run the offline suite: - ``` - cargo test --locked - cargo clippy --locked --all-targets -- -D warnings - ``` -5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish - path is slow and its circuit timeouts misbehave on hidden-service circuits, - and an upstream fix or behaviour change can make any of them wrong: - - | constant | why | guard | - |---|---|---| - | `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` | - | `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` | - | `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` | - | `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` | - - Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure - the rend handler is spawned *before* the probe wait, or the probe cannot - succeed at all. -6. Run the live two-node test on a networked machine. This is the only test that - proves the hidden service actually publishes and that a second node can - reach it: - ``` - cargo test --locked --test tor_hs -- --ignored --nocapture - ``` - It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant` - covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir - descriptor upload, not a hang), probe-connect against a live HS, a byte pipe - in both directions, restart, and the dormant/offline path. -7. Confirm the fail-closed path by hand if the publish wait changed at all: - with the write timeout still 360s, a peer whose onion is down must fail the - send. There is no outbox in v1 — the message must not be silently queued. -8. Rebuild the Android target — Arti's TLS backends are non-additive, and this - is the build that exercises the `rustls` feature: - ``` - scripts/build-android-local.sh - ``` -9. Verify the ciphertext claim still holds after the bump: send a message - between the two nodes, then - ``` - grep -r "" - ``` - must find nothing. The bodies live in sqlite as ciphertext, and nothing about - the plaintext should appear in Arti's state directory. -10. Open a PR against `main` describing: crates bumped, MSRV, the live-test - output, and anything upstream changed that touches `src/hs.rs`. Do not push - `main`; releases are minted by `.forgejo/workflows/release.yml` from a merge. - -## Rolling back - -Revert the version bump and the lockfile stanza together, re-run step 3's -`cargo update` only if the revert leaves the lockfile inconsistent, and re-run -`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and -`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the -intent. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index d0baa0a..9773e46 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -16,41 +16,11 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only `F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1. -## Your store is encrypted +## Message bodies are encrypted at rest; keys are not -The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). -A 32-byte key is derived from the store passphrase with Argon2id (same params as -identity backup) over a per-install 16-byte salt in `store_salt`, and handed to -SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it. -The key is the first statement after open, so the file header, schema, identity -secret key, friend public keys, locators, profiles and payment rows are all -ciphertext on disk. There is no `identity_sk`-on-disk problem to work around -because `identity_sk` is inside the encrypted file. A wrong or empty passphrase -fails closed before any write; an encrypted store whose `store_salt` is missing -refuses to open instead of guessing. +Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in the `messages.plaintext` column) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`. Swapping ciphertext between rows fails closed. A random 32-byte data key is wrapped with Argon2id (same params as identity backup) from a non-empty passphrase. Salt + wrapped key live in `store_meta`. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD. -v0.2.1 installs have a plaintext db. The first open with the right passphrase -upgrades it in place (`ATTACH … KEY` + `sqlcipher_export` after a WAL -checkpoint), and swaps the file in only after the new file opens, passes -`integrity_check` and unwraps `store_meta`. A wrong passphrase leaves the -plaintext file untouched. The `store_salt` file is not secret (a salt never is). - -Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || -ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || -0x00 || row_id_le64`, plus a random 32-byte data key wrapped with Argon2id from -the same passphrase (`store_meta`). Whole-db encryption does not stop someone who -can write the file from moving one row's ciphertext into another row; the AAD -does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not -open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` -never falls back to empty AAD. - -At-rest encryption is not a defense against a live compromise: while OnionWire -runs, the passphrase, the db key and decrypted bodies are in process memory, and -SQLCipher's page cache holds decrypted pages. It also does not stop an attacker -who has your passphrase. `/wipe` deletes chat and payments history (overwrite -message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a -forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data -dir (new identity); same disk caveat. +Identity secret key, friend public keys, and locators remain plaintext in the same db. The message key is not wrapped with `identity_sk` (that key is already on disk). A seized laptop still yields who you talk to and your identity unless you add OS/FDE. sqlcipher is out of v1. `/wipe` deletes chat and payments history (overwrite message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data dir (new identity); same disk caveat. ## Fail closed @@ -96,4 +66,4 @@ the peer already knows the plaintext they sent. ## Out of v1 Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, -A/V. +sqlcipher, A/V. diff --git a/scripts/arti-watch.py b/scripts/arti-watch.py deleted file mode 100644 index c7de9ab..0000000 --- a/scripts/arti-watch.py +++ /dev/null @@ -1,279 +0,0 @@ -#!/usr/bin/env python3 -"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins. - -Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on -the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency -it reads the version requirement in Cargo.toml, asks crates.io for the newest -published versions, and — when the major.minor moved — files ONE Forgejo issue. -The issue title carries the compared pair, e.g. - - Arti upstream: tor-hsservice 0.46 -> 0.47 - -Dedupe is on that title across all issues (open and closed), so a second run is -a no-op: no duplicate issue, no repeated comment. Nothing here bumps a -dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md. - -What this does NOT cover, by design: - * It does not subscribe to Tor Project security announcements. A fix that - ships without a crates.io version bump is invisible to this script. - * It will not catch a yanked crate, and it will not catch a vulnerability in - a version that has not changed. crates.io `max_stable_version` already - ignores yanks, so a yank alone produces no alert. - Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself. - -Usage: - FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \ - scripts/arti-watch.py --cargo-toml Cargo.toml - scripts/arti-watch.py --dry-run # no API writes, no token - scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45 -""" - -from __future__ import annotations - -import argparse -import json -import os -import re -import subprocess -import sys -from dataclasses import dataclass - -CRATES_API = "https://crates.io/api/v1/crates/{name}" -# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in -# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own. -USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)" -WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$") -# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch. -SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$") - - -def log(msg: str) -> None: - print(msg, flush=True) - - -class HardFail(SystemExit): - def __init__(self, msg: str) -> None: - super().__init__(2) - self.msg = msg - - -def curl_json(url, token=None, method="GET", body=None): - """curl a JSON endpoint. Returns (http_status, parsed_body_or_None). - - curl rather than urllib: the Cloudflare front door 403s a python-urllib - User-Agent, and curl's --retry covers transient 5xx. - """ - cmd = [ - "curl", "-sS", "--http1.1", - "--retry", "5", "--retry-all-errors", "--retry-delay", "3", - "--connect-timeout", "20", "--max-time", "60", - "-H", f"User-Agent: {USER_AGENT}", - "-H", "Accept: application/json", - ] - if token: - cmd += ["-H", f"Authorization: Bearer {token}"] - if body is not None: - cmd += ["-H", "Content-Type: application/json", - "-X", method, "--data-binary", json.dumps(body)] - cmd += ["-w", "\n%{http_code}", url] - proc = subprocess.run(cmd, capture_output=True, text=True, check=False) - if proc.returncode != 0: - raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}") - raw, _, code = proc.stdout.rpartition("\n") - try: - parsed = json.loads(raw) if raw.strip() else None - except json.JSONDecodeError: - parsed = None - return int(code or 0), parsed - - -def ver(text: str): - """('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise - version format upstream is loud rather than silently 'not an upgrade'.""" - m = SEMVER.match(text.strip()) - if not m: - raise HardFail(f"cannot parse version {text!r}") - return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)) - - -def parse_pins(cargo_toml: str): - """{crate: version_requirement} for the [dependencies] table only.""" - pins: dict[str, str] = {} - section = "" - for line in cargo_toml.splitlines(): - stripped = line.strip() - if stripped.startswith("["): - section = stripped.strip("[]").strip() - continue - if section != "dependencies" or not stripped or stripped.startswith("#"): - continue - m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped) - if not m: - continue - name, rest = m.group(1), m.group(2).split("#", 1)[0].strip() - if not WATCHED.match(name): - continue - vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest) - if vm: - pins[name] = vm.group(1) - return pins - - -def crates_io(name: str): - """(stable, newest) version strings for a crate, as crates.io reports them.""" - status, data = curl_json(CRATES_API.format(name=name)) - if status != 200 or not isinstance(data, dict) or "crate" not in data: - raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})") - crate = data["crate"] - return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"] - - -@dataclass -class Row: - name: str - pin: str - pin_triple: tuple - stable: str - newest: str - source: str # "Cargo.toml" or "simulate-pin" - - @property - def pin_minor(self) -> str: - return f"{self.pin_triple[0]}.{self.pin_triple[1]}" - - @property - def upgrade(self) -> bool: - stable = ver(self.stable) - return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1]) - - -def issue_title(row: Row) -> str: - stable = ver(row.stable) - return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}" - - -def issue_body(row: Row) -> str: - if row.source == "Cargo.toml": - lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**." - else: - lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, " - f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came " - f"from a `workflow_dispatch` test run — the repository pin has not changed.") - return f"""{lead} - -| | | -|---|---| -| crate | `{row.name}` | -| pinned requirement | `"{row.pin}"` | -| pin source | {row.source} | -| newest stable upstream | `{row.stable}` | -| newest upstream (incl. pre-release) | `{row.newest}` | -| crates.io | https://crates.io/crates/{row.name} | -| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases | - -Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole -`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do -not bump this one alone. - -Procedure, toolchain floor, and the tests a bump must pass: -[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor -is rustc 1.91+ (Arti 0.46); a bump may raise it. - -The watcher does **not** subscribe to Tor Project security announcements, and it -cannot see a yanked crate or a vulnerability that ships without a version bump. -""" - - -def existing_titles(repo_api: str, token: str) -> dict: - """{title: issue_number} over every issue, open and closed, paginated.""" - seen: dict[str, int] = {} - page = 1 - while True: - url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}" - status, data = curl_json(url, token) - if status != 200 or not isinstance(data, list): - raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})") - for item in data: - seen[item["title"]] = item["number"] - if len(data) < 50: - return seen - page += 1 - - -def main() -> int: - ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) - ap.add_argument("--cargo-toml", default="Cargo.toml") - ap.add_argument("--dry-run", action="store_true", - help="compare and log only; file no issue and need no token") - ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION", - help="pretend CRATE is pinned at VERSION (test the alert path " - "against real crates.io data without waiting for upstream)") - args = ap.parse_args() - - with open(args.cargo_toml, encoding="utf-8") as fh: - pins = parse_pins(fh.read()) - if not pins: - raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}") - - overrides = {} - for pair in args.simulate_pin: - name, _, version = pair.partition("=") - name, version = name.strip(), version.strip() - if name not in pins or not version: - raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}") - overrides[name] = version - - rows = [] - for name in sorted(pins): - source = "Cargo.toml" - pin = pins[name] - if name in overrides: - pin, source = overrides[name], "simulate-pin" - pin_triple = ver(pin) - stable, newest = crates_io(name) - rows.append(Row(name, pin, pin_triple, stable, newest, source)) - - log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):") - for row in rows: - log(f" {row.name}: pinned={row.pin} (from {row.source}) " - f"upstream_stable={row.stable} upstream_newest={row.newest} " - f"upgrade={'yes' if row.upgrade else 'no'}") - - todo = [row for row in rows if row.upgrade] - if not todo: - log("no upgrade available: every pin already covers the newest upstream release") - return 0 - - if args.dry_run: - for row in todo: - log(f"dry-run: would file issue {issue_title(row)!r}") - return 0 - - repo_api = os.environ.get("REPO_API", "").rstrip("/") - token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split()) - if not repo_api or not token: - raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run") - - titles = existing_titles(repo_api, token) - filed = 0 - for row in todo: - title = issue_title(row) - if title in titles: - log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one") - continue - status, created = curl_json(f"{repo_api}/issues", token, "POST", - {"title": title, "body": issue_body(row)}) - if status != 201 or not isinstance(created, dict): - raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})") - filed += 1 - log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})") - log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked") - return 0 - - -if __name__ == "__main__": - try: - sys.exit(main()) - except HardFail as exc: - log(f"error: {exc.msg}") - sys.exit(exc.code) diff --git a/src/store.rs b/src/store.rs index b3a9f89..1be94f3 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,5 +1,4 @@ use std::fs; -use std::io::Read; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -120,7 +119,7 @@ impl Store { mkdir_700(&home.join("arti"))?; mkdir_700(&home.join("cache"))?; let db_path = home.join("onionwire.db"); - let conn = open_store_db(home, &db_path, passphrase)?; + let conn = Connection::open(&db_path)?; let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?; if !journal.eq_ignore_ascii_case("wal") { return Err(Error(format!("journal_mode WAL failed: {journal}"))); @@ -816,187 +815,6 @@ fn gen_prekey() -> (Vec, Vec) { (sk.to_bytes().to_vec(), pk.to_bytes().to_vec()) } -/// Per-install KDF salt for the whole-database key. Not secret (a salt never -/// is); kept in the data dir so the db key never has to live inside the db it -/// opens. -const SALT_FILE: &str = "store_salt"; -const SQLITE_HEADER: &[u8] = b"SQLite format 3\0"; - -enum DbState { - Missing, - Empty, - Plaintext, - Encrypted, -} - -fn db_state(path: &Path) -> Result { - let meta = match fs::metadata(path) { - Ok(m) => m, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing), - Err(e) => return Err(e.into()), - }; - if meta.len() == 0 { - return Ok(DbState::Empty); - } - let mut head = [0u8; 16]; - let mut f = fs::File::open(path)?; - match f.read_exact(&mut head) { - Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext), - Ok(()) => Ok(DbState::Encrypted), - Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted), - Err(e) => Err(e.into()), - } -} - -fn read_salt(path: &Path) -> Result> { - match fs::read(path) { - Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))), - Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e.into()), - } -} - -fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> { - fs::write(path, salt)?; - let mut perms = fs::metadata(path)?.permissions(); - perms.set_mode(0o600); - fs::set_permissions(path, perms)?; - Ok(()) -} - -fn random_salt() -> [u8; 16] { - let mut salt = [0u8; 16]; - OsRng.fill_bytes(&mut salt); - salt -} - -/// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext -/// file in place. Any failure before the swap leaves the old file untouched. -fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result { - let salt_path = home.join(SALT_FILE); - let mut salt = read_salt(&salt_path)?; - match db_state(db_path)? { - DbState::Plaintext => { - let conn = Connection::open(db_path)?; - let ok = wrapped_key_opens(&conn, passphrase)?; - drop(conn); - if !ok { - return Err(Error("wrong passphrase".into())); - } - let s = salt.unwrap_or_else(random_salt); - let key = crate::backup::kdf(passphrase, &s)?; - write_salt(&salt_path, &s)?; - migrate_plaintext_to_encrypted(db_path, &key, passphrase)?; - salt = Some(s); - } - DbState::Missing | DbState::Empty => { - if salt.is_none() { - let s = random_salt(); - write_salt(&salt_path, &s)?; - salt = Some(s); - } - } - DbState::Encrypted => {} - } - let Some(salt) = salt else { - return Err(Error(format!( - "{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \ - your backup, or restore the db from backup and re-import" - ))); - }; - let key = crate::backup::kdf(passphrase, &salt)?; - open_keyed(db_path, &key) -} - -/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is -/// the key, with no second KDF pass over it. -fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result { - let conn = Connection::open(db_path)?; - conn.execute_batch(&pragma_key(key))?; - // A rejected key otherwise logs SQLCipher's internal "hmac check failed" - // at ERROR to stderr. A wrong passphrase is a normal user error here. - let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE"); - // Force a read so a wrong key fails here, not on the first later query. - conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| { - r.get::<_, i64>(0) - }) - .map_err(|_| Error("wrong passphrase or corrupt store".into()))?; - Ok(conn) -} - -fn pragma_key(key: &[u8; 32]) -> String { - format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key)) -} - -/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh -/// store) accepts any passphrase, matching the v0.2.1 behaviour. -fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result { - let row: Option<(Vec, Vec)> = conn - .query_row( - "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", - [], - |r| Ok((r.get(0)?, r.get(1)?)), - ) - .optional()?; - let Some((salt, wrapped)) = row else { - return Ok(true); - }; - let wrap_key = crate::backup::kdf(passphrase, &salt)?; - Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok()) -} - -/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in. -/// The source file is only replaced after the new file opens, passes -/// `integrity_check` and unlocks with this passphrase. -fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> { - let mut tmp_name = db_path.as_os_str().to_owned(); - tmp_name.push(".migrating"); - let tmp = PathBuf::from(tmp_name); - let _ = fs::remove_file(&tmp); - let mode = fs::metadata(db_path)?.permissions().mode() & 0o777; - - { - // Fold the WAL in so the export sees every committed row. - let conn = Connection::open(db_path)?; - let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); - let target = tmp.to_string_lossy().replace('\'', "''"); - conn.execute_batch(&format!( - "ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";", - hex = fingerprint(key) - ))?; - conn.execute_batch("SELECT sqlcipher_export('enc');")?; - conn.execute_batch("DETACH DATABASE enc;")?; - } - - let verified = (|| -> Result<()> { - let conn = open_keyed(&tmp, key)?; - let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; - if check != "ok" { - return Err(Error(format!("migration integrity_check: {check}"))); - } - if !wrapped_key_opens(&conn, passphrase)? { - return Err(Error("migrated store failed to unlock".into())); - } - Ok(()) - })(); - if let Err(e) = verified { - let _ = fs::remove_file(&tmp); - return Err(e); - } - - fs::rename(&tmp, db_path)?; - let mut perms = fs::metadata(db_path)?.permissions(); - perms.set_mode(mode); - fs::set_permissions(db_path, perms)?; - for suffix in ["-wal", "-shm"] { - let mut stale = db_path.as_os_str().to_owned(); - stale.push(suffix); - let _ = fs::remove_file(PathBuf::from(stale)); - } - Ok(()) -} - fn home_dir() -> Result { if let Some(p) = std::env::var_os("ONIONWIRE_HOME") { return Ok(PathBuf::from(p)); @@ -1209,211 +1027,6 @@ mod at_rest { } } - /// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with - /// the identity row in the clear, a `store_meta` row holding the - /// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to - /// their row AAD. Pin it here so the migration test cannot drift with the - /// production schema. - const LEGACY_SCHEMA: &str = " - CREATE TABLE friends ( - id INTEGER PRIMARY KEY, - pubkey BLOB NOT NULL UNIQUE, - fingerprint TEXT NOT NULL, - petname TEXT, - onion TEXT NOT NULL, - onion_updated_at INTEGER NOT NULL, - added_at INTEGER NOT NULL, - last_connect_ok INTEGER NOT NULL DEFAULT 1, - prekey BLOB NOT NULL DEFAULT x'' - ); - CREATE TABLE messages ( - id INTEGER PRIMARY KEY, - friend_id INTEGER NOT NULL REFERENCES friends(id), - dir TEXT NOT NULL CHECK(dir IN ('in','out')), - plaintext BLOB NOT NULL, - created_at INTEGER NOT NULL - ); - CREATE TABLE self ( - id INTEGER PRIMARY KEY CHECK (id = 1), - identity_sk BLOB NOT NULL, - identity_pk BLOB NOT NULL, - onion TEXT NOT NULL, - onion_rotated_at INTEGER NOT NULL, - prekey_sk BLOB NOT NULL, - prekey_pk BLOB NOT NULL, - hs_nickname TEXT NOT NULL DEFAULT 'ow0' - ); - CREATE TABLE self_profile ( - id INTEGER PRIMARY KEY CHECK (id = 1), - display_name TEXT NOT NULL DEFAULT '', - bio TEXT NOT NULL DEFAULT '', - xmr_addr TEXT NOT NULL DEFAULT '', - updated_at INTEGER NOT NULL DEFAULT 0 - ); - CREATE TABLE friend_profiles ( - pubkey BLOB PRIMARY KEY, - display_name TEXT NOT NULL, - bio TEXT NOT NULL, - xmr_addr TEXT NOT NULL DEFAULT '', - updated_at INTEGER NOT NULL - ); - CREATE TABLE store_meta ( - id INTEGER PRIMARY KEY CHECK (id = 1), - kdf_salt BLOB NOT NULL, - wrapped_key BLOB NOT NULL - ); - CREATE TABLE payments ( - id INTEGER PRIMARY KEY, - friend_id INTEGER NOT NULL REFERENCES friends(id), - dir TEXT NOT NULL CHECK(dir IN ('in','out')), - kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')), - amount_atomic TEXT NOT NULL, - address TEXT NOT NULL, - memo TEXT NOT NULL DEFAULT '', - txid TEXT, - verified INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL - ); - INSERT OR IGNORE INTO self_profile (id) VALUES (1); - "; - - const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32]; - const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32]; - - /// Writes a v0.2.1 store at `db_path` with no encryption at all. - fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) { - let conn = Connection::open(db_path).unwrap(); - conn.execute_batch(LEGACY_SCHEMA).unwrap(); - conn.execute( - "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) - VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')", - params![ - LEGACY_IDENTITY_SK.to_vec(), - vec![0x22u8; 32], - vec![0x33u8; 32], - vec![0x44u8; 32] - ], - ) - .unwrap(); - conn.execute( - "INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey) - VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')", - params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)], - ) - .unwrap(); - let mut salt = [0u8; 16]; - OsRng.fill_bytes(&mut salt); - let mut data_key = [0u8; 32]; - OsRng.fill_bytes(&mut data_key); - let wrap = crate::backup::kdf(passphrase, &salt).unwrap(); - let wrapped = crate::backup::aead_encrypt(&wrap, &data_key, b"").unwrap(); - conn.execute( - "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", - params![salt.as_slice(), wrapped], - ) - .unwrap(); - for (dir, body) in [ - ("in", "legacy-body-xyz"), - ("out", "legacy-reply-xyz"), - ] { - conn.execute( - "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)", - params![dir], - ) - .unwrap(); - let id = conn.last_insert_rowid(); - let blob = crate::backup::aead_encrypt( - &data_key, - body.as_bytes(), - &message_aad(1, dir, id), - ) - .unwrap(); - conn.execute( - "UPDATE messages SET plaintext = ?1 WHERE id = ?2", - params![blob, id], - ) - .unwrap(); - } - conn.close().unwrap(); - } - - fn file_has(path: &Path, needle: &[u8]) -> bool { - let Ok(bytes) = std::fs::read(path) else { - return false; - }; - bytes.windows(needle.len()).any(|w| w == needle) - } - - #[test] - fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() { - let dir = tempfile::tempdir().unwrap(); - let db_path = dir.path().join("onionwire.db"); - write_legacy_plaintext_store(&db_path, "legacy-pass"); - let raw = std::fs::read(&db_path).unwrap(); - assert!( - raw.starts_with(b"SQLite format 3\0"), - "fixture must be a plaintext sqlite file" - ); - - let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade"); - assert_eq!(store.self_identity().unwrap().identity_sk, LEGACY_IDENTITY_SK); - let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap(); - assert_eq!(msgs.len(), 2, "history must survive the upgrade"); - assert_eq!(msgs[0].plaintext, b"legacy-body-xyz"); - assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz"); - assert_eq!( - store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion, - "legacy-friend.onion" - ); - drop(store); - - let enc = std::fs::read(&db_path).unwrap(); - assert!( - !enc.starts_with(b"SQLite format 3\0"), - "db header must be encrypted after the in-place upgrade" - ); - for (needle, what) in [ - (b"legacy-body-xyz".to_vec(), "message body"), - (fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"), - (LEGACY_IDENTITY_SK.to_vec(), "identity secret"), - (b"legacy-friend.onion".to_vec(), "locator"), - ] { - assert!( - !file_has(&db_path, &needle), - "upgraded db still contains the {what}" - ); - } - - let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen"); - assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2); - } - - #[test] - fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() { - let dir = tempfile::tempdir().unwrap(); - let db_path = dir.path().join("onionwire.db"); - write_legacy_plaintext_store(&db_path, "legacy-pass"); - let before = std::fs::read(&db_path).unwrap(); - - let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") { - Ok(_) => panic!("wrong passphrase must not open a legacy store"), - Err(e) => e, - }; - assert!( - err.to_string().to_ascii_lowercase().contains("passphrase"), - "got {err}" - ); - assert_eq!( - std::fs::read(&db_path).unwrap(), - before, - "a failed legacy upgrade must not modify the plaintext db" - ); - assert!( - !dir.path().join("store_salt").exists(), - "a failed legacy upgrade must not leave a salt file behind" - ); - } - #[test] fn first_unlock_reencrypts_legacy_plaintext_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/tests/store.rs b/tests/store.rs index 37a6807..7bc688a 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -233,121 +233,6 @@ fn append_message_db_file_does_not_contain_plaintext() { ); } -fn hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -fn db_files(home: &Path) -> Vec<(String, Vec)> { - let mut out = Vec::new(); - for ent in fs::read_dir(home).expect("read_dir").flatten() { - let name = ent.file_name().to_string_lossy().to_string(); - if !name.starts_with("onionwire.db") { - continue; - } - out.push((name, fs::read(ent.path()).expect("read db file"))); - } - out.sort(); - out -} - -fn store_contains(home: &Path, needle: &[u8]) -> bool { - db_files(home) - .iter() - .any(|(_, bytes)| bytes.windows(needle.len()).any(|w| w == needle)) -} - -#[test] -fn whole_store_file_is_encrypted_at_rest() { - let dir = tempfile::tempdir().expect("tempdir"); - let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open"); - let me = store.self_identity().unwrap(); - store - .upsert_friend(&pk(7), "friend.onion", Some("alice")) - .unwrap(); - store - .append_message(&pk(7), "out", b"body-at-rest-xyz") - .unwrap(); - store - .append_message(&pk(7), "in", b"reply-at-rest-xyz") - .unwrap(); - drop(store); - - for (needle, what) in [ - (b"body-at-rest-xyz".to_vec(), "chat body"), - (b"reply-at-rest-xyz".to_vec(), "inbound chat body"), - (hex(&pk(7)).into_bytes(), "friend pubkey hex"), - (b"friend.onion".to_vec(), "friend locator"), - (me.identity_sk.clone(), "identity secret key"), - ] { - assert!( - !store_contains(dir.path(), &needle), - "onionwire.db* still contains the {what}" - ); - } -} - -#[test] -fn wrong_passphrase_touches_nothing_and_leaves_store_readable() { - let dir = tempfile::tempdir().expect("tempdir"); - let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("open"); - store.upsert_friend(&pk(1), "b.onion", None).unwrap(); - store - .append_message(&pk(1), "in", b"secret-chat-body") - .unwrap(); - drop(store); - let before = db_files(dir.path()); - assert!(!before.is_empty(), "expected store files on disk"); - - let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") { - Ok(_) => panic!("wrong passphrase should fail"), - Err(e) => e, - }; - let msg = err.to_string().to_ascii_lowercase(); - assert!( - msg.contains("passphrase") || msg.contains("decrypt") || msg.contains("wrong"), - "got {err}" - ); - assert_eq!( - db_files(dir.path()), - before, - "a failed unlock must not modify the store files" - ); - - let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("reopen"); - assert_eq!( - store.list_messages(&pk(1)).unwrap()[0].plaintext, - b"secret-chat-body" - ); -} - -#[test] -fn encrypted_store_without_salt_file_refuses_to_guess() { - let dir = tempfile::tempdir().expect("tempdir"); - let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open"); - store.upsert_friend(&pk(1), "b.onion", None).unwrap(); - let me = store.self_identity().unwrap(); - drop(store); - - fs::remove_file(dir.path().join("store_salt")).expect("remove salt"); - let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") { - Ok(_) => panic!("an encrypted store without its salt must not open"), - Err(e) => e, - }; - assert!(err.to_string().contains("store_salt"), "got {err}"); - - // The salt is only a salt: putting it back restores access, no data lost. - fs::write(dir.path().join("store_salt"), [0u8; 16]).unwrap(); - let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") { - Ok(_) => panic!("a wrong salt must not silently open the store"), - Err(e) => e, - }; - assert!( - err.to_string().to_ascii_lowercase().contains("passphrase"), - "a wrong salt must not silently open the store: {err}" - ); - assert_eq!(me.identity_sk.len(), 32); -} - #[test] fn wrong_passphrase_cannot_open_or_list() { let dir = tempfile::tempdir().expect("tempdir");