diff --git a/.forgejo/workflows/android-release.yml b/.forgejo/workflows/android-release.yml index 6de3ce7..ce98027 100644 --- a/.forgejo/workflows/android-release.yml +++ b/.forgejo/workflows/android-release.yml @@ -7,6 +7,10 @@ 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. @@ -67,6 +71,11 @@ 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 @@ -348,31 +357,75 @@ 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: ${{ steps.version.outputs.tag }} - VERSION: ${{ steps.version.outputs.version }} + TAG: ${{ needs.android.outputs.tag }} + VERSION: ${{ needs.android.outputs.version }} run: | set -euo pipefail - cd "${GITHUB_WORKSPACE}" : "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}" - apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk" - aar="dist/onionwire-sdk-$VERSION.aar" + 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" 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 @@ -384,39 +437,18 @@ 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" - 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" + 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" diff --git a/.forgejo/workflows/arti-watch.yml b/.forgejo/workflows/arti-watch.yml new file mode 100644 index 0000000..10a0e5f --- /dev/null +++ b/.forgejo/workflows/arti-watch.yml @@ -0,0 +1,72 @@ +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 1f99c80..dc0a370 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2295,6 +2295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -2653,6 +2654,7 @@ dependencies = [ "tor-rtcompat", "tracing-subscriber", "x25519-dalek", + "zeroize", ] [[package]] @@ -2692,6 +2694,15 @@ 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" @@ -2700,6 +2711,7 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" dependencies = [ "cc", "libc", + "openssl-src", "pkg-config", "vcpkg", ] diff --git a/Cargo.toml b/Cargo.toml index 7285691..68a965f 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"] } +rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] } tor-cell = "0.46" tor-hsservice = "0.46" @@ -47,6 +47,7 @@ sha3 = "0.10" sha2 = "0.10" md-5 = "0.10" rpassword = "7" +zeroize = { version = "1", features = ["derive"] } [dev-dependencies] tempfile = "3" diff --git a/README.md b/README.md index fc2f559..82aeb2c 100644 --- a/README.md +++ b/README.md @@ -245,19 +245,26 @@ 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. Both are built on a host with -the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK: +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. ```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.3.0 scripts/build-android-local.sh # + upload to that release +PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release ``` -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 +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 [`android/README.md`](android/README.md). ## Releases (maintainers) diff --git a/android/README.md b/android/README.md index ac86336..31d3980 100644 --- a/android/README.md +++ b/android/README.md @@ -94,6 +94,49 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped message key *and* the plaintext identity keys to Google Drive. Chat bodies are encrypted at rest; identity keys are not — that is the locked v1 posture. +### The store passphrase at rest + +Typing the passphrase on every launch is no longer required. On first unlock +the passphrase can be remembered (checkbox, on by default), and it is then +stored as an AES-256-GCM blob: + +* the wrapping key is generated inside the **Android Keystore** under alias + `onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` — + deliberately **not** biometric-gated, because a fingerprint prompt would turn + "the node opens or tells you why it did not" into "the node is unusable"; +* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by + `FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary + TEE-backed or software Keystore key when the chip refuses AES-256 + (`StrongBoxUnavailableException is a ProviderException`). The fallback is + reported, not hidden: the lock screen prints what `KeyInfo` actually said, + and a software key is labelled **NOT hardware-backed**; +* only ciphertext + IV reach disk, at + `filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of + magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`, + no plaintext in logs, and the typed `CharArray` is zeroed as soon as the + unlock call returns. The text field is a plain `remember`, so the typed + passphrase is never written into saved instance state; +* **Keystore invalidation is a supported path, not a crash.** A factory reset, + an app-data wipe, or a key the platform invalidates leaves a blob that cannot + authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock + screen explains it, and the user types the passphrase again. A failed read + does **not** delete the blob — a transient Keystore failure must not destroy + the only copy; +* `forget` deletes the blob **and** the Keystore key. + +The one plaintext copy this cannot erase is the immutable `String` the UniFFI +binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change +should accept the key (or a `ByteArray`) so the passphrase never becomes a +`String` at all. + +`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM +(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore +provider only exists on a device: + +```bash +./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report +``` + ### Signing Release APKs are signed with a **repo-owned keystore**, not the debug key. @@ -153,5 +196,8 @@ android/ src/main/java/com/siriusdevops/onionwire/ MainActivity.kt # NavHost WireViewModel.kt # owns the single Wire node + crypto/ # Keystore-wrapped store passphrase ui/ # Compose screens (M3) + src/test/ # JVM tests (envelope, store, invite flow) + src/androidTest/ # device-only: AndroidKeyStore ``` diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 0c5f844..f1238bb 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -28,6 +28,7 @@ android { // the offline default and match the first automated tag (v0.1.0 → 100). versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100 versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { abiFilters += onionwireAbis } @@ -129,4 +130,10 @@ dependencies { testImplementation(libs.junit) testImplementation(libs.kotlinx.coroutines.test) + + // Device-only: the AndroidKeyStore provider does not exist in the unit-test + // JVM. These run under `./gradlew :app:connectedDebugAndroidTest`. + androidTestImplementation(libs.junit) + androidTestImplementation(libs.androidx.test.ext.junit) + androidTestImplementation(libs.androidx.test.runner) } diff --git a/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt b/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt new file mode 100644 index 0000000..2763026 --- /dev/null +++ b/android/app/src/androidTest/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipherTest.kt @@ -0,0 +1,150 @@ +package com.siriusdevops.onionwire.crypto + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * The device half of the Keystore story. The unit-test JVM has no + * `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test. + * + * Run on a real device or an emulator: + * + * ./gradlew :app:connectedDebugAndroidTest + * + * and read the `OnionWireKeystore` tag in logcat for the actual + * `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of + * [key_backing_is_reported_and_logged] is to print the truth, not to assert a + * hardware-backed key on hardware that does not have one. + */ +@RunWith(AndroidJUnit4::class) +class KeystorePassphraseCipherTest { + + private val context: Context = + InstrumentationRegistry.getInstrumentation().targetContext + + private val cipher = KeystorePassphraseCipher(context) + + private val passphrase = "correct horse battery staple".toCharArray() + + @After + fun tearDown() { + cipher.deleteKey() + } + + @Test + fun seal_open_round_trips_through_the_android_keystore() { + val blob = cipher.seal(passphrase) + assertTrue( + "envelope is magic + IV + ciphertext + tag", + blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9, + ) + val out = cipher.open(blob) + try { + assertArrayEquals(passphrase, out) + } finally { + StoreSecret.wipe(out) + } + } + + @Test + fun stored_blob_on_a_device_is_not_the_plaintext() { + val dir = File(context.filesDir, "secrets-test") + dir.mkdirs() + val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher) + try { + store.save(passphrase) + + val raw = File(store.path).readBytes() + val needle = String(passphrase).toByteArray(Charsets.UTF_8) + assertFalse( + "the passphrase must not appear in the file", + String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)), + ) + + val loaded = store.load() as StoredPassphraseStore.Load.Loaded + try { + assertArrayEquals(passphrase, loaded.passphrase) + } finally { + StoreSecret.wipe(loaded.passphrase) + } + } finally { + store.forget() + dir.deleteRecursively() + } + } + + @Test + fun key_backing_is_reported_and_logged() { + cipher.seal(passphrase) // force key creation + + val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && + context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE) + val backing = cipher.backing() + + Log.i( + "OnionWireKeystore", + "alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " + + "strongBoxAdvertised=$strongBoxAdvertised " + + "sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}", + ) + + if (strongBoxAdvertised) { + assertTrue( + "StrongBox is advertised but the key did not land in a secure element: $backing", + backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE, + ) + } else { + assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing) + } + } + + @Test + fun open_does_not_require_user_authentication() { + // The card's contract: unlocking must not need a fingerprint. If the + // key had been created with setUserAuthenticationRequired(true), this + // open() would throw UserNotAuthenticatedException. + val out = cipher.open(cipher.seal(passphrase)) + StoreSecret.wipe(out) + assertTrue(cipher.keyPresent()) + } + + @Test + fun deleted_key_reports_unavailable_instead_of_crashing() { + val blob = cipher.seal(passphrase) + cipher.deleteKey() + + assertFalse(cipher.keyPresent()) + try { + cipher.open(blob) + fail("expected SecretUnavailable after the key was deleted") + } catch (e: SecretUnavailable) { + assertTrue(e.message!!.contains("gone")) + } + } + + @Test + fun a_regenerated_key_cannot_open_an_old_blob() { + val blob = cipher.seal(passphrase) + cipher.deleteKey() // a reset that leaves the app's data dir intact + cipher.seal(passphrase) // same alias, brand-new key + + try { + cipher.open(blob) + fail("expected SecretUnavailable for a blob wrapped by the deleted key") + } catch (_: SecretUnavailable) { + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index dee0b05..8319e1b 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -47,10 +47,17 @@ class MainActivity : ComponentActivity() { @Composable private fun AppRoot(vm: WireViewModel = viewModel()) { val phase by vm.phase.collectAsStateWithLifecycle() + val unlock by vm.unlock.collectAsStateWithLifecycle() when (val p = phase) { is Phase.Ready -> ReadyGraph(vm, p) - else -> UnlockScreen(phase = p, onUnlock = vm::unlock) + else -> UnlockScreen( + phase = p, + unlock = unlock, + onUnlock = vm::unlock, + onUnlockStored = vm::unlockStored, + onForgetStored = vm::forgetStoredPassphrase, + ) } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 90cbf32..93bc1ef 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -3,10 +3,16 @@ package com.siriusdevops.onionwire import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import com.siriusdevops.onionwire.crypto.KeyBacking +import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher +import com.siriusdevops.onionwire.crypto.StoreSecret +import com.siriusdevops.onionwire.crypto.StoredPassphraseStore +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo @@ -32,6 +38,23 @@ sealed interface Phase { data class Failed(val message: String) : Phase } +/** + * How the lock screen expects the next unlock to happen. + * + * This is a probe of local state, not a promise: [OneTap] means a blob exists + * *and* decrypted successfully during this process's lifetime. + */ +sealed interface Unlock { + /** + * The passphrase must be typed. [notice] explains why a stored one is not + * being used (key invalidated, blob corrupt, nothing stored yet). + */ + data class TypeIt(val notice: String? = null) : Unlock + + /** A stored, decryptable passphrase exists — one tap. */ + data class OneTap(val backing: KeyBacking) : Unlock +} + /** * Owns the single Wire node for the process. * @@ -43,46 +66,166 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { /** `context.filesDir` — app-private, never external storage. */ private val home: File = File(app.filesDir, "onionwire") + /** + * The Keystore-wrapped passphrase. Two files at most: this blob and the + * KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else + * on disk ever sees the plaintext. + */ + private val secrets: StoredPassphraseStore = StoredPassphraseStore( + File(File(app.filesDir, "secrets"), "store-passphrase.bin"), + KeystorePassphraseCipher(app), + ) + private val _phase = MutableStateFlow(Phase.Locked) val phase: StateFlow = _phase.asStateFlow() + private val _unlock = MutableStateFlow(Unlock.TypeIt()) + val unlock: StateFlow = _unlock.asStateFlow() + private val _friends = MutableStateFlow>(emptyList()) val friends: StateFlow> = _friends.asStateFlow() private var wire: Wire? = null + init { + // Probe on a background dispatcher: this touches the Keystore and does + // a full GCM decrypt. Doing it here means a killed Keystore key is + // reported on the lock screen instead of at the first tap. + refreshUnlockState() + } + /** - * Opens (or on first run, creates) the identity and starts hosting. + * Unlocks with a typed passphrase. Empty fails closed — the SDK maps it + * straight to an error, it is not a "skip" path. * - * An empty passphrase fails closed — the SDK maps it straight to an error, - * it is not a "skip" path. + * [remember] wraps the passphrase with the Keystore key so later launches + * are one tap. It is opt-in in the UI (and on by default there); it is + * never implied by this call. */ - fun unlock(passphrase: String) { + fun unlock(passphrase: String, remember: Boolean = false) { + if (passphrase.isEmpty()) return + openWith(passphrase.toCharArray(), storeAfterwards = remember) + } + + /** + * One-tap unlock from the stored blob. + * + * Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to + * "type it" with the reason on screen. It never crashes and never silently + * unlocks with something else. + */ + fun unlockStored() { if (_phase.value is Phase.Opening) return - _phase.value = Phase.Opening viewModelScope.launch { - try { - val w = openWire(home.absolutePath, passphrase) - wire = w - _phase.value = Phase.Ready( - fingerprint = w.fingerprint(), - onion = w.onion(), - sdkVersion = w.version(), - ) - refreshFriends() - } catch (t: Throwable) { - _phase.value = Phase.Failed(t.message ?: t.toString()) + val loaded = withContext(Dispatchers.IO) { secrets.load() } + when (loaded) { + is StoredPassphraseStore.Load.Loaded -> + openWith(loaded.passphrase, storeAfterwards = false) + + StoredPassphraseStore.Load.Absent -> { + _unlock.value = Unlock.TypeIt("No passphrase is stored on this device.") + } + + is StoredPassphraseStore.Load.Unavailable -> { + _unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason)) + } } } } + /** Drops the stored passphrase and its Keystore key. Irreversible. */ + fun forgetStoredPassphrase() { + viewModelScope.launch { + withContext(Dispatchers.IO) { secrets.forget() } + _unlock.value = Unlock.TypeIt( + "Stored passphrase deleted. Type it to open the store again.", + ) + } + } + /** Drops our handle. The onion service stops; nothing is sent after this. */ fun lock() { wire = null _friends.value = emptyList() _phase.value = Phase.Locked + refreshUnlockState() } + private fun refreshUnlockState() { + viewModelScope.launch { + val state = withContext(Dispatchers.IO) { + when (val loaded = secrets.load()) { + is StoredPassphraseStore.Load.Loaded -> { + // We only needed to know it decrypts. Wipe immediately. + StoreSecret.wipe(loaded.passphrase) + Unlock.OneTap(secrets.backing()) + } + + StoredPassphraseStore.Load.Absent -> Unlock.TypeIt() + + is StoredPassphraseStore.Load.Unavailable -> + Unlock.TypeIt(unavailableNotice(loaded.reason)) + } + } + _unlock.value = state + } + } + + /** + * The one path that calls the SDK. + * + * [secret] is wiped in `finally`, including when the Keystore write or the + * SDK call throws. The SDK's UniFFI signature takes a `String`, so one + * immutable copy is unavoidable here — see the PR description for the + * follow-up SDK signature this card cannot make itself. + */ + private fun openWith(secret: CharArray, storeAfterwards: Boolean) { + if (secret.isEmpty() || _phase.value is Phase.Opening) { + StoreSecret.wipe(secret) + return + } + _phase.value = Phase.Opening + viewModelScope.launch { + try { + val w = openWire(home.absolutePath, secret.concatToString()) + wire = w + if (storeAfterwards) store(secret) + _phase.value = Phase.Ready( + fingerprint = w.fingerprint(), + onion = w.onion(), + sdkVersion = w.version(), + ) + refreshFriends() + } catch (t: Throwable) { + _phase.value = Phase.Failed(t.message ?: t.toString()) + } finally { + StoreSecret.wipe(secret) + } + } + } + + private suspend fun store(secret: CharArray) { + val outcome: Result = withContext(Dispatchers.IO) { + try { + secrets.save(secret) + Result.success(secrets.backing()) + } catch (t: Throwable) { + Result.failure(t) + } + } + _unlock.value = outcome.fold( + onSuccess = { Unlock.OneTap(it) }, + onFailure = { + // Unlock succeeded, so this is not fatal — say so plainly + // instead of pretending the passphrase was stored. + Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.") + }, + ) + } + + private fun unavailableNotice(reason: String): String = + "The stored passphrase could not be read — $reason. Type it once to store it again." + private fun requireWire(): Wire = wire ?: error("locked") suspend fun refreshFriends() { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt new file mode 100644 index 0000000..1153139 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/KeystorePassphraseCipher.kt @@ -0,0 +1,139 @@ +package com.siriusdevops.onionwire.crypto + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyInfo +import android.security.keystore.KeyProperties +import java.security.KeyStore +import java.security.ProviderException +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.SecretKeyFactory + +/** + * AES-256-GCM key held by the Android Keystore under [ALIAS]. + * + * The key material is never readable by this process (`SecretKey.encoded` is + * null for AndroidKeyStore keys) — that is the whole point: pulling + * `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the + * ciphertext, not the passphrase. + * + * StrongBox is requested first and falls back to the ordinary TEE-backed (or + * software) Keystore without a crash. The fallback is not silent: call + * [backing] and report what the Keystore actually produced. + * + * `setUserAuthenticationRequired` is deliberately **false**. Requiring a + * fingerprint to unlock the node would turn "fail closed" into "unusable + * unattended", and the SDK's contract is that an unlock either opens the node + * or reports why it did not. + */ +class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher { + + private var cached: SecretKey? = null + + override fun seal(plaintext: CharArray): ByteArray = + StoreSecret.seal(loadOrCreateKey(), plaintext) + + /** + * Never creates a key. A freshly generated key cannot decrypt an old blob, + * and generating one here would turn "the key is gone" into a confusing + * GCM tag failure. The caller needs the real reason to tell the user. + */ + override fun open(blob: ByteArray): CharArray { + val key = cached ?: existingKey() + ?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone") + return StoreSecret.open(key, blob) + } + + override fun keyPresent(): Boolean = (cached ?: existingKey()) != null + + override fun backing(): KeyBacking { + val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN + val info = try { + SecretKeyFactory.getInstance(key.algorithm, PROVIDER) + .getKeySpec(key, KeyInfo::class.java) as KeyInfo + } catch (_: Exception) { + // Some OEM Keystore implementations refuse getKeySpec. Report + // UNKNOWN rather than guessing hardware backing. + return KeyBacking.UNKNOWN + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && + info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX + ) { + return KeyBacking.STRONGBOX + } + // Deprecated in API 31 in favour of securityLevel, but it is the only + // TEE/software answer available on 26–30, and minSdk is 26. + @Suppress("DEPRECATION") + val inSecureHardware = info.isInsideSecureHardware + return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE + } + + override fun deleteKey() { + cached = null + try { + keyStore().deleteEntry(ALIAS) + } catch (_: Exception) { + // Nothing usable to delete. + } + } + + private fun existingKey(): SecretKey? { + cached?.let { return it } + val key = try { + keyStore().getKey(ALIAS, null) as? SecretKey + } catch (_: Exception) { + null + } + cached = key + return key + } + + private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey() + + private fun createKey(): SecretKey { + val strongBoxAdvertised = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && + context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE) + if (strongBoxAdvertised) { + try { + return generate(strongBox = true).also { cached = it } + } catch (_: ProviderException) { + // StrongBoxUnavailableException is a ProviderException: the chip + // exists but its slots are full, or it refuses AES-256. Fall + // through to a normal Keystore key instead of failing unlock. + } + } + return generate(strongBox = false).also { cached = it } + } + + private fun generate(strongBox: Boolean): SecretKey { + val builder = KeyGenParameterSpec.Builder( + ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(StoreSecret.KEY_BITS) + // Our IV comes from Cipher.init, and the Keystore supplies it. + .setRandomizedEncryptionRequired(true) + .setUserAuthenticationRequired(false) + if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + builder.setIsStrongBoxBacked(true) + } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER) + generator.init(builder.build()) + return generator.generateKey() + } + + private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) } + + companion object { + const val PROVIDER = "AndroidKeyStore" + + /** One key per app: the passphrase it wraps is the only secret here. */ + const val ALIAS = "onionwire.store" + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/PassphraseCipher.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/PassphraseCipher.kt new file mode 100644 index 0000000..50cd2b9 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/PassphraseCipher.kt @@ -0,0 +1,49 @@ +package com.siriusdevops.onionwire.crypto + +/** + * Wraps the store passphrase with a key that never leaves the Keystore. + * + * Implementations must not persist the plaintext anywhere, and must not log it. + */ +interface PassphraseCipher { + + /** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */ + fun seal(plaintext: CharArray): ByteArray + + /** + * Decrypts a blob produced by [seal]. + * + * @throws SecretUnavailable when the key is gone, invalidated, or the blob + * does not authenticate. Callers fall back to asking the user to type. + */ + fun open(blob: ByteArray): CharArray + + /** True when a usable key is already in the Keystore. */ + fun keyPresent(): Boolean + + /** + * Where the key actually lives, as reported by the Keystore itself. + * + * This is an observation, not a claim: on a device without a StrongBox or + * TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so. + */ + fun backing(): KeyBacking + + /** Removes the key. The ciphertext becomes permanently undecryptable. */ + fun deleteKey() +} + +/** Result of asking the Keystore where the key lives. */ +enum class KeyBacking { + /** Dedicated security chip (API 28+, Pixel 3-class and up). */ + STRONGBOX, + + /** Key is inside a TEE. Good. */ + HARDWARE, + + /** Keystore software implementation. Passphrase is still not plaintext on disk. */ + SOFTWARE, + + /** No key created yet, or the API could not be queried. Never claim hardware here. */ + UNKNOWN, +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoreSecret.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoreSecret.kt new file mode 100644 index 0000000..89b9e7b --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoreSecret.kt @@ -0,0 +1,130 @@ +package com.siriusdevops.onionwire.crypto + +import java.nio.CharBuffer +import java.nio.charset.StandardCharsets +import java.security.GeneralSecurityException +import java.util.Arrays +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * AES-256-GCM envelope for the store passphrase. + * + * This file is deliberately free of `android.*` imports so the exact + * seal/open code that runs on a device can also run in a plain JVM unit test + * with a JVM-generated AES key. The Android Keystore only supplies the key — + * the framing and the AEAD call are these functions. + * + * Wire format (little of it is secret, all of it is authenticated): + * + * magic "OWSEAL1\n" 8 bytes + * iv length 1 byte (always [IV_BYTES]) + * iv [IV_BYTES] bytes, from the cipher + * ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended) + * + * The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore + * key created with `setRandomizedEncryptionRequired(true)` refuses an + * app-supplied IV, and SunJCE likewise default-generates one. Nothing here + * ever writes the plaintext passphrase to disk. + */ +object StoreSecret { + + /** AES-256 per the card. Keystore key size and this constant must agree. */ + const val KEY_BITS: Int = 256 + + /** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */ + const val IV_BYTES: Int = 12 + + /** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */ + private const val TAG_BITS: Int = 128 + + private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte()) + + private const val TRANSFORMATION = "AES/GCM/NoPadding" + + /** + * Encrypts [plaintext] under [key]. The passphrase is never converted to a + * `String` on this path: the UTF-8 encoder reads the `CharArray` directly. + */ + fun seal(key: SecretKey, plaintext: CharArray): ByteArray { + require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" } + val bytes = utf8(plaintext) + try { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, key) + val iv = cipher.iv + val ct = cipher.doFinal(bytes) + return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out -> + var p = 0 + MAGIC.copyInto(out, p); p += MAGIC.size + out[p] = iv.size.toByte(); p += 1 + iv.copyInto(out, p); p += iv.size + ct.copyInto(out, p) + } + } catch (e: GeneralSecurityException) { + throw SecretUnavailable("could not encrypt the passphrase", e) + } finally { + wipe(bytes) + } + } + + /** + * Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated + * blob, or a failed GCM tag check — never returns partial plaintext. + */ + fun open(key: SecretKey, blob: ByteArray): CharArray { + if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) { + throw SecretUnavailable("stored secret is truncated") + } + for (i in MAGIC.indices) { + if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope") + } + var p = MAGIC.size + val ivLen = blob[p].toInt() and 0xFF + p += 1 + if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen") + if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated") + val iv = blob.copyOfRange(p, p + ivLen) + val ct = blob.copyOfRange(p + ivLen, blob.size) + val plain = try { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv)) + cipher.doFinal(ct) + } catch (e: GeneralSecurityException) { + throw SecretUnavailable("stored secret did not authenticate", e) + } + return try { + decodeUtf8(plain) + } finally { + wipe(plain) + } + } + + /** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */ + fun wipe(bytes: ByteArray) { + Arrays.fill(bytes, 0) + } + + /** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */ + fun wipe(chars: CharArray) { + Arrays.fill(chars, '\u0000') + } + + private fun utf8(chars: CharArray): ByteArray { + val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars)) + return ByteArray(bb.remaining()).also(bb::get) + } + + private fun decodeUtf8(bytes: ByteArray): CharArray { + val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)) + return CharArray(cb.remaining()).also(cb::get) + } +} + +/** + * The passphrase could not be recovered. The caller must fall back to typing + * it — a Keystore key does not survive a factory reset, a lock-screen change + * that invalidates keys, or an app-data wipe. + */ +class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt new file mode 100644 index 0000000..4b88fed --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStore.kt @@ -0,0 +1,91 @@ +package com.siriusdevops.onionwire.crypto + +import java.io.File +import java.io.IOException + +/** + * The only on-disk copy of the passphrase: an AES-GCM blob under + * `context.filesDir`, which is app-private and excluded from backup and + * device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`). + * + * The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag. + * There is no second copy, no SharedPreferences mirror, and nothing outside the + * app's data dir. + */ +class StoredPassphraseStore( + private val file: File, + private val cipher: PassphraseCipher, +) { + + sealed interface Load { + /** Decrypted for this call only. The caller must wipe the array. */ + class Loaded(val passphrase: CharArray) : Load + + /** Nothing stored yet — first run, or the user forgot it. */ + data object Absent : Load + + /** + * Something is stored but cannot be read: the Keystore key is gone or + * invalidated, or the file is corrupt. Fall back to typing. + */ + data class Unavailable(val reason: String) : Load + } + + fun exists(): Boolean = file.isFile && file.length() > 0L + + /** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */ + fun backing(): KeyBacking = cipher.backing() + + /** Path for diagnostics in tests. Never logged with its contents. */ + val path: String get() = file.absolutePath + + /** + * Encrypts and replaces the stored blob. Atomic-ish: written to a sibling + * temp file and renamed, so a crash mid-write cannot leave half a blob. + */ + fun save(passphrase: CharArray) { + require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" } + val blob = cipher.seal(passphrase) + try { + file.parentFile?.mkdirs() + val tmp = File(file.parentFile, file.name + ".tmp") + tmp.writeBytes(blob) + if (!tmp.renameTo(file)) { + file.writeBytes(blob) + tmp.delete() + } + } finally { + StoreSecret.wipe(blob) + } + } + + /** + * Reads and decrypts the blob. The returned array is the caller's to wipe. + * + * A failed decrypt does **not** delete the blob: a transient Keystore + * failure must not silently destroy the user's only copy. Use [forget] to + * drop it deliberately. + */ + fun load(): Load { + if (!exists()) return Load.Absent + val blob = try { + file.readBytes() + } catch (e: IOException) { + return Load.Unavailable("the stored passphrase file could not be read (${e.message})") + } + return try { + Load.Loaded(cipher.open(blob)) + } catch (e: SecretUnavailable) { + Load.Unavailable(e.message ?: "the stored passphrase did not authenticate") + } finally { + StoreSecret.wipe(blob) + } + } + + /** Drops the ciphertext and the Keystore key. Irreversible. */ + fun forget() { + file.delete() + File(file.parentFile, file.name + ".tmp").delete() + cipher.deleteKey() + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt index a7892d2..d762028 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt @@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -11,10 +12,13 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -28,10 +32,38 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import com.siriusdevops.onionwire.Phase +import com.siriusdevops.onionwire.Unlock +import com.siriusdevops.onionwire.crypto.KeyBacking +/** + * Lock screen. + * + * When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the + * Android Keystore key and the user taps once. Otherwise they type it — and + * they land here, with [Unlock.TypeIt.notice] explaining why, whenever the + * stored blob cannot be read (key invalidated, device reset, corrupt file). + * + * The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and + * is cleared as soon as it is handed to the ViewModel: it never survives a + * config change and never gets written to the saved-instance-state bundle. + */ @Composable -fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) { +fun UnlockScreen( + phase: Phase, + unlock: Unlock, + onUnlock: (passphrase: String, remember: Boolean) -> Unit, + onUnlockStored: () -> Unit, + onForgetStored: () -> Unit, +) { var pass by remember { mutableStateOf("") } + var storePassphrase by remember { mutableStateOf(true) } + // Only meaningful under OneTap: reveal the form without giving up the + // stored passphrase. + var typeInstead by remember { mutableStateOf(false) } + + val oneTap = unlock as? Unlock.OneTap + val failed = phase is Phase.Failed + val showForm = oneTap == null || typeInstead || failed Column( modifier = Modifier @@ -64,38 +96,107 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) { } else -> { - Text( - "Passphrase", - style = MaterialTheme.typography.titleSmall, - ) - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = pass, - onValueChange = { pass = it }, - singleLine = true, - visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Password, - imeAction = ImeAction.Done, - ), - label = { Text("wraps the local message key") }, - modifier = Modifier.fillMaxWidth(), - ) - Spacer(Modifier.height(12.dp)) - Text( - "Empty is not a bypass — it fails closed. There is no recovery: " + - "lose this and the stored chat bodies stay unreadable.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(20.dp)) - Button( - onClick = { onUnlock(pass) }, - enabled = pass.isNotEmpty(), - modifier = Modifier.fillMaxWidth(), - ) { Text("Open") } + if (oneTap != null && !failed) { + Text("Passphrase", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + Text( + "Stored on this device, wrapped by an Android Keystore key " + + "(${backingLabel(oneTap.backing)}).", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(20.dp)) + Button( + onClick = onUnlockStored, + modifier = Modifier.fillMaxWidth(), + ) { Text("Unlock") } + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + TextButton(onClick = { typeInstead = true }) { + Text("Type it instead") + } + TextButton(onClick = onForgetStored) { + Text("Forget stored passphrase") + } + } + if (showForm) { + Spacer(Modifier.height(16.dp)) + HorizontalDivider() + Spacer(Modifier.height(16.dp)) + } + } - if (phase is Phase.Failed) { + if (showForm) { + if (unlock is Unlock.TypeIt && unlock.notice != null) { + Text( + unlock.notice, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(16.dp)) + } + + OutlinedTextField( + value = pass, + onValueChange = { pass = it }, + singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Password, + imeAction = ImeAction.Done, + ), + label = { Text("wraps the local message key") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(12.dp)) + Text( + "Empty is not a bypass — it fails closed. There is no recovery: " + + "lose this and the stored chat bodies stay unreadable.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(Modifier.height(4.dp)) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth(), + ) { + Checkbox( + checked = storePassphrase, + onCheckedChange = { storePassphrase = it }, + ) + Text( + "Remember on this device (wrapped by the Android Keystore, " + + "no backup)", + style = MaterialTheme.typography.bodySmall, + ) + } + if (oneTap != null) { + Text( + "Typing and remembering replaces the stored passphrase.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + Spacer(Modifier.height(20.dp)) + Button( + onClick = { + val typed = pass + // Drop the plaintext from Compose state the moment + // it is handed over; the ViewModel wipes its copy. + pass = "" + onUnlock(typed, storePassphrase) + }, + enabled = pass.isNotEmpty(), + modifier = Modifier.fillMaxWidth(), + ) { Text("Open") } + } + + if (failed) { Spacer(Modifier.height(20.dp)) Text( "Failed to start", @@ -128,3 +229,14 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) { ) } } + +/** + * What the Keystore reported, verbatim. Never upgraded into a stronger claim: + * a software key says so. + */ +internal fun backingLabel(backing: KeyBacking): String = when (backing) { + KeyBacking.STRONGBOX -> "StrongBox" + KeyBacking.HARDWARE -> "TEE-backed" + KeyBacking.SOFTWARE -> "software key, NOT hardware-backed" + KeyBacking.UNKNOWN -> "backing not reported by this device" +} diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoreSecretTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoreSecretTest.kt new file mode 100644 index 0000000..3fa7db3 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoreSecretTest.kt @@ -0,0 +1,157 @@ +package com.siriusdevops.onionwire.crypto + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +/** + * Exercises the real envelope code — [StoreSecret] has no `android.*` imports, + * so a JVM AES key stands in for the AndroidKeystore key. + * + * What this does NOT cover (see the PR description): the AndroidKeyStore provider + * itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and + * `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test + * JVM has no such provider. + */ +class StoreSecretTest { + + private fun aesKey(): SecretKey = + KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey() + + private val passphrase = "correct horse battery staple".toCharArray() + + @Test + fun seal_open_round_trips() { + val key = aesKey() + val blob = StoreSecret.seal(key, passphrase) + val out = StoreSecret.open(key, blob) + try { + assertArrayEquals(passphrase, out) + } finally { + StoreSecret.wipe(out) + } + } + + @Test + fun round_trips_non_ascii_and_whitespace() { + val key = aesKey() + val weird = " ünïcödé 🔑 \n\ttab ".toCharArray() + val out = StoreSecret.open(key, StoreSecret.seal(key, weird)) + try { + assertArrayEquals(weird, out) + } finally { + StoreSecret.wipe(out) + } + } + + @Test + fun blob_does_not_contain_the_plaintext() { + val key = aesKey() + val blob = StoreSecret.seal(key, passphrase) + val needle = String(passphrase).toByteArray(Charsets.UTF_8) + assertFalse( + "ciphertext must not contain the passphrase", + blob.containsSubsequence(needle), + ) + assertTrue(blob.size > needle.size) + } + + @Test + fun blob_carries_the_envelope_magic() { + val blob = StoreSecret.seal(aesKey(), passphrase) + assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII)) + // Magic(8) + IV length(1) + IV(12) + tag(16) + assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size) + } + + @Test + fun each_seal_uses_a_fresh_iv() { + val key = aesKey() + val a = StoreSecret.seal(key, passphrase) + val b = StoreSecret.seal(key, passphrase) + assertNotEquals( + "identical ciphertext means the IV was reused", + a.toList(), + b.toList(), + ) + } + + @Test + fun wrong_key_fails_closed() { + val blob = StoreSecret.seal(aesKey(), passphrase) + try { + StoreSecret.open(aesKey(), blob) + fail("expected SecretUnavailable") + } catch (e: SecretUnavailable) { + assertTrue(e.message!!.contains("authenticate")) + } + } + + @Test + fun tampered_ciphertext_fails_the_gcm_tag() { + val key = aesKey() + val blob = StoreSecret.seal(key, passphrase) + blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte() + try { + StoreSecret.open(key, blob) + fail("expected SecretUnavailable") + } catch (_: SecretUnavailable) { + } + } + + @Test + fun truncated_blob_fails_closed() { + val key = aesKey() + val blob = StoreSecret.seal(key, passphrase) + try { + StoreSecret.open(key, blob.copyOfRange(0, 10)) + fail("expected SecretUnavailable") + } catch (_: SecretUnavailable) { + } + } + + @Test + fun garbage_blob_fails_closed() { + try { + StoreSecret.open(aesKey(), "not an envelope".toByteArray()) + fail("expected SecretUnavailable") + } catch (e: SecretUnavailable) { + assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope")) + } + } + + @Test + fun seal_refuses_an_empty_passphrase() { + try { + StoreSecret.seal(aesKey(), CharArray(0)) + fail("expected IllegalArgumentException") + } catch (_: IllegalArgumentException) { + } + } + + @Test + fun wipe_zeroes() { + val bytes = byteArrayOf(1, 2, 3) + StoreSecret.wipe(bytes) + assertArrayEquals(ByteArray(3), bytes) + + val chars = charArrayOf('a', 'b') + StoreSecret.wipe(chars) + assertArrayEquals(CharArray(2), chars) + } + + private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean { + if (needle.isEmpty() || needle.size > size) return false + outer@ for (i in 0..size - needle.size) { + for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer + return true + } + return false + } +} diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStoreTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStoreTest.kt new file mode 100644 index 0000000..a56141d --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/crypto/StoredPassphraseStoreTest.kt @@ -0,0 +1,167 @@ +package com.siriusdevops.onionwire.crypto + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +/** + * File-level behaviour of [StoredPassphraseStore] with the real envelope from + * [StoreSecret] and a JVM AES key standing in for the Keystore key. + * + * The Keystore itself is device-only; what is proven here is that nothing + * plaintext reaches the file, that a lost key degrades instead of crashing, + * and that a lost key does not delete the user's blob. + */ +class StoredPassphraseStoreTest { + + @get:Rule + val tmp = TemporaryFolder() + + private val passphrase = "correct horse battery staple".toCharArray() + + /** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */ + private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher { + var deleted = false + var backingQueried = 0 + + override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext) + + override fun open(blob: ByteArray): CharArray { + if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone") + return StoreSecret.open(key, blob) + } + + override fun keyPresent(): Boolean = !deleted + + override fun backing(): KeyBacking { + backingQueried++ + return KeyBacking.SOFTWARE + } + + override fun deleteKey() { + deleted = true + } + } + + private fun jvmKey(): SecretKey = + KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey() + + private fun store(cipher: PassphraseCipher) = + StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher) + + @Test + fun save_then_load_round_trips() { + val store = store(JvmKeyCipher(jvmKey())) + store.save(passphrase) + + val loaded = store.load() + assertTrue(loaded is StoredPassphraseStore.Load.Loaded) + val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase + try { + assertArrayEquals(passphrase, out) + } finally { + StoreSecret.wipe(out) + } + } + + @Test + fun on_disk_blob_is_not_the_plaintext() { + val store = store(JvmKeyCipher(jvmKey())) + store.save(passphrase) + + val raw = java.io.File(store.path).readBytes() + val needle = String(passphrase).toByteArray(Charsets.UTF_8) + assertFalse( + "the passphrase must not appear in the file", + raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)), + ) + assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20) + assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII)) + } + + @Test + fun no_temp_file_is_left_behind() { + val store = store(JvmKeyCipher(jvmKey())) + store.save(passphrase) + val dir = requireNotNull(java.io.File(store.path).parentFile) + val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") } + assertTrue("temp files left: $leftovers", leftovers.isEmpty()) + } + + @Test + fun save_overwrites_the_previous_blob() { + val store = store(JvmKeyCipher(jvmKey())) + store.save("first".toCharArray()) + store.save("second".toCharArray()) + + val loaded = store.load() as StoredPassphraseStore.Load.Loaded + try { + assertArrayEquals("second".toCharArray(), loaded.passphrase) + } finally { + StoreSecret.wipe(loaded.passphrase) + } + } + + @Test + fun absent_when_nothing_was_ever_stored() { + val store = store(JvmKeyCipher(jvmKey())) + assertFalse(store.exists()) + assertEquals(StoredPassphraseStore.Load.Absent, store.load()) + } + + @Test + fun lost_key_reports_unavailable_and_keeps_the_blob() { + val cipher = JvmKeyCipher(jvmKey()) + val store = store(cipher) + store.save(passphrase) + + cipher.deleteKey() // device reset / key invalidated + + val loaded = store.load() + assertTrue(loaded is StoredPassphraseStore.Load.Unavailable) + assertTrue( + (loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"), + ) + assertTrue("a failed read must not delete the blob", store.exists()) + } + + @Test + fun corrupt_blob_reports_unavailable_instead_of_throwing() { + val store = store(JvmKeyCipher(jvmKey())) + store.save(passphrase) + java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray()) + + val loaded = store.load() + assertTrue(loaded is StoredPassphraseStore.Load.Unavailable) + } + + @Test + fun forget_deletes_the_blob_and_the_key() { + val cipher = JvmKeyCipher(jvmKey()) + val store = store(cipher) + store.save(passphrase) + assertTrue(store.exists()) + + store.forget() + + assertFalse(store.exists()) + assertFalse(cipher.keyPresent()) + assertEquals(StoredPassphraseStore.Load.Absent, store.load()) + } + + @Test + fun backing_is_reported_from_the_cipher() { + val cipher = JvmKeyCipher(jvmKey()) + val store = store(cipher) + store.save(passphrase) + + assertEquals(KeyBacking.SOFTWARE, store.backing()) + assertEquals(1, cipher.backingQueried) + } +} diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 551b081..1ef47c0 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -9,11 +9,15 @@ composeBom = "2025.12.01" jna = "5.19.1" coroutines = "1.11.0" junit = "4.13.2" +androidxTestJunit = "1.3.0" +androidxTestRunner = "1.7.0" [libraries] androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } jna = { module = "net.java.dev.jna:jna", version.ref = "jna" } junit = { module = "junit:junit", version.ref = "junit" } +androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" } kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } diff --git a/docs/ARTI_UPGRADE.md b/docs/ARTI_UPGRADE.md new file mode 100644 index 0000000..bb0ad7b --- /dev/null +++ b/docs/ARTI_UPGRADE.md @@ -0,0 +1,143 @@ +# 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/PROTOCOL.md b/docs/PROTOCOL.md index 6cda19e..e93943f 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -19,7 +19,7 @@ SOCKS proxy.” | Discovery | DHT + bootstrap nodes | Out-of-band invite only | | After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion | | Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator | -| Offline send | Expected (relays / retry) | Fail closed — no outbox | +| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) | | Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers | There is no directory, no name server, no introduction point of our own, and no @@ -51,8 +51,18 @@ not on the wire. 4. File transfer is N independent sessions (one handshake per chunk). There is no multiplexed long-lived stream in v1. -If the onion is down, send fails. No retry queue except the locator-push path, -which retries for 180 seconds and then gives up. +If the onion is down, a **chat** send is persisted to the local outbox and +retried by a background worker with exponential backoff (30s, doubling, capped +at 30 min; 8 attempts, then terminal `Failed`). There is no server and no +store-and-forward relay: each attempt is a fresh handshake straight to +`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on +unlock/foreground, and whenever that peer is heard from (successful handshake or +`connect_onion()`). A protocol failure — signature mismatch, unknown frame, +oversize — is not a transport failure and is never queued. + +File transfer and payment frames stay fail-closed: they are one-shot and are +**not** queued. The locator-push path still retries for 180 seconds and then +gives up. Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10. Excess is dropped before handshake. That is availability, not anonymity. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9773e46..56f44d2 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -16,15 +16,54 @@ 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. -## Message bodies are encrypted at rest; keys are not +## Your store is encrypted -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. +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. -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. +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. ## Fail closed -Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. +Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. + +## Local outbox (chat retry queue) is local, and it re-dials on a schedule + +A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted: + +- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase. +- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure. + +The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever. ## Profile is friend-visible, not a directory @@ -65,5 +104,7 @@ the peer already knows the plaintext they sent. ## Out of v1 -Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, -sqlcipher, A/V. +Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward +relay, multi-device, DHT / name server, A/V. The local retry queue of the +previous section is not an outbox in the XMPP sense: it never leaves the device. + diff --git a/scripts/arti-watch.py b/scripts/arti-watch.py new file mode 100644 index 0000000..c7de9ab --- /dev/null +++ b/scripts/arti-watch.py @@ -0,0 +1,279 @@ +#!/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/backup.rs b/src/backup.rs index b946476..5e6a775 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -4,6 +4,7 @@ use argon2::{Algorithm, Argon2, Params, Version}; use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; use rand::RngCore; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; pub const MAGIC: &[u8] = b"owbak1"; const SALT_LEN: usize = 16; @@ -11,17 +12,31 @@ const NONCE_LEN: usize = 12; const KEY_LEN: usize = 32; const PLAIN_LEN: usize = KEY_LEN * 4; -#[derive(Debug, Clone, PartialEq, Eq)] +/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them. +#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)] pub struct BackupKeys { pub identity_sk: [u8; 32], + #[zeroize(skip)] pub identity_pk: [u8; 32], pub prekey_sk: [u8; 32], + #[zeroize(skip)] pub prekey_pk: [u8; 32], } +impl std::fmt::Debug for BackupKeys { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("BackupKeys") + .field("identity_sk", &"") + .field("identity_pk", &self.identity_pk) + .field("prekey_sk", &"") + .field("prekey_pk", &self.prekey_pk) + .finish() + } +} + impl BackupKeys { - pub fn to_bytes(&self) -> [u8; PLAIN_LEN] { - let mut out = [0u8; PLAIN_LEN]; + pub fn to_bytes(&self) -> Zeroizing<[u8; PLAIN_LEN]> { + let mut out = Zeroizing::new([0u8; PLAIN_LEN]); out[0..32].copy_from_slice(&self.identity_sk); out[32..64].copy_from_slice(&self.identity_pk); out[64..96].copy_from_slice(&self.prekey_sk); @@ -42,7 +57,7 @@ impl BackupKeys { } } -pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> { +pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result, String> { if passphrase.is_empty() { return Err("empty passphrase".into()); } @@ -51,9 +66,9 @@ pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> { } let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?; let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); - let mut key = [0u8; 32]; + let mut key = Zeroizing::new([0u8; 32]); argon - .hash_password_into(passphrase.as_bytes(), salt, &mut key) + .hash_password_into(passphrase.as_bytes(), salt, &mut key[..]) .map_err(|e| e.to_string())?; Ok(key) } @@ -62,13 +77,13 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result, String> { let mut salt = [0u8; SALT_LEN]; rand::rngs::OsRng.fill_bytes(&mut salt); let key = kdf(passphrase, &salt)?; - let cipher = ChaCha20Poly1305::new(Key::from_slice(&key)); + let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..])); let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); if nonce.len() != NONCE_LEN { return Err("nonce length".into()); } let ct = cipher - .encrypt(&nonce, keys.to_bytes().as_ref()) + .encrypt(&nonce, &keys.to_bytes()[..]) .map_err(|_| "encrypt failed".to_string())?; let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len()); out.extend_from_slice(MAGIC); @@ -88,11 +103,13 @@ pub fn open(passphrase: &str, blob: &[u8]) -> Result { let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]); let ct = &blob[nonce_off + NONCE_LEN..]; let key = kdf(passphrase, salt)?; - let cipher = ChaCha20Poly1305::new(Key::from_slice(&key)); - let pt = cipher - .decrypt(nonce, ct) - .map_err(|_| "wrong passphrase or corrupt backup".to_string())?; - BackupKeys::from_bytes(&pt) + let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..])); + let pt = Zeroizing::new( + cipher + .decrypt(nonce, ct) + .map_err(|_| "wrong passphrase or corrupt backup".to_string())?, + ); + BackupKeys::from_bytes(&pt[..]) } pub(crate) fn aead_encrypt( @@ -133,3 +150,45 @@ pub(crate) fn aead_decrypt(key: &[u8; 32], blob: &[u8], aad: &[u8]) -> Result BackupKeys { + BackupKeys { + identity_sk: [tag; 32], + identity_pk: [tag.wrapping_add(1); 32], + prekey_sk: [tag.wrapping_add(2); 32], + prekey_pk: [tag.wrapping_add(3); 32], + } + } + + #[test] + fn derived_wrap_key_is_a_zeroizing_buffer() { + let mut key = kdf("correct horse", &[7u8; 16]).expect("kdf"); + let _: &Zeroizing<[u8; 32]> = &key; + let before = *key; + assert_ne!(before, [0u8; 32]); + key.zeroize(); + assert_eq!(*key, [0u8; 32], "derived key not wiped"); + } + + #[test] + fn backup_plaintext_buffer_is_a_zeroizing_buffer() { + let mut bytes = keys(5).to_bytes(); + let _: &Zeroizing<[u8; PLAIN_LEN]> = &bytes; + assert_eq!(&bytes[..32], &[5u8; 32][..]); + bytes.zeroize(); + assert_eq!(&bytes[..], &[0u8; PLAIN_LEN][..], "backup plaintext kept"); + } + + #[test] + fn backup_keys_debug_redacts_the_secret_halves() { + let dbg = format!("{:?}", keys(0xAB)); + assert!(!dbg.contains("171"), "identity secret in Debug: {dbg}"); + assert!(!dbg.contains("173"), "prekey secret in Debug: {dbg}"); + assert!(dbg.contains(""), "{dbg}"); + assert!(dbg.contains("174"), "public half should stay: {dbg}"); + } +} diff --git a/src/lib.rs b/src/lib.rs index ea6dba2..9d9eb7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod frame; pub mod hs; pub mod loc; pub mod node; +pub mod outbox; pub mod pay; pub mod profile; pub mod qr; diff --git a/src/loc.rs b/src/loc.rs index aa25574..9803f77 100644 --- a/src/loc.rs +++ b/src/loc.rs @@ -23,9 +23,10 @@ pub struct Loc { const PREFIX: &[u8] = b"loc "; pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result { - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + // Same one-shot raw identity-secret copy as `profile::sign`; shared so + // `Zeroize` covers it here too. + let sk_bytes = + crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?; let sk = SigningKey::from_bytes(&sk_bytes); let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec(); Ok(Loc { diff --git a/src/node.rs b/src/node.rs index 97745a2..b7b9fa3 100644 --- a/src/node.rs +++ b/src/node.rs @@ -8,12 +8,14 @@ use futures::StreamExt; use futures::io::{AsyncRead, AsyncWrite}; use tor_cell::relaycell::msg::Connected; use tor_hsservice::{RunningOnionService, handle_rend_requests}; +use zeroize::Zeroizing; use crate::dispatch::{self, Kind}; use crate::file; use crate::frame; use crate::hs::{self, Client, HS_PORT}; use crate::loc; +use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; use crate::profile; use crate::qr; @@ -39,9 +41,18 @@ impl Drop for HsHandle { } } +/// Abort the outbox worker when the node goes away. +struct WorkerHandle(tokio::task::JoinHandle<()>); + +impl Drop for WorkerHandle { + fn drop(&mut self) { + self.0.abort(); + } +} + pub struct Node { home: PathBuf, - store: Mutex, + store: Arc>, client: Client, hs: Mutex>, onion: Mutex, @@ -49,16 +60,20 @@ pub struct Node { wallet: Wallet, incoming_limit: Mutex, inbox: Mutex, + outbox: Arc, + _outbox_worker: WorkerHandle, } impl Node { pub async fn start(home: PathBuf) -> Result, String> { - let pass = std::env::var("ONIONWIRE_STORE_PASSPHRASE") - .map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?; + let pass = Zeroizing::new( + std::env::var("ONIONWIRE_STORE_PASSPHRASE") + .map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?, + ); if pass.is_empty() { return Err("empty passphrase".into()); } - Self::start_with_passphrase(home, &pass).await + Self::start_with_passphrase(home, pass.as_str()).await } pub async fn start_with_passphrase( @@ -79,9 +94,17 @@ impl Node { let (svc, rend) = launched; let onion = hs::onion_string(&svc)?; let inbox = file::Inbox::new(home.join("inbox")); + let store = Arc::new(Mutex::new(store)); + let outbox = Arc::new(Outbox::new( + Arc::clone(&store), + Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())), + )); + if let Err(e) = outbox.reset_stale() { + eprintln!("outbox: {e}"); + } let node = Arc::new(Self { home, - store: Mutex::new(store), + store, client, hs: Mutex::new(None), onion: Mutex::new(onion.clone()), @@ -89,7 +112,12 @@ impl Node { wallet: Wallet::from_env(), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), + outbox: Arc::clone(&outbox), + _outbox_worker: WorkerHandle(outbox.spawn_worker()), }); + // Unlock trigger: flush anything queued by a previous run now, in the + // background, rather than waiting out its backoff. + spawn_flush_all(Arc::clone(&node.outbox)); // Accept rens before waiting so a reachability probe can succeed // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); @@ -416,6 +444,8 @@ impl Node { self.try_send(&onion, friend_pk, &prekey, plaintext).await } + /// Dial a peer's onion. Success is evidence the peer is up, which is one of + /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { tokio::time::timeout( Duration::from_secs(20), @@ -424,6 +454,14 @@ impl Node { .await .map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))? .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + if let Ok(Some(friend)) = self + .store + .lock() + .map_err(|e| e.to_string()) + .and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string())) + { + spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey); + } Ok(()) } @@ -506,36 +544,30 @@ impl Node { Ok(name) } - pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { - let (onion, prekey) = { - let store = self.store.lock().map_err(|e| e.to_string())?; - let f = store - .get_friend(friend_pk) - .map_err(|e| e.to_string())? - .ok_or_else(|| "unknown friend".to_string())?; - if f.prekey.len() != 32 { - return Err("friend missing prekey".into()); - } - (f.onion, f.prekey) - }; - let deadline = Instant::now() + Duration::from_secs(180); - let mut last = None::; - while Instant::now() < deadline { - match self.try_send(&onion, friend_pk, &prekey, plaintext).await { - Ok(()) => { - self.store - .lock() - .map_err(|e| e.to_string())? - .append_message(friend_pk, "out", plaintext) - .map_err(|e| e.to_string())?; - return Ok(()); - } - Err(e) if e.contains("fingerprint mismatch") => return Err(e), - Err(e) => last = Some(e), - } - tokio::time::sleep(Duration::from_secs(3)).await; - } - Err(last.unwrap_or_else(|| "send timed out".into())) + /// Send one chat message. Returns `Sent` when it went out now and `Queued` + /// when the peer's onion is unreachable — the outbox worker then retries with + /// backoff. A real protocol error (signature mismatch, unknown/short/oversize + /// frame) still fails immediately and is never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.outbox.send(friend_pk, plaintext).await + } + + /// Pending and failed outbox rows for a friend, for UI surfacing. + /// Delivered rows are dropped, so a message absent here was sent. + pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result, String> { + self.outbox.pending(friend_pk) + } + + pub fn outbox_status_of_message( + &self, + message_id: i64, + ) -> Result, String> { + self.outbox.status_of_message(message_id) + } + + /// Foreground/unlock trigger: try every outstanding queued send now. + pub fn flush_outbox(&self) { + spawn_flush_all(Arc::clone(&self.outbox)); } async fn push_loc( @@ -568,20 +600,10 @@ impl Node { remote_prekey: &[u8], plaintext: &[u8], ) -> Result<(), String> { - let mut stream = self - .client - .connect((onion, HS_PORT)) + self.outbox + .deliverer() + .deliver(onion, pinned_id, remote_prekey, plaintext) .await - .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; - let keys = self.keys()?; - let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey) - .await - .map_err(session_err)?; - let ct = sess.encrypt(plaintext).map_err(session_err)?; - frame::write_frame(&mut stream, &ct) - .await - .map_err(|e| e.to_string())?; - Ok(()) } async fn handle_incoming(&self, stream: &mut S) -> Result<(), String> @@ -598,6 +620,9 @@ impl Node { }) .await .map_err(session_err)?; + // Trigger (c): the peer just proved they are online. Try their queued + // sends now instead of waiting out the backoff, off this stream's path. + spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone()); let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?; let pt = sess.decrypt(&ct).map_err(session_err)?; match dispatch::classify(&pt) { @@ -814,6 +839,24 @@ fn spawn_rend( }) } +/// Foreground/unlock flush: every outstanding queued send gets one attempt now. +fn spawn_flush_all(outbox: Arc) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_all(unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + +/// We just saw this peer (handshake or successful dial): try their queue now. +fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") diff --git a/src/outbox.rs b/src/outbox.rs new file mode 100644 index 0000000..495e63e --- /dev/null +++ b/src/outbox.rs @@ -0,0 +1,308 @@ +//! Local-only outbox. +//! +//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and +//! retried by a background worker with exponential backoff. There is no server +//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake +//! straight to the friend's onion, so a queued message is never handed to a +//! third party. File transfer and payment frames stay fail-closed — only chat +//! goes through here. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tokio::sync::Notify; + +use crate::frame; +use crate::hs::{Client, HS_PORT}; +use crate::session::{self, Keys}; +use crate::store::Store; + +pub use crate::store::{OutboxEntry, OutboxStatus}; + +/// First retry waits this long. +pub const BACKOFF_START_SECS: i64 = 30; +/// Backoff never sleeps longer than this. +pub const BACKOFF_CAP_SECS: i64 = 1_800; +/// Attempts after which a queued message is terminally `Failed`. +pub const DEFAULT_MAX_ATTEMPTS: u32 = 8; +/// Worker scan period. The shortest backoff is 30s, so a slower scan still +/// lands each retry close to its schedule without busy-waiting. +pub const WORKER_TICK: Duration = Duration::from_secs(15); +/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the +/// worker. +const MAX_PER_PASS: i64 = 32; + +pub type BoxFut<'a, T> = Pin + Send + 'a>>; + +/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s… +/// capped at 30 min. `attempt` is the number of retries already made. +pub fn backoff_secs(attempt: u32) -> i64 { + // 30 << 16 is the largest shift we ever need to reach the cap, so this + // cannot overflow even for a silly attempt count. + (BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS) +} + +/// Protocol failures: another attempt cannot fix a bad signature, a bad frame +/// header, or an oversize payload, so they must fail loudly and never queue. +const PERMANENT_ERRORS: &[&str] = &[ + "fingerprint mismatch", + "bad identity proof", + "unexpected handshake payload", + "frame too large", + "bad version", + "length mismatch", + "short frame", +]; + +pub fn is_permanent_send_error(err: &str) -> bool { + PERMANENT_ERRORS.iter().any(|p| err.contains(p)) +} + +/// One delivery attempt. Implemented by Arti for real sends and by tests for a +/// fake or flaky peer. +pub trait Deliverer: Send + Sync { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>>; +} + +/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's +/// identity key, send exactly one application frame, drop the circuit. +pub struct ArtiDeliverer { + client: Client, + keys: Keys, +} + +impl ArtiDeliverer { + pub fn new(client: Client, keys: Keys) -> Self { + Self { client, keys } + } +} + +impl Deliverer for ArtiDeliverer { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + Box::pin(async move { + let mut stream = self + .client + .connect((onion, HS_PORT)) + .await + .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + let mut sess = + session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey) + .await + .map_err(|e| e.into_message())?; + let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?; + frame::write_frame(&mut stream, &ct) + .await + .map_err(|e| e.to_string())?; + Ok(()) + }) + } +} + +pub struct Outbox { + store: Arc>, + deliverer: Arc, + max_attempts: u32, + wake: Notify, +} + +impl Outbox { + pub fn new(store: Arc>, deliverer: Arc) -> Self { + Self { + store, + deliverer, + max_attempts: DEFAULT_MAX_ATTEMPTS, + wake: Notify::new(), + } + } + + pub fn with_max_attempts(mut self, max: u32) -> Self { + self.max_attempts = max.max(1); + self + } + + /// The transport, for callers (locator/profile pushes) that stay fail-closed + /// and must not queue. + pub fn deliverer(&self) -> &dyn Deliverer { + self.deliverer.as_ref() + } + + /// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is + /// unreachable, the message is persisted and will be retried. `Err` — a + /// protocol error or a bad local state, never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + let (onion, prekey) = self.target(friend_pk)?; + match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await { + Ok(()) => { + self.store()?.append_message(friend_pk, "out", plaintext)?; + Ok(OutboxStatus::Sent) + } + Err(e) if is_permanent_send_error(&e) => Err(e), + Err(e) => { + let now = unix_now(); + let store = self.store()?; + let message_id = store.append_message_id(friend_pk, "out", plaintext)?; + store.enqueue_outbox( + friend_pk, + message_id, + 1, + now + backoff_secs(0), + &e, + now, + )?; + Ok(OutboxStatus::Queued) + } + } + } + + /// Timer trigger: every row whose backoff has elapsed gets one attempt. + pub async fn tick(&self, now: i64) -> Result, String> { + let due = self.store()?.due_outbox(now, MAX_PER_PASS)?; + self.attempt(due, now).await + } + + /// Unlock / foreground trigger: every outstanding row gets one attempt now, + /// regardless of where it sits in the backoff. + pub async fn flush_all(&self, now: i64) -> Result, String> { + let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?; + self.attempt(rows, now).await + } + + /// Trigger (c): we just heard from this peer, so try their rows immediately. + pub async fn flush_friend( + &self, + friend_pk: &[u8], + now: i64, + ) -> Result, String> { + let rows = self.store()?.outbox_for_friend(friend_pk)?; + self.attempt(rows, now).await + } + + /// Pending and failed rows for one friend. Delivered rows are deleted, so a + /// message that is not here was either sent first try or flushed since. + pub fn pending(&self, friend_pk: &[u8]) -> Result, String> { + self.store()?.pending_outbox(friend_pk).map_err(store_err) + } + + pub fn status_of_message(&self, message_id: i64) -> Result, String> { + self.store()? + .outbox_status_of_message(message_id) + .map_err(store_err) + } + + /// A process that died mid-attempt leaves `sending` rows behind; requeue + /// them on unlock so they are retried instead of stranded. + pub fn reset_stale(&self) -> Result { + self.store()?.reset_sending_outbox().map_err(store_err) + } + + /// Wake the worker (e.g. after `flush_all` was queued from a UI thread). + pub fn kick(&self) { + self.wake.notify_one(); + } + + /// Background retry worker. Aborted by dropping the returned handle. + pub fn spawn_worker(self: &Arc) -> tokio::task::JoinHandle<()> { + let me = Arc::clone(self); + tokio::spawn(async move { + loop { + if let Err(e) = me.tick(unix_now()).await { + eprintln!("outbox: {e}"); + } + tokio::select! { + _ = tokio::time::sleep(WORKER_TICK) => {} + _ = me.wake.notified() => {} + } + } + }) + } + + async fn attempt( + &self, + rows: Vec, + now: i64, + ) -> Result, String> { + let mut out = Vec::with_capacity(rows.len()); + for entry in rows { + self.store()?.mark_outbox_sending(entry.id, now)?; + let (onion, prekey) = match self.target(&entry.friend_pk) { + Ok(t) => t, + Err(e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + out.push((entry.id, OutboxStatus::Failed(e))); + continue; + } + }; + let result = self + .deliverer + .deliver(&onion, &entry.friend_pk, &prekey, &entry.body) + .await; + let status = match result { + Ok(()) => { + self.store()?.mark_outbox_sent(entry.id)?; + OutboxStatus::Sent + } + Err(e) if is_permanent_send_error(&e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } + Err(e) => { + let attempts = entry.attempts.saturating_add(1); + if attempts >= self.max_attempts { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } else { + let next = now + backoff_secs(attempts - 1); + self.store()? + .mark_outbox_retry(entry.id, attempts, next, now, &e)?; + OutboxStatus::Queued + } + } + }; + out.push((entry.id, status)); + } + Ok(out) + } + + /// Friend's current locator + Noise static. Missing prekey means the invite + /// was never completed — retrying cannot fix that, so it is fatal. + fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec), String> { + let store = self.store()?; + let f = store + .get_friend(friend_pk) + .map_err(store_err)? + .ok_or_else(|| "unknown friend".to_string())?; + if f.prekey.len() != 32 { + return Err("friend missing prekey".into()); + } + Ok((f.onion, f.prekey)) + } + + fn store(&self) -> Result, String> { + self.store.lock().map_err(|e| e.to_string()) + } +} + +fn store_err(e: crate::store::Error) -> String { + e.to_string() +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} diff --git a/src/pay.rs b/src/pay.rs index ae17390..21485fb 100644 --- a/src/pay.rs +++ b/src/pay.rs @@ -1,5 +1,6 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use sha3::{Digest, Keccak256}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -386,9 +387,12 @@ fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec { } fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result> { - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + // ed25519-dalek's `SigningKey` wipes itself on drop (its default `zeroize` + // feature); the raw copy we make to build it is ours to wipe. + let sk_bytes = Zeroizing::new( + <[u8; 32]>::try_from(identity_sk) + .map_err(|_| Error("identity secret key must be 32 bytes".into()))?, + ); let sk = SigningKey::from_bytes(&sk_bytes); Ok(sk.sign(msg).to_bytes().to_vec()) } diff --git a/src/profile.rs b/src/profile.rs index a22d0ef..8a8ac24 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -1,4 +1,5 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> { check_fields(display_name, bio, xmr_addr) } +/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to +/// build a `SigningKey`. +/// +/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature); +/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather +/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes` +/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it +/// used to make. +pub fn signing_key_bytes(identity_sk: &[u8]) -> Result> { + if identity_sk.len() != 32 { + return Err(Error("identity secret key must be 32 bytes".into())); + } + let mut bytes = Zeroizing::new([0u8; 32]); + bytes[..].copy_from_slice(identity_sk); + Ok(bytes) +} + pub fn sign( identity_sk: &[u8], display_name: &str, @@ -38,9 +56,7 @@ pub fn sign( ts: i64, ) -> Result { check_fields(display_name, bio, xmr_addr)?; - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + let sk_bytes = signing_key_bytes(identity_sk)?; let sk = SigningKey::from_bytes(&sk_bytes); let sig = sk .sign(&sign_msg_v2(display_name, bio, xmr_addr, ts)) diff --git a/src/qr.rs b/src/qr.rs index 4a5e365..3746775 100644 --- a/src/qr.rs +++ b/src/qr.rs @@ -1,4 +1,5 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -34,9 +35,10 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result::try_from(identity_sk) + .map_err(|_| Error("identity secret key must be 32 bytes".into()))?, + ); let sk = SigningKey::from_bytes(&sk_bytes); let k = to_hex(&sk.verifying_key().to_bytes()); let spk = to_hex(signed_prekey); diff --git a/src/session.rs b/src/session.rs index e5e21b6..2e23022 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2,6 +2,7 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use rand::rngs::OsRng; use snow::Builder; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use crate::store::SelfIdentity; @@ -35,6 +36,16 @@ impl Error { pub fn is_fingerprint_mismatch(&self) -> bool { self.mismatch } + + /// String for the UI: a pinned-identity mismatch gets the documented banner, + /// everything else is the underlying snow/framing message. + pub fn into_message(self) -> String { + if self.mismatch { + crate::tui::fingerprint_mismatch_banner().to_string() + } else { + self.msg + } + } } impl std::fmt::Display for Error { @@ -51,11 +62,15 @@ impl From for Error { } } -#[derive(Clone)] +/// Local secret keys. `Clone` copies the secrets, but the copy is itself +/// `ZeroizeOnDrop`, so no clone outlives its owner un-wiped. +#[derive(Clone, Zeroize, ZeroizeOnDrop)] pub struct Keys { pub identity_sk: [u8; 32], + #[zeroize(skip)] pub identity_pk: [u8; 32], pub prekey_sk: [u8; 32], + #[zeroize(skip)] pub prekey_pk: [u8; 32], } @@ -121,7 +136,7 @@ pub fn handshake_pinned(init: &Keys, resp: &Keys, pinned: &[u8; 32]) -> Result<( .prologue(PROLOGUE)? .build_responder()?; - let mut buf = vec![0u8; MSG_BUF]; + let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); let n = initiator.write_message(&[], &mut buf)?; let msg1 = buf[..n].to_vec(); let n = responder.read_message(&msg1, &mut buf)?; @@ -190,7 +205,7 @@ where .prologue(PROLOGUE)? .build_initiator()?; - let mut buf = vec![0u8; MSG_BUF]; + let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); let n = hs.write_message(&[], &mut buf)?; crate::frame::write_frame(stream, &buf[..n]) .await @@ -244,7 +259,7 @@ where .prologue(PROLOGUE)? .build_responder()?; - let mut buf = vec![0u8; MSG_BUF]; + let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]); let msg1 = crate::frame::read_frame(stream) .await .map_err(|e| Error::new(e.to_string()))?; diff --git a/src/store.rs b/src/store.rs index 1be94f3..a90666f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,4 +1,5 @@ use std::fs; +use std::io::Read; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -8,6 +9,7 @@ use rand::RngCore; use rand::rngs::OsRng; use rusqlite::{Connection, OptionalExtension, params}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -40,16 +42,26 @@ impl From for Error { } } -pub struct Store { - conn: Connection, - msg_key: [u8; 32], +/// The store error is a message and nothing else, and the rest of the crate +/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the +/// outbox boundary — no per-call `map_err`. +impl From for String { + fn from(e: Error) -> Self { + e.0 + } } +pub struct Store { + conn: Connection, + msg_key: Zeroizing<[u8; 32]>, +} + +/// The identity row. Secret halves wipe when this is dropped. pub struct SelfIdentity { - pub identity_sk: Vec, + pub identity_sk: Zeroizing>, pub identity_pk: Vec, pub onion: String, - pub prekey_sk: Vec, + pub prekey_sk: Zeroizing>, pub prekey_pk: Vec, } @@ -88,6 +100,64 @@ pub struct Payment { pub created_at: i64, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutboxStatus { + Queued, + Sending, + Sent, + /// Terminal: transport or protocol failure that will not be retried. + Failed(String), +} + +impl OutboxStatus { + pub fn is_terminal(&self) -> bool { + matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_)) + } + + /// Column encoding for the `outbox.status` CHECK constraint. + pub fn as_db_str(&self) -> &'static str { + match self { + OutboxStatus::Queued => "queued", + OutboxStatus::Sending => "sending", + OutboxStatus::Sent => "sent", + OutboxStatus::Failed(_) => "failed", + } + } + + pub fn from_db(status: &str, last_error: Option<&str>) -> Self { + match status { + "sending" => OutboxStatus::Sending, + "sent" => OutboxStatus::Sent, + "failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()), + _ => OutboxStatus::Queued, + } + } +} + +impl std::fmt::Display for OutboxStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + OutboxStatus::Failed(why) => write!(f, "failed: {why}"), + other => f.write_str(other.as_db_str()), + } + } +} + +/// One queued chat send. The body is not copied: it lives in the `messages` +/// row the outbox row points at, under that row's own AEAD. +#[derive(Debug, Clone)] +pub struct OutboxEntry { + pub id: i64, + pub friend_pk: Vec, + pub message_id: i64, + pub body: Vec, + pub attempts: u32, + pub next_attempt_at: i64, + pub created_at: i64, + pub status: OutboxStatus, + pub last_error: Option, +} + pub struct PaymentWrite<'a> { pub dir: &'a str, pub kind: &'a str, @@ -108,7 +178,8 @@ impl Store { } pub fn open_at(home: &Path) -> Result { - Self::open_at_with_passphrase(home, &passphrase_from_env()?) + let passphrase = passphrase_from_env()?; + Self::open_at_with_passphrase(home, passphrase.as_str()) } pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result { @@ -119,7 +190,7 @@ impl Store { mkdir_700(&home.join("arti"))?; mkdir_700(&home.join("cache"))?; let db_path = home.join("onionwire.db"); - let conn = Connection::open(&db_path)?; + let conn = open_store_db(home, &db_path, passphrase)?; 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}"))); @@ -189,6 +260,18 @@ impl Store { verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); + CREATE TABLE IF NOT EXISTS outbox ( + id INTEGER PRIMARY KEY, + friend_id INTEGER NOT NULL REFERENCES friends(id), + message_id INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at INTEGER NOT NULL, + status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')), + last_error TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at); INSERT OR IGNORE INTO self_profile (id) VALUES (1); ", )?; @@ -198,7 +281,7 @@ impl Store { } let mut store = Self { conn, - msg_key: [0u8; 32], + msg_key: Zeroizing::new([0u8; 32]), }; store.migrate()?; store.ensure_self()?; @@ -274,8 +357,11 @@ impl Store { match row { Some((salt, wrapped)) => { let wrap_key = crate::backup::kdf(passphrase, &salt)?; - let raw = crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") - .map_err(|_| Error("wrong passphrase".into()))?; + // The unwrapped data key lands in a Zeroizing buffer immediately. + let raw = Zeroizing::new( + crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") + .map_err(|_| Error("wrong passphrase".into()))?, + ); if raw.len() != 32 { return Err(Error("wrapped message key length".into())); } @@ -284,12 +370,12 @@ impl Store { Ok(()) } None => { - let mut data_key = [0u8; 32]; - OsRng.fill_bytes(&mut data_key); + let mut data_key = Zeroizing::new([0u8; 32]); + OsRng.fill_bytes(&mut data_key[..]); let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut salt); let wrap_key = crate::backup::kdf(passphrase, &salt)?; - let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key, b"")?; + let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?; self.conn.execute( "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", params![salt.as_slice(), wrapped], @@ -383,13 +469,13 @@ impl Store { })?; if exists == 0 { let signing = SigningKey::generate(&mut OsRng); - let sk = signing.to_bytes().to_vec(); + let sk = Zeroizing::new(signing.to_bytes().to_vec()); let pk = signing.verifying_key().to_bytes().to_vec(); let (psk, ppk) = gen_prekey(); self.conn.execute( "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')", - params![sk, pk, psk, ppk], + params![&sk[..], pk, &psk[..], ppk], )?; } else { let empty: i64 = self.conn.query_row( @@ -401,7 +487,7 @@ impl Store { let (psk, ppk) = gen_prekey(); self.conn.execute( "UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1", - params![psk, ppk], + params![&psk[..], ppk], )?; } } @@ -415,10 +501,10 @@ impl Store { [], |row| { Ok(SelfIdentity { - identity_sk: row.get(0)?, + identity_sk: Zeroizing::new(row.get(0)?), identity_pk: row.get(1)?, onion: row.get(2)?, - prekey_sk: row.get(3)?, + prekey_sk: Zeroizing::new(row.get(3)?), prekey_pk: row.get(4)?, }) }, @@ -475,6 +561,20 @@ impl Store { .map_err(Into::into) } + /// Locator → friend. Onions are not unique in the schema (a stale row can + /// hold a rotated address), so the first match wins; the outbox uses this + /// only to pick which queue to flush early. + pub fn friend_by_onion(&self, onion: &str) -> Result> { + self.conn + .query_row( + "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1", + params![onion], + friend_from_row, + ) + .optional() + .map_err(Into::into) + } + pub fn list_friends(&self) -> Result> { let mut stmt = self.conn.prepare( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends @@ -699,6 +799,17 @@ impl Store { } pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { + self.append_message_id(friend_pk, dir, plaintext).map(|_| ()) + } + + /// Same as `append_message`, returning the row id so an outbox row can + /// point at the body instead of storing a second copy. + pub fn append_message_id( + &self, + friend_pk: &[u8], + dir: &str, + plaintext: &[u8], + ) -> Result { if dir != "in" && dir != "out" { return Err(Error("dir must be in or out".into())); } @@ -723,7 +834,7 @@ impl Store { params![blob, row_id], )?; tx.commit()?; - Ok(()) + Ok(row_id) } pub fn list_messages(&self, friend_pk: &[u8]) -> Result> { @@ -752,9 +863,194 @@ impl Store { Ok(out) } + /// Queue one already-stored chat message for retry. `next_attempt_at` is an + /// absolute unix second; `now` is used for created_at/updated_at so the + /// caller and the row agree on the clock. + pub fn enqueue_outbox( + &self, + friend_pk: &[u8], + message_id: i64, + attempts: u32, + next_attempt_at: i64, + last_error: &str, + now: i64, + ) -> Result { + let friend_id: i64 = self + .conn + .query_row( + "SELECT id FROM friends WHERE pubkey = ?1", + params![friend_pk], + |row| row.get(0), + ) + .map_err(|_| Error("friend not found".into()))?; + self.conn.execute( + "INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)", + params![friend_id, message_id, attempts, next_attempt_at, last_error, now], + )?; + Ok(self.conn.last_insert_rowid()) + } + + /// Rows whose backoff has elapsed: the timer trigger for the worker. + pub fn due_outbox(&self, now: i64, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1 + ORDER BY o.next_attempt_at, o.id LIMIT ?2" + ), + params![now, limit], + ) + } + + /// Unscheduleable rows for one friend (queued or mid-attempt): the + /// "we just heard from this peer" trigger, which ignores the backoff. + pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + /// Every row the worker may still try: the unlock/foreground trigger. + pub fn all_pending_outbox(&self, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status IN ('queued','sending') + ORDER BY o.next_attempt_at, o.id LIMIT ?1" + ), + params![limit], + ) + } + + /// Pending and failed rows for one friend — what a UI shows as not-yet-sent. + /// Delivered rows are deleted, so absence means "sent". + pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + pub fn outbox_status_of_message(&self, message_id: i64) -> Result> { + let row: Option<(String, Option)> = self + .conn + .query_row( + "SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1", + params![message_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref()))) + } + + pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2", + params![now, id], + )?; + Ok(()) + } + + /// Delivered. The row is dropped — the chat history is the record, and a + /// per-message status table would grow without bound. + pub fn mark_outbox_sent(&self, id: i64) -> Result<()> { + self.conn + .execute("DELETE FROM outbox WHERE id = ?1", params![id])?; + Ok(()) + } + + pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3", + params![why, now, id], + )?; + Ok(()) + } + + pub fn mark_outbox_retry( + &self, + id: i64, + attempts: u32, + next_attempt_at: i64, + now: i64, + why: &str, + ) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5", + params![attempts, next_attempt_at, why, now, id], + )?; + Ok(()) + } + + /// A row left in 'sending' means we died mid-attempt. Requeue on unlock. + pub fn reset_sending_outbox(&self) -> Result { + let n = self.conn.execute( + "UPDATE outbox SET status = 'queued' WHERE status = 'sending'", + [], + )?; + Ok(n) + } + + fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { + let mut stmt = self.conn.prepare(sql)?; + let rows = stmt.query_map(args, |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, Vec>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, i64>(3)?, + row.get::<_, i64>(4)?, + row.get::<_, String>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, i64>(7)?, + row.get::<_, i64>(8)?, + row.get::<_, String>(9)?, + row.get::<_, Vec>(10)?, + )) + })?; + let mut out = Vec::new(); + for row in rows { + let ( + id, + friend_pk, + message_id, + attempts, + next_attempt_at, + status, + last_error, + created_at, + m_friend_id, + dir, + blob, + ) = row?; + let aad = message_aad(m_friend_id, &dir, message_id); + let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) + .map_err(|_| Error("outbox body decrypt failed".into()))?; + out.push(OutboxEntry { + id, + friend_pk, + message_id, + body, + attempts: attempts as u32, + next_attempt_at, + created_at, + status: OutboxStatus::from_db(&status, last_error.as_deref()), + last_error, + }); + } + Ok(out) + } + /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { + self.conn.execute("DELETE FROM outbox", [])?; self.conn.execute( "UPDATE messages SET plaintext = zeroblob(length(plaintext))", [], @@ -809,10 +1105,194 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { }) } -fn gen_prekey() -> (Vec, Vec) { +fn gen_prekey() -> (Zeroizing>, Vec) { let sk = StaticSecret::random_from_rng(OsRng); let pk = X25519Public::from(&sk); - (sk.to_bytes().to_vec(), pk.to_bytes().to_vec()) + (Zeroizing::new(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).as_str())?; + // 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) +} + +/// SQLCipher's key material as hex inside the pragma text. The `String` holds +/// the database key, so it wipes on drop. +fn pragma_key(key: &[u8; 32]) -> Zeroizing { + Zeroizing::new(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('\'', "''"); + let attach = Zeroizing::new(format!( + "ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";", + hex = fingerprint(key) + )); + conn.execute_batch(attach.as_str())?; + 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 { @@ -823,29 +1303,29 @@ fn home_dir() -> Result { Ok(PathBuf::from(home).join(".local/share/onionwire")) } -fn passphrase_from_env() -> Result { +fn passphrase_from_env() -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), - Ok(p) => Ok(p), + Ok(p) => Ok(Zeroizing::new(p)), Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())), } } /// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret` -/// (TTY, no echo). Empty values fail closed. +/// (TTY, no echo). Empty values fail closed. The passphrase is wiped on drop. pub fn resolve_store_passphrase( read_secret: impl FnOnce(&str) -> std::io::Result, -) -> Result { +) -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), - Ok(p) => Ok(p), + Ok(p) => Ok(Zeroizing::new(p)), Err(_) => { let s = read_secret("onionwire: store passphrase: ")?; let s = s.trim_end_matches(['\n', '\r']).to_string(); if s.is_empty() { Err(Error("empty passphrase".into())) } else { - Ok(s) + Ok(Zeroizing::new(s)) } } } @@ -859,6 +1339,12 @@ fn mkdir_700(path: &Path) -> Result<()> { Ok(()) } +/// Base projection for outbox rows: the body comes from the `messages` row the +/// outbox row points at, so it stays under that row's AEAD + AAD. +const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \ + o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \ + FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id"; + /// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64 fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec { let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8); @@ -884,6 +1370,21 @@ fn fingerprint(pubkey: &[u8]) -> String { #[cfg(test)] mod at_rest { use super::*; + use zeroize::Zeroize; + + #[test] + fn store_data_key_is_a_zeroizing_wrapper_that_wipes() { + let dir = tempfile::tempdir().unwrap(); + let mut store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").unwrap(); + + // Type-level: the field is `Zeroizing<[u8; 32]>`, so its Drop wipes it. + let _: &Zeroizing<[u8; 32]> = &store.msg_key; + let before = *store.msg_key; + assert_ne!(before, [0u8; 32], "store has no data key"); + + store.msg_key.zeroize(); + assert_eq!(*store.msg_key, [0u8; 32], "store data key not wiped"); + } #[test] fn swapped_ciphertext_does_not_show_other_friends_body() { @@ -1027,6 +1528,214 @@ 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 = Zeroizing::new([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/src/tui.rs b/src/tui.rs index 20eb4b6..090e1a7 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -8,6 +8,7 @@ use ratatui::style::{Color, Modifier, Style}; use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; +use zeroize::{Zeroize, Zeroizing}; use crate::node::Node; use crate::qr::{self, QrPayload}; @@ -761,6 +762,78 @@ impl BackupPrompt { } } +/// The in-progress passphrase on the backup/restore screen: the hidden buffer +/// plus the first entry, kept across the second prompt of the backup flow. +/// +/// Both are `Zeroizing`, so the passphrase does not sit in a plain +/// heap `String` for the life of the screen; `close()` wipes eagerly on every +/// exit path (submit, mismatch, cancel) instead of waiting for the screen +/// value to be dropped, and the wrapper covers the paths that cannot call it +/// (Ctrl-Q, a panic). +pub struct PassphraseEntry { + first: Option>, + buf: Zeroizing, +} + +impl Default for PassphraseEntry { + fn default() -> Self { + Self { + first: None, + buf: Zeroizing::new(String::new()), + } + } +} + +impl PassphraseEntry { + pub fn new() -> Self { + Self::default() + } + + /// Second prompt of the backup flow: the first passphrase was already typed. + pub fn with_first(first: &str) -> Self { + Self { + first: Some(Zeroizing::new(first.to_string())), + ..Self::default() + } + } + + pub fn push(&mut self, c: char) { + self.buf.push(c); + } + + pub fn backspace(&mut self) { + self.buf.pop(); + } + + /// What the screen echoes back — the passphrase itself is not drawn. + pub fn buf(&self) -> &str { + self.buf.as_str() + } + + pub fn first(&self) -> Option<&str> { + self.first.as_deref().map(String::as_str) + } + + /// Take the typed passphrase for submission, leaving this entry empty. + pub fn take_buf(&mut self) -> Zeroizing { + std::mem::replace(&mut self.buf, Zeroizing::new(String::new())) + } + + /// Take the first-passphrase copy for the confirm comparison. + pub fn take_first(&mut self) -> Option> { + self.first.take() + } + + /// Wipe both buffers: the screen is done with them. + pub fn close(&mut self) { + self.buf.zeroize(); + if let Some(first) = self.first.as_mut() { + first.zeroize(); + } + self.first = None; + } +} + pub fn backup_screen_text() -> &'static str { "Write encrypted identity backup?\n\ This file is your identity secret. Treat it like the database.\n\ @@ -840,8 +913,7 @@ enum Screen { Passphrase { kind: BackupKind, path: String, - first: Option, - buf: String, + entry: PassphraseEntry, }, Quit { prompt: QuitPrompt, @@ -929,6 +1001,7 @@ impl App { let mut tip_cmd = None; let mut file_cmd = None; let mut chat_send = None; + let mut pass_submit = None; match &mut self.screen { Screen::Main => match key.code { KeyCode::Tab => self.focus = self.focus.next(), @@ -1090,8 +1163,7 @@ impl App { self.screen = Screen::Passphrase { kind, path: path.clone(), - first: None, - buf: String::new(), + entry: PassphraseEntry::new(), }; } } @@ -1101,25 +1173,17 @@ impl App { _ => {} } } - Screen::Passphrase { - kind, - path, - first, - buf, - } => match key.code { - KeyCode::Esc => self.screen = Screen::Main, - KeyCode::Backspace => { - buf.pop(); + Screen::Passphrase { kind, path, entry } => match key.code { + KeyCode::Esc => { + entry.close(); + self.screen = Screen::Main; } + KeyCode::Backspace => entry.backspace(), KeyCode::Enter => { - let kind = *kind; - let path = path.clone(); - let first = first.clone(); - let pass = buf.clone(); - self.submit_passphrase(kind, &path, first.as_deref(), &pass)?; + pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf())); } KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { - buf.push(c); + entry.push(c); } _ => {} }, @@ -1166,6 +1230,9 @@ impl App { if let Some(text) = chat_send { self.send_chat(&text)?; } + if let Some((kind, path, first, pass)) = pass_submit { + self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?; + } Ok(None) } @@ -1279,8 +1346,7 @@ impl App { self.screen = Screen::Passphrase { kind, path: path.to_string(), - first: Some(pass.to_string()), - buf: String::new(), + entry: PassphraseEntry::with_first(pass), }; } } @@ -1449,8 +1515,10 @@ impl App { let (tx, rx) = mpsc::channel(); self.status_note = Some("sending".into()); std::mem::drop(self.rt.spawn(async move { + // send() now reports `Sent`/`Queued`; surfacing `queued` in the + // footer is a follow-up card, so this arm keeps today's wording. let note = match node.send(&pk, &body).await { - Ok(()) => "sent".to_string(), + Ok(_) => "sent".to_string(), Err(e) => format!("send failed: {e}"), }; let _ = tx.send(note); @@ -1485,9 +1553,9 @@ impl App { Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()), Screen::Profile { editor } => draw_profile(f, editor), Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()), - Screen::Passphrase { - kind, first, buf, .. - } => draw_passphrase(f, *kind, first.is_some(), buf), + Screen::Passphrase { kind, entry, .. } => { + draw_passphrase(f, *kind, entry.first().is_some(), entry.buf()) + } Screen::Quit { prompt } => draw_quit(f, prompt.typed()), } if self.help_open { @@ -2015,3 +2083,66 @@ fn to_hex(bytes: &[u8]) -> String { fn io_err(e: io::Error) -> String { e.to_string() } + +#[cfg(test)] +mod passphrase_buffer_tests { + use super::*; + + fn assert_zeroize_on_drop() {} + + /// The typed passphrase lives in `Zeroizing` buffers, not in bare + /// `String`s that sit in the heap for the life of the screen. + #[test] + fn passphrase_buffers_are_zeroizing() { + let mut entry = PassphraseEntry::new(); + entry.push('x'); + + let _: &Zeroizing = &entry.buf; + let _: &Option> = &entry.first; + assert_zeroize_on_drop::>(); + } + + /// Closing the screen (submit, mismatch or cancel) must leave nothing of + /// the typed passphrase behind in its heap buffer. + #[test] + fn closing_the_passphrase_screen_wipes_the_typed_secret() { + let mut entry = PassphraseEntry::new(); + for c in "hunter2-secret".chars() { + entry.push(c); + } + assert_eq!(entry.buf(), "hunter2-secret"); + + let ptr = entry.buf.as_ptr(); + let cap = entry.buf.capacity(); + assert!(cap >= 14, "expected a heap buffer, capacity {cap}"); + + entry.close(); + + assert!(entry.buf().is_empty(), "buffer not cleared"); + // SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole + // capacity and *keeps* the allocation (`Vec::zeroize`: zero the + // elements, clear the length, zero the spare capacity). `entry` still + // owns that buffer, so these `cap` bytes are live memory. + let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) }; + assert!( + bytes.iter().all(|b| *b == 0), + "typed passphrase survived close(): {bytes:?}" + ); + } + + /// The first entry of the two-step backup flow is a secret too, and the + /// screen holds it across the second prompt. + #[test] + fn closing_the_passphrase_screen_drops_the_first_entry_copy() { + let mut entry = PassphraseEntry::with_first("first-typed"); + assert_eq!(entry.first(), Some("first-typed")); + + entry.close(); + + assert_eq!( + entry.first(), + None, + "first passphrase copy survived close()" + ); + } +} diff --git a/src/wallet.rs b/src/wallet.rs index 9dd574f..1917cd7 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -3,6 +3,7 @@ use std::time::Duration; use rand::RngCore; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -23,7 +24,7 @@ struct Endpoint { port: u16, path: String, user: String, - pass: String, + pass: Zeroizing, } impl std::fmt::Debug for Endpoint { @@ -59,12 +60,15 @@ impl Wallet { pub fn from_env() -> Self { match std::env::var("ONIONWIRE_WALLET_RPC") { + // The URL can carry `user:pass@` in its userinfo: keep it in a + // wiping buffer, not a bare `String`. Ok(s) if !s.trim().is_empty() => { + let url = Zeroizing::new(s); let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN") .ok() - .map(|v| v.trim().to_string()) + .map(|v| Zeroizing::new(v.trim().to_string())) .filter(|v| !v.is_empty()); - match parse_http_url(s.trim(), login.as_deref()) { + match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { Ok(endpoint) => Self { endpoint: Some(endpoint), }, @@ -185,12 +189,12 @@ fn credentials_required() -> Error { Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into()) } -fn parse_login(login: &str) -> Result<(String, String)> { +fn parse_login(login: &str) -> Result<(String, Zeroizing)> { let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; if user.is_empty() || pass.is_empty() { return Err(credentials_required()); } - Ok((user.to_string(), pass.to_string())) + Ok((user.to_string(), Zeroizing::new(pass.to_string()))) } fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result { @@ -405,7 +409,9 @@ fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result { let nonce = digest_param(challenge, "nonce") .ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?; let qop = digest_param(challenge, "qop"); - let ha1 = md5_hex(&format!("{}:{realm}:{}", ep.user, ep.pass)); + // `user:realm:password` never leaves a bare `String` behind. + let pw_input = Zeroizing::new(format!("{}:{realm}:{}", ep.user, ep.pass.as_str())); + let ha1 = md5_hex(pw_input.as_str()); let ha2 = md5_hex(&format!("POST:{}", ep.path)); let (qop_part, resp) = if qop .as_deref() diff --git a/tests/backup.rs b/tests/backup.rs index 37590b6..51ee582 100644 --- a/tests/backup.rs +++ b/tests/backup.rs @@ -72,9 +72,9 @@ fn restore_overwrites_self_keys_friends_stay() { ) .unwrap(); let me = store.self_identity().unwrap(); - assert_eq!(me.identity_sk, incoming.identity_sk); + assert_eq!(me.identity_sk[..], incoming.identity_sk[..]); assert_eq!(me.identity_pk, incoming.identity_pk); - assert_eq!(me.prekey_sk, incoming.prekey_sk); + assert_eq!(me.prekey_sk[..], incoming.prekey_sk[..]); assert_eq!(me.prekey_pk, incoming.prekey_pk); assert_eq!(me.onion, old.onion, "onion is locator, not restored"); assert_eq!(store.friend_count().unwrap(), 1); diff --git a/tests/outbox.rs b/tests/outbox.rs new file mode 100644 index 0000000..3b7cc13 --- /dev/null +++ b/tests/outbox.rs @@ -0,0 +1,312 @@ +//! Local outbox: queue a chat send when the peer's onion is unreachable, retry +//! with exponential backoff, expose a terminal status. All offline — the +//! transport is a fake deliverer, so these run without Tor. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use onionwire::outbox::{ + BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs, + is_permanent_send_error, +}; +use onionwire::Store; + +const PASS: &str = "outbox-pass"; + +fn pk(tag: u8) -> [u8; 32] { + let mut k = [0u8; 32]; + k[0] = tag; + k +} + +/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext. +struct Flaky { + fail_times: AtomicUsize, + err: String, + calls: AtomicUsize, + delivered: Mutex>>, +} + +impl Flaky { + fn new(fail_times: usize, err: &str) -> Arc { + Arc::new(Self { + fail_times: AtomicUsize::new(fail_times), + err: err.into(), + calls: AtomicUsize::new(0), + delivered: Mutex::new(Vec::new()), + }) + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + + fn delivered(&self) -> Vec> { + self.delivered.lock().unwrap().clone() + } +} + +impl Deliverer for Flaky { + fn deliver<'a>( + &'a self, + _onion: &'a str, + _pinned_id: &'a [u8], + _prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + self.calls.fetch_add(1, Ordering::SeqCst); + let left = self.fail_times.load(Ordering::SeqCst); + if left > 0 { + self.fail_times.fetch_sub(1, Ordering::SeqCst); + let err = self.err.clone(); + return Box::pin(async move { Err(err) }); + } + self.delivered.lock().unwrap().push(plaintext.to_vec()); + Box::pin(async move { Ok(()) }) + } +} + +fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc> { + let store = Store::open_at_with_passphrase(dir, PASS).expect("open store"); + store.upsert_friend(&pk(1), onion, None).unwrap(); + store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap(); + Arc::new(Mutex::new(store)) +} + +fn outbox(store: Arc>, deliverer: Arc, max_attempts: u32) -> Outbox { + Outbox::new(store, deliverer).with_max_attempts(max_attempts) +} + +#[test] +fn backoff_schedule_doubles_from_30s_and_caps_at_30m() { + assert_eq!(BACKOFF_START_SECS, 30); + assert_eq!(BACKOFF_CAP_SECS, 1800); + let got: Vec = (0..9).map(backoff_secs).collect(); + assert_eq!( + got, + vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800], + "exponential backoff, capped" + ); + assert_eq!( + backoff_secs(u32::MAX), + BACKOFF_CAP_SECS, + "no overflow at silly attempt counts" + ); +} + +#[test] +fn transport_errors_are_retryable_protocol_errors_are_not() { + assert!(!is_permanent_send_error( + "connect abc.onion:80: timed out" + )); + assert!(!is_permanent_send_error("connect abc.onion:80: refused")); + assert!(is_permanent_send_error("fingerprint mismatch")); + assert!(is_permanent_send_error("frame too large")); + assert!(is_permanent_send_error("bad version")); + assert!(is_permanent_send_error("bad identity proof")); +} + +#[tokio::test] +async fn send_to_dead_onion_is_queued_and_row_persists() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + + let status = ob.send(&pk(1), b"hello dead peer").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err"); + assert!(!status.is_terminal()); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1, "one outbox row"); + assert_eq!(pending[0].status, OutboxStatus::Queued); + assert_eq!(pending[0].attempts, 1, "the immediate attempt counted"); + assert!( + ob.status_of_message(pending[0].message_id).unwrap().is_some(), + "status is addressable by chat row id" + ); + + // The chat line is already in local history while it waits. + let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap(); + assert_eq!(msgs.len(), 1); + assert_eq!(msgs[0].dir, "out"); + assert_eq!(msgs[0].plaintext, b"hello dead peer"); +} + +#[tokio::test] +async fn flaky_peer_is_flushed_by_the_worker_on_schedule() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "flaky.onion"); + // First dial fails (the immediate one), the rest succeed: "peer came up". + let flaky = Flaky::new(1, "connect flaky.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + let status = ob.send(&pk(1), b"late hello").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued); + let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + assert_eq!( + next - ob.pending(&pk(1)).unwrap()[0].created_at, + BACKOFF_START_SECS, + "first retry waits the start of the schedule" + ); + + // Too early: the worker must not dial out of schedule. + let t0 = next - BACKOFF_START_SECS; + let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap(); + assert!(fired.is_empty(), "not due yet"); + + let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "delivered rows leave the pending set" + ); +} + +#[tokio::test] +async fn max_attempts_reaches_failed_and_stops_retrying() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "gone.onion"); + let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead.clone(), 3); + + assert_eq!( + ob.send(&pk(1), b"never lands").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(dead.calls(), 1, "immediate attempt"); + + // Walk the schedule forward; each tick is one more attempt. + let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + let mut last = OutboxStatus::Queued; + for _ in 0..6 { + let fired = ob.tick(now).await.unwrap(); + if let Some((_, st)) = fired.first() { + last = st.clone(); + } + if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) { + break; + } + now += BACKOFF_CAP_SECS; + } + assert_eq!( + last, + OutboxStatus::Failed("connect gone.onion:80: timed out".into()), + "gives up after max_attempts" + ); + assert_eq!(dead.calls(), 3, "attempts stop at the cap"); + + let calls_at_cap = dead.calls(); + for _ in 0..3 { + now += BACKOFF_CAP_SECS; + assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries"); + } + assert_eq!(dead.calls(), calls_at_cap); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1); + assert!(matches!(pending[0].status, OutboxStatus::Failed(_))); + assert!(pending[0].status.is_terminal()); +} + +#[tokio::test] +async fn queued_message_survives_reopen_and_flushes_after_unlock() { + let dir = tempfile::tempdir().unwrap(); + let pk1 = pk(1); + let next_attempt_at = { + let store = store_and_friend(dir.path(), "later.onion"); + let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk1, b"survives restart").await.unwrap(), + OutboxStatus::Queued + ); + ob.pending(&pk1).unwrap()[0].next_attempt_at + }; + + // Process exit: everything above is dropped and the store is reopened. + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + let up = Flaky::new(0, ""); + let ob = outbox(Arc::clone(&store), up.clone(), 8); + let fired = ob.flush_all(next_attempt_at).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]); + assert!(ob.pending(&pk1).unwrap().is_empty()); +} + +#[tokio::test] +async fn protocol_error_fails_immediately_and_is_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "liar.onion"); + let liar = Flaky::new(usize::MAX, "fingerprint mismatch"); + let ob = outbox(Arc::clone(&store), liar, 8); + + let err = ob.send(&pk(1), b"hello liar").await.unwrap_err(); + assert!(err.contains("fingerprint mismatch"), "got {err}"); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "protocol errors are never queued" + ); + assert!( + store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(), + "a failed protocol send is not written to history" + ); +} + +#[tokio::test] +async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "seen.onion"); + let flaky = Flaky::new(1, "connect seen.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + assert_eq!( + ob.send(&pk(1), b"you are back").await.unwrap(), + OutboxStatus::Queued + ); + let now = ob.pending(&pk(1)).unwrap()[0].created_at; + let fired = ob.flush_friend(&pk(1), now).await.unwrap(); + assert_eq!(fired.len(), 1, "a live handshake flushes without waiting"); + assert_eq!(fired[0].1, OutboxStatus::Sent); +} + +#[tokio::test] +async fn wipe_clears_outbox_rows() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk(1), b"wipe me").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1); + + store.lock().unwrap().wipe_messages().unwrap(); + + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "wipe must drop queued sends, not only chat" + ); +} + +#[tokio::test] +async fn missing_prekey_is_fatal_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + { + let s = store.lock().unwrap(); + s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap(); + } + let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8); + let err = ob.send(&pk(2), b"hi").await.unwrap_err(); + assert!(err.contains("prekey"), "got {err}"); + assert!(ob.pending(&pk(2)).unwrap().is_empty()); +} diff --git a/tests/store.rs b/tests/store.rs index 7bc688a..2390261 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -67,7 +67,7 @@ fn first_run_creates_0700_dirs_and_self_row() { let me = store.self_identity().expect("self"); assert_eq!(me.identity_pk.len(), 32); assert_eq!(me.identity_sk.len(), 32); - assert_ne!(me.identity_pk, me.identity_sk); + assert_ne!(me.identity_pk, me.identity_sk.to_vec()); assert_eq!(me.onion, ""); assert_eq!(store.friend_count().unwrap(), 0); @@ -152,7 +152,7 @@ fn self_has_x25519_prekey_and_set_onion() { let me = store.self_identity().unwrap(); assert_eq!(me.prekey_pk.len(), 32); assert_eq!(me.prekey_sk.len(), 32); - assert_ne!(me.prekey_pk, me.prekey_sk); + assert_ne!(me.prekey_pk, me.prekey_sk.to_vec()); store.set_onion("abc.onion").unwrap(); assert_eq!(store.self_identity().unwrap().onion, "abc.onion"); } @@ -233,6 +233,121 @@ 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.to_vec(), "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"); @@ -279,7 +394,7 @@ fn env_passphrase_skips_prompt() { unsafe { std::env::remove_var("ONIONWIRE_STORE_PASSPHRASE"); } - assert_eq!(got.unwrap(), "from-env"); + assert_eq!(got.unwrap().as_str(), "from-env"); assert!(!prompted); } @@ -313,7 +428,7 @@ fn missing_env_reads_secret_and_strips_newline() { Ok("secret-from-tty\n".into()) }) .unwrap(); - assert_eq!(got, "secret-from-tty"); + assert_eq!(got.as_str(), "secret-from-tty"); } #[test] diff --git a/tests/zeroize.rs b/tests/zeroize.rs new file mode 100644 index 0000000..ce77a45 --- /dev/null +++ b/tests/zeroize.rs @@ -0,0 +1,157 @@ +//! Wipe in-memory secrets on drop — keys, not just the file at rest. +//! +//! Not covered here (see the PR body): allocator copies, swap/hibernation, +//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the +//! Noise handshake/transport state that lives inside `snow`. + +use onionwire::backup::BackupKeys; +use onionwire::profile; +use onionwire::session::Keys; +use onionwire::wallet::Wallet; +use onionwire::Store; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; + +/// Type-level: the wrapper is applied to the type, not just mentioned in a +/// comment. Removing the derive breaks the build here. +fn assert_zeroize_on_drop() {} + +#[test] +fn session_and_backup_key_types_are_zeroize_on_drop() { + assert_zeroize_on_drop::(); + assert_zeroize_on_drop::(); +} + +/// Behavioural: the derived impl must wipe the secret halves and leave the +/// public halves alone. A `Zeroize` that only touched the publics would still +/// satisfy a bare drop assertion and leak anyway. +#[test] +fn session_keys_zeroize_wipes_secrets_and_keeps_publics() { + let mut k = Keys::generate(); + let (id_pk, prekey_pk) = (k.identity_pk, k.prekey_pk); + assert_ne!(k.identity_sk, [0u8; 32]); + assert_ne!(k.prekey_sk, [0u8; 32]); + + k.zeroize(); + + assert_eq!(k.identity_sk, [0u8; 32], "identity secret not wiped"); + assert_eq!(k.prekey_sk, [0u8; 32], "prekey secret not wiped"); + assert_eq!(k.identity_pk, id_pk, "identity public key was wiped"); + assert_eq!(k.prekey_pk, prekey_pk, "prekey public key was wiped"); +} + +/// Drops `v` in place and reads its secret field back, so a drop test cannot +/// pass on a copy that the caller still holds. +/// +/// SAFETY: only for `ManuallyDrop` locals — the value is dropped exactly +/// once, at its own address, and its storage is still alive when it is read. +unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] { + let p = std::ptr::addr_of!(v.identity_sk); + // SAFETY: the caller guarantees `v` is a `ManuallyDrop` dropped once. + unsafe { + std::ptr::drop_in_place(v as *mut Keys); + std::ptr::read_volatile(p) + } +} + +/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back. +/// +/// SAFETY: only for `ManuallyDrop>` locals — same contract +/// as `drop_in_place_and_peek_identity_sk`. +unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] { + let p: *const [u8; 32] = &**v; + // SAFETY: the caller guarantees `v` is dropped exactly once and is still + // alive at its own address when read back. + unsafe { + std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>); + std::ptr::read_volatile(p) + } +} + +/// Drop behaviour, not a comment: after the value drops, the local secret key +/// material that feeds the Noise IK handshake is gone from its memory. +#[test] +fn dropped_session_keys_leave_no_secret_behind() { + let mut k = std::mem::ManuallyDrop::new(Keys::generate()); + // SAFETY: `k` is a live local; the pointer targets its own field. + assert_ne!(unsafe { *std::ptr::addr_of!(k.identity_sk) }, [0u8; 32]); + + let after = unsafe { drop_in_place_and_peek_identity_sk(&mut k) }; + + assert_eq!(after, [0u8; 32], "identity secret survived drop"); +} + +/// `Keys` is `Clone`, so a cloned copy is itself live secret material. It must +/// wipe on *its* drop, and dropping it must not wipe the original it came from. +#[test] +fn cloned_session_keys_wipe_their_own_copy_only() { + let original = std::mem::ManuallyDrop::new(Keys::generate()); + let mut copy = std::mem::ManuallyDrop::new((*original).clone()); + + let after = unsafe { drop_in_place_and_peek_identity_sk(&mut copy) }; + assert_eq!(after, [0u8; 32], "cloned secret survived its drop"); + + // SAFETY: `original` is a live local; the pointer targets its own field. + assert_ne!( + unsafe { *std::ptr::addr_of!(original.identity_sk) }, + [0u8; 32], + "dropping the clone wiped the original's key" + ); +} + +/// The identity secret handed out by the store is a `Zeroizing`, not a bare +/// `Vec` that outlives every caller. +#[test] +fn self_identity_secrets_are_zeroizing_and_wipe() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").expect("open"); + let mut me = store.self_identity().expect("self"); + + let _: &Zeroizing> = &me.identity_sk; + let _: &Zeroizing> = &me.prekey_sk; + + assert_eq!(me.identity_sk.len(), 32); + assert!(me.identity_sk.iter().any(|b| *b != 0)); + + me.identity_sk.zeroize(); + me.prekey_sk.zeroize(); + + assert!(me.identity_sk.iter().all(|b| *b == 0)); + assert!(me.prekey_sk.iter().all(|b| *b == 0)); +} + +/// The wallet RPC password is a secret, so it is `Zeroizing` and its `Debug` +/// redacts it instead of printing it. +#[test] +fn wallet_endpoint_debug_redacts_the_rpc_password() { + let w = Wallet::from_url("http://monero:hunter2@127.0.0.1:18083/json_rpc").expect("url"); + let dbg = format!("{w:?}"); + assert!( + !dbg.contains("hunter2"), + "wallet RPC password leaked into Debug: {dbg}" + ); + assert!(dbg.contains(""), "{dbg}"); +} + +/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the +/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that +/// stays on the stack until the function returns. +#[test] +fn profile_signing_key_bytes_are_zeroizing_and_wipe() { + let secret = [0x5au8; 32]; + let bytes = profile::signing_key_bytes(&secret).expect("32 bytes"); + + let _: &Zeroizing<[u8; 32]> = &bytes; + assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret"); + + let mut probe = std::mem::ManuallyDrop::new(bytes); + let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) }; + + assert_eq!(after, [0u8; 32], "identity secret survived its drop"); +} + +/// A length-mismatched secret is an error, not a truncated/padded key. +#[test] +fn profile_signing_key_bytes_rejects_a_short_secret() { + assert!(profile::signing_key_bytes(&[7u8; 31]).is_err()); + assert!(profile::signing_key_bytes(&[7u8; 33]).is_err()); +}